diff --git a/sdk/communication/Azure.Communication.JobRouter/src/Azure.Communication.JobRouter.csproj b/sdk/communication/Azure.Communication.JobRouter/src/Azure.Communication.JobRouter.csproj index b9aca635fe4a..07e9f4cda383 100644 --- a/sdk/communication/Azure.Communication.JobRouter/src/Azure.Communication.JobRouter.csproj +++ b/sdk/communication/Azure.Communication.JobRouter/src/Azure.Communication.JobRouter.csproj @@ -17,7 +17,6 @@ - @@ -27,5 +26,8 @@ + + + diff --git a/sdk/communication/Azure.Communication.JobRouter/src/Generated/JobRouterRestClient.cs b/sdk/communication/Azure.Communication.JobRouter/src/Generated/JobRouterRestClient.cs index 15694ece3888..7d1f1c8a69be 100644 --- a/sdk/communication/Azure.Communication.JobRouter/src/Generated/JobRouterRestClient.cs +++ b/sdk/communication/Azure.Communication.JobRouter/src/Generated/JobRouterRestClient.cs @@ -53,7 +53,8 @@ internal HttpMessage CreateUpsertJobRequest(string id, RouterJob patch) request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/merge-patch+json"); var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(patch); + // TODO: + //content.JsonWriter.WriteObjectValue(patch); request.Content = content; return message; } diff --git a/sdk/communication/Azure.Communication.JobRouter/src/Generated/Models/RouterJob.Serialization.cs b/sdk/communication/Azure.Communication.JobRouter/src/Generated/Models/RouterJob.Serialization.cs index e2009385449a..3c2dc1dd0bd2 100644 --- a/sdk/communication/Azure.Communication.JobRouter/src/Generated/Models/RouterJob.Serialization.cs +++ b/sdk/communication/Azure.Communication.JobRouter/src/Generated/Models/RouterJob.Serialization.cs @@ -8,14 +8,42 @@ using System; using System.Collections.Generic; using System.Text.Json; -using Azure.Communication.JobRouter; using Azure.Core; +using Azure.Core.Serialization; namespace Azure.Communication.JobRouter.Models { - public partial class RouterJob : IUtf8JsonSerializable + public partial class RouterJob : IModelJsonSerializable, IUtf8JsonSerializable { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + #region Serialize + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IModelJsonSerializable)this).Serialize(writer, ModelSerializerOptions.DefaultWireOptions); + + void IModelJsonSerializable.Serialize(Utf8JsonWriter writer, ModelSerializerOptions options) + { + // TODO: PatchModelHelper.ValidateFormat(this, options.Format); + + switch (options.Format.ToString()) + { + case "J": + case "W": + Serialize(writer, options); + break; + case "P": + SerializePatch(writer); + break; + default: + // Exception was thrown by ValidateFormat. + break; + } + } + + BinaryData IModelSerializable.Serialize(ModelSerializerOptions options) + { + // TODO: PatchModelHelper.ValidateFormat(this, options.Format); + return ModelSerializer.SerializeCore(this, options); + } + + private void Serialize(Utf8JsonWriter writer, ModelSerializerOptions options) { writer.WriteStartObject(); if (Optional.IsDefined(ChannelReference)) @@ -48,21 +76,21 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) writer.WritePropertyName("dispositionCode"u8); writer.WriteStringValue(DispositionCode); } - if (Optional.IsCollectionDefined(_requestedWorkerSelectors)) + if (Optional.IsCollectionDefined(RequestedWorkerSelectors)) { writer.WritePropertyName("requestedWorkerSelectors"u8); writer.WriteStartArray(); - foreach (var item in _requestedWorkerSelectors) + foreach (var item in RequestedWorkerSelectors) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } - if (Optional.IsCollectionDefined(_labels)) + if (Optional.IsCollectionDefined(Labels)) { writer.WritePropertyName("labels"u8); writer.WriteStartObject(); - foreach (var item in _labels) + foreach (var item in Labels) { writer.WritePropertyName(item.Key); if (item.Value == null) @@ -74,11 +102,11 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) } writer.WriteEndObject(); } - if (Optional.IsCollectionDefined(_tags)) + if (Optional.IsCollectionDefined(Tags)) { writer.WritePropertyName("tags"u8); writer.WriteStartObject(); - foreach (var item in _tags) + foreach (var item in Tags) { writer.WritePropertyName(item.Key); if (item.Value == null) @@ -90,17 +118,18 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) } writer.WriteEndObject(); } - if (Optional.IsCollectionDefined(_notes)) - { - writer.WritePropertyName("notes"u8); - writer.WriteStartObject(); - foreach (var item in _notes) - { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); - } - writer.WriteEndObject(); - } + // TODO + //if (Optional.IsCollectionDefined(Notes)) + //{ + // writer.WritePropertyName("notes"u8); + // writer.WriteStartObject(); + // foreach (var item in Notes) + // { + // writer.WritePropertyName(item.Key); + // writer.WriteStringValue(item.Value); + // } + // writer.WriteEndObject(); + //} if (Optional.IsDefined(MatchingMode)) { writer.WritePropertyName("matchingMode"u8); @@ -109,7 +138,19 @@ void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) writer.WriteEndObject(); } - internal static RouterJob DeserializeRouterJob(JsonElement element) + private void SerializePatch(Utf8JsonWriter writer) + { + throw new NotImplementedException(); + } + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + public static implicit operator RequestContent(RouterJob model) +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member + => RequestContent.Create(model, ModelSerializerOptions.DefaultWireOptions); + #endregion + + #region Deserialize + internal static RouterJob DeserializeRouterJob(JsonElement element, ModelSerializerOptions options = default) { if (element.ValueKind == JsonValueKind.Null) { @@ -310,5 +351,29 @@ internal static RouterJob DeserializeRouterJob(JsonElement element) } return new RouterJob(id.Value, channelReference.Value, Optional.ToNullable(status), Optional.ToNullable(enqueuedAt), channelId.Value, classificationPolicyId.Value, queueId.Value, Optional.ToNullable(priority), dispositionCode.Value, Optional.ToList(requestedWorkerSelectors), Optional.ToList(attachedWorkerSelectors), Optional.ToDictionary(labels), Optional.ToDictionary(assignments), Optional.ToDictionary(tags), Optional.ToDictionary(notes), Optional.ToNullable(scheduledAt), matchingMode.Value); } + + RouterJob IModelJsonSerializable.Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) + { + // TODO: PatchModelHelper.ValidateFormat(this, options.Format); + using var doc = JsonDocument.ParseValue(ref reader); + return DeserializeRouterJob(doc.RootElement, options); + } + + RouterJob IModelSerializable.Deserialize(BinaryData data, ModelSerializerOptions options) + { + // TODO: PatchModelHelper.ValidateFormat(this, options.Format); + return DeserializeRouterJob(JsonDocument.Parse(data.ToString()).RootElement, options); + } + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + public static explicit operator RouterJob(Response response) +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member + { + Argument.AssertNotNull(response, nameof(response)); + + using JsonDocument jsonDocument = JsonDocument.Parse(response.ContentStream); + return DeserializeRouterJob(jsonDocument.RootElement, ModelSerializerOptions.DefaultWireOptions); + } + #endregion } } diff --git a/sdk/communication/Azure.Communication.JobRouter/src/JobRouterClient.cs b/sdk/communication/Azure.Communication.JobRouter/src/JobRouterClient.cs index 697b5a6c19e2..0bd262ec7a3f 100644 --- a/sdk/communication/Azure.Communication.JobRouter/src/JobRouterClient.cs +++ b/sdk/communication/Azure.Communication.JobRouter/src/JobRouterClient.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; @@ -9,8 +9,9 @@ using Azure.Communication.Pipeline; using Azure.Core; using Azure.Core.Pipeline; +using Azure.Core.Serialization; - namespace Azure.Communication.JobRouter +namespace Azure.Communication.JobRouter { /// /// The Azure Communication Services Router client. @@ -115,7 +116,7 @@ public virtual async Task> CreateJobWithClassificationPolicy scope.Start(); try { - var request = new RouterJob + var request = new RouterJob(options.JobId) { ChannelId = options.ChannelId, ClassificationPolicyId = options.ClassificationPolicyId, @@ -146,7 +147,7 @@ public virtual async Task> CreateJobWithClassificationPolicy } return await RestClient.UpsertJobAsync( - id:options.JobId, + id: options.JobId, patch: request, cancellationToken: cancellationToken) .ConfigureAwait(false); @@ -170,7 +171,7 @@ public virtual Response CreateJobWithClassificationPolicy( scope.Start(); try { - var request = new RouterJob + var request = new RouterJob(options.JobId) { ChannelId = options.ChannelId, ClassificationPolicyId = options.ClassificationPolicyId, @@ -201,7 +202,7 @@ public virtual Response CreateJobWithClassificationPolicy( } return RestClient.UpsertJob( - id:options.JobId, + id: options.JobId, patch: request, cancellationToken: cancellationToken); } @@ -217,51 +218,25 @@ public virtual Response CreateJobWithClassificationPolicy( #region Create job with direct queue assignment /// Creates a new job to be routed. - /// Options for creating job with direct queue assignment. + /// Job to create with direct queue assignment. /// The cancellation token to use. /// The server returned an error. See for details returned from the server. public virtual async Task> CreateJobAsync( - CreateJobOptions options, + RouterJob job, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(JobRouterClient)}.{nameof(CreateJob)}"); scope.Start(); try { - var request = new RouterJob - { - ChannelId = options.ChannelId, - ChannelReference = options.ChannelReference, - QueueId = options.QueueId, - Priority = options.Priority, - MatchingMode = options.MatchingMode, - }; - - foreach (var label in options.Labels) + if (job is not IModelJsonSerializable model) { - request.Labels[label.Key] = label.Value; + throw new InvalidCastException("Model is not serializable."); } - foreach (var tag in options.Tags) - { - request.Tags[tag.Key] = tag.Value; - } - - foreach (var workerSelector in options.RequestedWorkerSelectors) - { - request.RequestedWorkerSelectors.Add(workerSelector); - } - - foreach (var note in options.Notes) - { - request.Notes.Add(note); - } - - return await RestClient.UpsertJobAsync( - id: options.JobId, - patch: request, - cancellationToken: cancellationToken) - .ConfigureAwait(false); + RequestContent content = RequestContent.Create(model, new ModelSerializerOptions("P")); + Response response = await UpdateJobAsync(job.Id, content, new() { CancellationToken = cancellationToken }).ConfigureAwait(false); + return Response.FromValue((RouterJob)response, response); } catch (Exception ex) { @@ -271,50 +246,26 @@ public virtual async Task> CreateJobAsync( } /// Creates a new job to be routed. - /// Options for creating job with direct queue assignment. + /// Job to create with direct queue assignment. /// The cancellation token to use. /// The server returned an error. See for details returned from the server. public virtual Response CreateJob( - CreateJobOptions options, + RouterJob job, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(JobRouterClient)}.{nameof(CreateJob)}"); scope.Start(); try { - var request = new RouterJob - { - ChannelId = options.ChannelId, - ChannelReference = options.ChannelReference, - QueueId = options.QueueId, - Priority = options.Priority, - MatchingMode = options.MatchingMode, - }; - - foreach (var label in options.Labels) - { - request.Labels[label.Key] = label.Value; - } - - foreach (var tag in options.Tags) + if (job is not IModelJsonSerializable model) { - request.Tags[tag.Key] = tag.Value; + throw new InvalidCastException("Model is not serializable."); } - foreach (var workerSelector in options.RequestedWorkerSelectors) - { - request.RequestedWorkerSelectors.Add(workerSelector); - } + RequestContent content = RequestContent.Create(model, new ModelSerializerOptions("P")); + Response response = UpdateJob(job.Id, content, new() { CancellationToken = cancellationToken }); - foreach (var note in options.Notes) - { - request.Notes.Add(note); - } - - return RestClient.UpsertJob( - id: options.JobId, - patch: request, - cancellationToken: cancellationToken); + return Response.FromValue((RouterJob)response, response); } catch (Exception ex) { @@ -323,56 +274,28 @@ public virtual Response CreateJob( } } - #endregion Create job with direct queue assignment + #endregion Update job with direct queue assignment /// Update an existing job. - /// Options for updating a job. Uses merge-patch semantics: https://datatracker.ietf.org/doc/html/rfc7386. + /// Job to update. Uses merge-patch semantics: https://datatracker.ietf.org/doc/html/rfc7386. /// The cancellation token to use. /// The server returned an error. See for details returned from the server. public virtual async Task> UpdateJobAsync( - UpdateJobOptions options, + RouterJob job, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(JobRouterClient)}.{nameof(UpdateJob)}"); scope.Start(); try { - var request = new RouterJob - { - ChannelId = options.ChannelId, - ClassificationPolicyId = options.ClassificationPolicyId, - ChannelReference = options.ChannelReference, - QueueId = options.QueueId, - Priority = options.Priority, - DispositionCode = options.DispositionCode, - MatchingMode = options.MatchingMode, - }; - - foreach (var label in options.Labels) - { - request.Labels[label.Key] = label.Value; - } - - foreach (var tag in options.Tags) + if (job is not IModelJsonSerializable model) { - request.Tags[tag.Key] = tag.Value; + throw new InvalidCastException("Model is not serializable."); } - foreach (var workerSelector in options.RequestedWorkerSelectors) - { - request.RequestedWorkerSelectors.Add(workerSelector); - } - - foreach (var note in options.Notes) - { - request.Notes.Add(note); - } - - return await RestClient.UpsertJobAsync( - id: options.JobId, - patch: request, - cancellationToken: cancellationToken) - .ConfigureAwait(false); + RequestContent content = RequestContent.Create(model, new ModelSerializerOptions("P")); + Response response = await UpdateJobAsync(job.Id, content, new() { CancellationToken = cancellationToken }).ConfigureAwait(false); + return Response.FromValue((RouterJob)response, response); } catch (Exception ex) { @@ -382,52 +305,25 @@ public virtual async Task> UpdateJobAsync( } /// Update an existing job. - /// Options for updating a job. Uses merge-patch semantics: https://datatracker.ietf.org/doc/html/rfc7386. + /// Job to update. Uses merge-patch semantics: https://datatracker.ietf.org/doc/html/rfc7386. /// The cancellation token to use. /// The server returned an error. See for details returned from the server. public virtual Response UpdateJob( - UpdateJobOptions options, + RouterJob job, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(JobRouterClient)}.{nameof(UpdateJob)}"); scope.Start(); try { - var request = new RouterJob + if (job is not IModelJsonSerializable model) { - ChannelId = options.ChannelId, - ClassificationPolicyId = options.ClassificationPolicyId, - ChannelReference = options.ChannelReference, - QueueId = options.QueueId, - Priority = options.Priority, - DispositionCode = options.DispositionCode, - MatchingMode = options.MatchingMode, - }; - - foreach (var label in options.Labels) - { - request.Labels[label.Key] = label.Value; - } - - foreach (var tag in options.Tags) - { - request.Tags[tag.Key] = tag.Value; + throw new InvalidCastException("Model is not serializable."); } - foreach (var workerSelector in options.RequestedWorkerSelectors) - { - request.RequestedWorkerSelectors.Add(workerSelector); - } - - foreach (var note in options.Notes) - { - request.Notes.Add(note); - } - - return RestClient.UpsertJob( - id: options.JobId, - patch: request, - cancellationToken: cancellationToken); + RequestContent content = RequestContent.Create(model, new ModelSerializerOptions("P")); + Response response = UpdateJob(job.Id, content, new() { CancellationToken = cancellationToken }); + return Response.FromValue((RouterJob)response, response); } catch (Exception ex) { @@ -1476,7 +1372,7 @@ async Task> FirstPageFunc(int? maxPageSize) queueId: options?.QueueId, hasCapacity: options?.HasCapacity, maxpagesize: maxPageSize, - cancellationToken: cancellationToken) + cancellationToken: cancellationToken) .ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } diff --git a/sdk/communication/Azure.Communication.JobRouter/src/Models/RouterJob.cs b/sdk/communication/Azure.Communication.JobRouter/src/Models/RouterJob.cs index c8887150f83e..2101dcb95ece 100644 --- a/sdk/communication/Azure.Communication.JobRouter/src/Models/RouterJob.cs +++ b/sdk/communication/Azure.Communication.JobRouter/src/Models/RouterJob.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Text.Json; using Azure.Core; namespace Azure.Communication.JobRouter.Models @@ -15,8 +14,10 @@ namespace Azure.Communication.JobRouter.Models public partial class RouterJob { /// Initializes a new instance of RouterJob. - internal RouterJob() + public RouterJob(string id) { + Id = id; + AttachedWorkerSelectors = new ChangeTrackingList(); Assignments = new ChangeTrackingDictionary(); _requestedWorkerSelectors = new ChangeTrackingList(); @@ -28,10 +29,10 @@ internal RouterJob() /// /// A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. /// - public Dictionary Labels { get; } = new Dictionary(); + public IDictionary Labels { get; } = new Dictionary(); /// A set of non-identifying attributes attached to this job. - public Dictionary Tags { get; } = new Dictionary(); + public IDictionary Tags { get; } = new Dictionary(); /// A collection of manually specified label selectors, which a worker must satisfy in order to process this job. public List RequestedWorkerSelectors { get; } = new List(); diff --git a/sdk/communication/Azure.Communication.JobRouter/tests/Samples/JobRouterPatchSamples.cs b/sdk/communication/Azure.Communication.JobRouter/tests/Samples/JobRouterPatchSamples.cs new file mode 100644 index 000000000000..47ca32074bbb --- /dev/null +++ b/sdk/communication/Azure.Communication.JobRouter/tests/Samples/JobRouterPatchSamples.cs @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Communication.JobRouter.Models; +using Azure.Core; +using Azure.Core.Serialization; +using Azure.Identity; +using NUnit.Framework; + +namespace Azure.Communication.JobRouter.Samples +{ + public class RouterJobModelSamples + { + [Test] + public void RoundTripRouterJobSample_ProtocolMethods() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient(""); + + RouterJob routerJob = client.GetJob(""); + + Console.WriteLine($"Job ID: '{routerJob.Id}'."); + Console.WriteLine($"Channel ID: '{routerJob.ChannelId}'."); + + var patch = new + { + labels = new + { + Some_Skill = 10 + } + }; + + // Sends JSON """{{"labels": {"Some_Skill": 10}}}""" + client.UpdateJob(routerJob.Id, RequestContent.Create(patch)); + } + + [Test] + public void RoundTripRouterJobSample_ProtocolMethods_DeleteLabel() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient(""); + + RouterJob routerJob = client.GetJob(""); + + Console.WriteLine($"Job ID: '{routerJob.Id}'."); + Console.WriteLine($"Channel ID: '{routerJob.ChannelId}'."); + + var patch = new + { + labels = new + { + Some_Skill = (object)null + } + }; + + // Sends JSON """{{"labels": {"Some_Skill": null}}}""" + client.UpdateJob(routerJob.Id, RequestContent.Create(patch)); + } + + [Test] + public void RoundTripRouterJobSample_ConvenienceMethods() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient(""); + + RouterJob routerJob = client.GetJob(""); + + Console.WriteLine($"Job ID: '{routerJob.Id}'."); + Console.WriteLine($"Channel ID: '{routerJob.ChannelId}'."); + + // Sends JSON """{{"labels": {"Some_Skill": 10}}}""" + routerJob.Labels["Some_Skill"] = new LabelValue(10); + + client.UpdateJob(routerJob); + } + + [Test] + public void RoundTripRouterJobSample_ConvenienceMethods_DeleteLabel() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient(""); + + RouterJob routerJob = client.GetJob(""); + + Console.WriteLine($"Job ID: '{routerJob.Id}'."); + Console.WriteLine($"Channel ID: '{routerJob.ChannelId}'."); + + routerJob.Labels.Remove("Some_Skill"); + + // Sends JSON """{{"labels": {"Some_Skill": null}}}""" + client.UpdateJob(routerJob); + } + [Test] + public void PatchWithoutGetRouterJobSample_ProtocolMethods() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient(""); + + var patch = new + { + labels = new + { + Some_Skill = 10 + } + }; + + // Sends JSON """{{"labels": {"Some_Skill": 10}}}""" + client.UpdateJob("", RequestContent.Create(patch)); + } + + [Test] + public void PatchWithoutGetRouterJobSample_ProtocolMethods_DeleteLabel() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient(""); + + var patch = new + { + labels = new + { + Some_Skill = (object)null + } + }; + + // Sends JSON """{{"labels": {"Some_Skill": null}}}""" + client.UpdateJob("", RequestContent.Create(patch)); + } + + [Test] + public void PatchWithoutGetRouterJobSample_ConvenienceMethods() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient(""); + + RouterJob routerJob = new RouterJob(""); + + // Sends JSON """{{"labels": {"Some_Skill": 10}}}""" + routerJob.Labels["Some_Skill"] = new LabelValue(10); + + client.UpdateJob(routerJob); + } + + [Test] + public void PatchWithoutGetRouterJobSample_ConvenienceMethods_DeleteLabel() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient(""); + + RouterJob routerJob = new RouterJob(""); + + routerJob.Labels.Remove("Some_Skill"); + + // Sends JSON """{{"labels": {"Some_Skill": null}}}""" + client.UpdateJob(routerJob); + } + } +} diff --git a/sdk/communication/Azure.Communication.JobRouter/tests/Samples/Sample1_KeyConcepts.cs b/sdk/communication/Azure.Communication.JobRouter/tests/Samples/Sample1_KeyConcepts.cs index 5ee4a2ca37b8..068856b668c3 100644 --- a/sdk/communication/Azure.Communication.JobRouter/tests/Samples/Sample1_KeyConcepts.cs +++ b/sdk/communication/Azure.Communication.JobRouter/tests/Samples/Sample1_KeyConcepts.cs @@ -48,19 +48,19 @@ public void BasicScenario() #endregion Snippet:Azure_Communication_JobRouter_Tests_Samples_CreateQueue #region Snippet:Azure_Communication_JobRouter_Tests_Samples_CreateJobDirectQAssign - Response job = routerClient.CreateJob( - new CreateJobOptions( - jobId: "jobId-2", - channelId: "my-channel", - queueId: queue.Value.Id) - { - ChannelReference = "12345", - Priority = 1, - RequestedWorkerSelectors = - { - new RouterWorkerSelector("Some-Skill", LabelOperator.GreaterThan, new LabelValue(10)) - }, - }); + //Response job = routerClient.CreateJob( + // new CreateJobOptions( + // jobId: "jobId-2", + // channelId: "my-channel", + // queueId: queue.Value.Id) + // { + // ChannelReference = "12345", + // Priority = 1, + // RequestedWorkerSelectors = + // { + // new RouterWorkerSelector("Some-Skill", LabelOperator.GreaterThan, new LabelValue(10)) + // }, + // }); #endregion Snippet:Azure_Communication_JobRouter_Tests_Samples_CreateJobDirectQAssign #region Snippet:Azure_Communication_JobRouter_Tests_Samples_RegisterWorker @@ -86,68 +86,68 @@ public void BasicScenario() #region Snippet:Azure_Communication_JobRouter_Tests_Samples_AcceptOffer - // fetching the offer id - Models.RouterJobOffer jobOffer = result.Value.Offers.First(x => x.JobId == job.Value.Id); + //// fetching the offer id + //Models.RouterJobOffer jobOffer = result.Value.Offers.First(x => x.JobId == job.Value.Id); - string offerId = jobOffer.OfferId; // `OfferId` can be retrieved directly from consuming event from Event grid + //string offerId = jobOffer.OfferId; // `OfferId` can be retrieved directly from consuming event from Event grid - // accepting the offer sent to `worker-1` - Response acceptJobOfferResult = routerClient.AcceptJobOffer(worker.Value.Id, offerId); + //// accepting the offer sent to `worker-1` + //Response acceptJobOfferResult = routerClient.AcceptJobOffer(worker.Value.Id, offerId); - Console.WriteLine($"Offer: {jobOffer.OfferId} sent to worker: {worker.Value.Id} has been accepted"); - Console.WriteLine($"Job has been assigned to worker: {worker.Value.Id} with assignment: {acceptJobOfferResult.Value.AssignmentId}"); + //Console.WriteLine($"Offer: {jobOffer.OfferId} sent to worker: {worker.Value.Id} has been accepted"); + //Console.WriteLine($"Job has been assigned to worker: {worker.Value.Id} with assignment: {acceptJobOfferResult.Value.AssignmentId}"); - // verify job assignment is populated when querying job - Response updatedJob = routerClient.GetJob(job.Value.Id); - Console.WriteLine($"Job assignment has been successful: {updatedJob.Value.Status == RouterJobStatus.Assigned && updatedJob.Value.Assignments.ContainsKey(acceptJobOfferResult.Value.AssignmentId)}"); + //// verify job assignment is populated when querying job + //Response updatedJob = routerClient.GetJob(job.Value.Id); + //Console.WriteLine($"Job assignment has been successful: {updatedJob.Value.Status == RouterJobStatus.Assigned && updatedJob.Value.Assignments.ContainsKey(acceptJobOfferResult.Value.AssignmentId)}"); #endregion Snippet:Azure_Communication_JobRouter_Tests_Samples_AcceptOffer #region Snippet:Azure_Communication_JobRouter_Tests_Samples_CompleteJob - Response completeJob = routerClient.CompleteJob( - options: new CompleteJobOptions( - jobId: job.Value.Id, - assignmentId: acceptJobOfferResult.Value.AssignmentId) - { - Note = $"Job has been completed by {worker.Value.Id} at {DateTimeOffset.UtcNow}" - }); + //Response completeJob = routerClient.CompleteJob( + // options: new CompleteJobOptions( + // jobId: job.Value.Id, + // assignmentId: acceptJobOfferResult.Value.AssignmentId) + // { + // Note = $"Job has been completed by {worker.Value.Id} at {DateTimeOffset.UtcNow}" + // }); - Console.WriteLine($"Job has been successfully completed: {completeJob.Status == 200}"); + //Console.WriteLine($"Job has been successfully completed: {completeJob.Status == 200}"); #endregion Snippet:Azure_Communication_JobRouter_Tests_Samples_CompleteJob #region Snippet:Azure_Communication_JobRouter_Tests_Samples_CloseJob - Response closeJob = routerClient.CloseJob( - options: new CloseJobOptions( - jobId: job.Value.Id, - assignmentId: acceptJobOfferResult.Value.AssignmentId) - { - Note = $"Job has been closed by {worker.Value.Id} at {DateTimeOffset.UtcNow}" - }); - Console.WriteLine($"Job has been successfully closed: {closeJob.Status == 200}"); + //Response closeJob = routerClient.CloseJob( + // options: new CloseJobOptions( + // jobId: job.Value.Id, + // assignmentId: acceptJobOfferResult.Value.AssignmentId) + // { + // Note = $"Job has been closed by {worker.Value.Id} at {DateTimeOffset.UtcNow}" + // }); + //Console.WriteLine($"Job has been successfully closed: {closeJob.Status == 200}"); - updatedJob = routerClient.GetJob(job.Value.Id); - Console.WriteLine($"Updated job status: {updatedJob.Value.Status == RouterJobStatus.Closed}"); + //updatedJob = routerClient.GetJob(job.Value.Id); + //Console.WriteLine($"Updated job status: {updatedJob.Value.Status == RouterJobStatus.Closed}"); #endregion Snippet:Azure_Communication_JobRouter_Tests_Samples_CloseJob #region Snippet:Azure_Communication_JobRouter_Tests_Samples_CloseJobInFuture - // Optionally, a job can also be set up to be marked as closed in the future. - var closeJobInFuture = routerClient.CloseJob( - options: new CloseJobOptions(job.Value.Id, acceptJobOfferResult.Value.AssignmentId) - { - CloseAt = DateTimeOffset.UtcNow.AddSeconds(2), // this will mark the job as closed after 2 seconds - Note = $"Job has been marked to close in the future by {worker.Value.Id} at {DateTimeOffset.UtcNow}" - }); - Console.WriteLine($"Job has been marked to close: {closeJob.Status == 202}"); // You'll received a 202 in that case + //// Optionally, a job can also be set up to be marked as closed in the future. + //var closeJobInFuture = routerClient.CloseJob( + // options: new CloseJobOptions(job.Value.Id, acceptJobOfferResult.Value.AssignmentId) + // { + // CloseAt = DateTimeOffset.UtcNow.AddSeconds(2), // this will mark the job as closed after 2 seconds + // Note = $"Job has been marked to close in the future by {worker.Value.Id} at {DateTimeOffset.UtcNow}" + // }); + //Console.WriteLine($"Job has been marked to close: {closeJob.Status == 202}"); // You'll received a 202 in that case - Thread.Sleep(TimeSpan.FromSeconds(2)); + //Thread.Sleep(TimeSpan.FromSeconds(2)); - updatedJob = routerClient.GetJob(job.Value.Id); - Console.WriteLine($"Updated job status: {updatedJob.Value.Status == RouterJobStatus.Closed}"); + //updatedJob = routerClient.GetJob(job.Value.Id); + //Console.WriteLine($"Updated job status: {updatedJob.Value.Status == RouterJobStatus.Closed}"); #endregion Snippet:Azure_Communication_JobRouter_Tests_Samples_CloseJobInFuture } diff --git a/sdk/communication/Azure.Communication.sln b/sdk/communication/Azure.Communication.sln index d44b404a05ae..fb4588125723 100644 --- a/sdk/communication/Azure.Communication.sln +++ b/sdk/communication/Azure.Communication.sln @@ -68,6 +68,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Communication.CallAut EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Communication.CallAutomation.Tests", "Azure.Communication.CallAutomation\tests\Azure.Communication.CallAutomation.Tests.csproj", "{8E628698-3ECB-4FA0-BDDF-62E018FDA0CA}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core", "..\core\Azure.Core\src\Azure.Core.csproj", "{AA4EFA41-28D0-4605-97A1-615A0DC82562}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -190,6 +192,10 @@ Global {8E628698-3ECB-4FA0-BDDF-62E018FDA0CA}.Debug|Any CPU.Build.0 = Debug|Any CPU {8E628698-3ECB-4FA0-BDDF-62E018FDA0CA}.Release|Any CPU.ActiveCfg = Release|Any CPU {8E628698-3ECB-4FA0-BDDF-62E018FDA0CA}.Release|Any CPU.Build.0 = Release|Any CPU + {AA4EFA41-28D0-4605-97A1-615A0DC82562}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AA4EFA41-28D0-4605-97A1-615A0DC82562}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AA4EFA41-28D0-4605-97A1-615A0DC82562}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AA4EFA41-28D0-4605-97A1-615A0DC82562}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/sdk/core/Azure.Core/src/Azure.Core.csproj b/sdk/core/Azure.Core/src/Azure.Core.csproj index f1b330f3c871..6f3c6aa98178 100644 --- a/sdk/core/Azure.Core/src/Azure.Core.csproj +++ b/sdk/core/Azure.Core/src/Azure.Core.csproj @@ -58,6 +58,10 @@ + + + + @@ -68,6 +72,9 @@ + + + diff --git a/sdk/core/Azure.Core/src/DynamicData/MutableJsonDocument.cs b/sdk/core/Azure.Core/src/DynamicData/MutableJsonDocument.cs index d4c508161185..ed5ed38af20a 100644 --- a/sdk/core/Azure.Core/src/DynamicData/MutableJsonDocument.cs +++ b/sdk/core/Azure.Core/src/DynamicData/MutableJsonDocument.cs @@ -7,6 +7,7 @@ using System.Text; using System.Text.Json; using System.Text.Json.Serialization; +using Azure.Core.Serialization; namespace Azure.Core.Json { diff --git a/sdk/core/Azure.Core/src/Serialization/ModelSerializerFormat.cs b/sdk/core/Azure.Core/src/Serialization/ModelSerializerFormat.cs index 7a4b8a7ce7f8..d5d0165b1663 100644 --- a/sdk/core/Azure.Core/src/Serialization/ModelSerializerFormat.cs +++ b/sdk/core/Azure.Core/src/Serialization/ModelSerializerFormat.cs @@ -13,6 +13,7 @@ namespace Azure.Core.Serialization { internal const string JsonValue = "J"; internal const string WireValue = "W"; + internal const string JsonMergePatchValue = "P"; /// /// Default format which will serialize all properties including read-only and additional properties. @@ -30,6 +31,16 @@ namespace Azure.Core.Serialization /// public static readonly ModelSerializerFormat Wire = new ModelSerializerFormat(WireValue); + /// + /// Format used to serialize this model when sending as a request to an Azure service. + /// It may not serialize read-only properties or additional properties. + /// The content-type will vary between JSON, XML, etc., depending on the service. + /// + /// Most use cases should prefer a more complete format like that includes + /// read-only and additional properties. + /// + public static readonly ModelSerializerFormat JsonMergePatch = new ModelSerializerFormat(JsonMergePatchValue); + private readonly string _value; /// diff --git a/sdk/core/Azure.Core/src/Shared/BitVector128.cs b/sdk/core/Azure.Core/src/Shared/BitVector128.cs new file mode 100644 index 000000000000..89ef6fb0f6ef --- /dev/null +++ b/sdk/core/Azure.Core/src/Shared/BitVector128.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Azure.Core +{ + internal struct BitVector128 + { + private ulong _bits0; + private ulong _bits1; + + public bool this[int i] + { + readonly get + { + int index = i >> 6; + int mod = i & 0b111111; + ulong mask = 1ul << mod; + ulong bit = (index == 0 ? _bits0 : _bits1) & mask; + return bit == mask; + } + set + { + int index = i >> 6; + int mod = i & 0b111111; + ulong mask = 1ul << mod; + if (index == 0) + { + _bits0 |= mask; + } + else + { + _bits1 |= mask; + } + } + } + + public readonly bool IsNonzero() => (_bits0 > 0) || (_bits1 > 0); + } +} diff --git a/sdk/core/Azure.Core/src/Shared/BitVector64.cs b/sdk/core/Azure.Core/src/Shared/BitVector64.cs new file mode 100644 index 000000000000..de5b5aced822 --- /dev/null +++ b/sdk/core/Azure.Core/src/Shared/BitVector64.cs @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Azure.Core +{ + internal struct BitVector64 + { + private ulong _bits; + + public bool this[int i] + { + get + { + int mod = i & 0b111111; + ulong mask = 1ul << mod; + ulong bit = _bits & mask; + return bit == mask; + } + set + { + int mod = i & 0b111111; + ulong mask = 1ul << mod; + _bits |= mask; + } + } + + public bool IsNonzero() => _bits > 0; + } +} diff --git a/sdk/core/Azure.Core/src/Shared/BitVector640.cs b/sdk/core/Azure.Core/src/Shared/BitVector640.cs new file mode 100644 index 000000000000..24b4b80b702e --- /dev/null +++ b/sdk/core/Azure.Core/src/Shared/BitVector640.cs @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; + +namespace Azure.Core +{ + internal struct BitVector640 + { + private ulong _bits0; + private ulong _bits1; + private ulong _bits2; + private ulong _bits3; + private ulong _bits4; + private ulong _bits5; + private ulong _bits6; + private ulong _bits7; + private ulong _bits8; + private ulong _bits9; + + public bool this[int i] + { + readonly get + { + int index = i >> 6; + int mod = i & 0b111111; + ulong mask = 1ul << mod; + ulong bit = Get(index) & mask; + return bit == mask; + } + set + { + int index = i >> 6; + int mod = i & 0b111111; + ulong mask = 1ul << mod; + Set(index, mask); + } + } + + public readonly bool IsNonzero() => + _bits0 > 0 || + _bits1 > 0 || + _bits2 > 0 || + _bits3 > 0 || + _bits4 > 0 || + _bits5 > 0 || + _bits6 > 0 || + _bits7 > 0 || + _bits8 > 0 || + _bits9 > 0; + + private readonly ulong Get(int index) + { + return index switch + { + 0 => _bits0, + 1 => _bits1, + 2 => _bits2, + 3 => _bits3, + 4 => _bits4, + 5 => _bits5, + 6 => _bits6, + 7 => _bits7, + 8 => _bits8, + 9 => _bits9, + _ => throw new InvalidOperationException(), + }; + } + + private void Set(int index, ulong mask) + { + switch (index) + { + case 0: + _bits0 |= mask; + break; + case 1: + _bits1 |= mask; + break; + case 2: + _bits2 |= mask; + break; + case 3: + _bits3 |= mask; + break; + case 4: + _bits4 |= mask; + break; + case 5: + _bits5 |= mask; + break; + case 6: + _bits6 |= mask; + break; + case 7: + _bits7 |= mask; + break; + case 8: + _bits8 |= mask; + break; + case 9: + _bits9 |= mask; + break; + default: + throw new InvalidOperationException(); + } + } + } +} diff --git a/sdk/core/Azure.Core/src/Shared/BitVectorHeapBacked.cs b/sdk/core/Azure.Core/src/Shared/BitVectorHeapBacked.cs new file mode 100644 index 000000000000..27cca6cd0b98 --- /dev/null +++ b/sdk/core/Azure.Core/src/Shared/BitVectorHeapBacked.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Azure.Core +{ + internal readonly struct BitVectorHeapBacked + { + private readonly ulong[] _bits; + + public BitVectorHeapBacked(int size) + { + _bits = new ulong[(size >> 6) + 1]; + } + + public bool this[int i] + { + get + { + int index = i >> 6; + int mod = i & 0b111111; + ulong mask = 1ul << mod; + ulong bit = _bits[index] & mask; + return bit == mask; + } + set + { + int index = i >> 6; + int mod = i & 0b111111; + ulong mask = 1ul << mod; + _bits[index] |= mask; + } + } + + public bool IsNonzero() + { + foreach (ulong value in _bits) + { + if (value > 0) + { + return true; + } + } + + return false; + } + } +} diff --git a/sdk/core/Azure.Core/src/Shared/MergePatchDictionary.Serialization.cs b/sdk/core/Azure.Core/src/Shared/MergePatchDictionary.Serialization.cs new file mode 100644 index 000000000000..08ab4ca5689b --- /dev/null +++ b/sdk/core/Azure.Core/src/Shared/MergePatchDictionary.Serialization.cs @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Text.Json; + +namespace Azure.Core.Serialization +{ + //internal partial class MergePatchDictionary : IModelJsonSerializable> + //{ + // #region Serialize + // void IModelJsonSerializable>.Serialize(Utf8JsonWriter writer, ModelSerializerOptions options) + // { + // ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + + // if (options.Format.ToString() == ModelSerializerFormat.Json || + // options.Format.ToString() == ModelSerializerFormat.Wire) + // { + // SerializeFull(writer); + // } + // else if (options.Format.ToString() == ModelSerializerFormat.JsonMergePatch) + // { + // SerializePatch(writer); + // } + // } + + // BinaryData IModelSerializable>.Serialize(ModelSerializerOptions options) + // { + // ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + // return ModelSerializer.SerializeCore(this, options); + // } + + // private void SerializeFull(Utf8JsonWriter writer) + // { + // writer.WriteStartObject(); + + // foreach (KeyValuePair kvp in _dictionary) + // { + // if (kvp.Value == null) + // { + // writer.WritePropertyName(kvp.Key); + // writer.WriteNullValue(); + // } + // else + // { + // writer.WritePropertyName(kvp.Key); + // _serializeItem(writer, kvp.Value); + // } + // } + + // writer.WriteEndObject(); + // } + + // private void SerializePatch(Utf8JsonWriter writer) + // { + // writer.WriteStartObject(); + + // foreach (KeyValuePair kvp in _changed) + // { + // if (kvp.Value) + // { + // if (!_dictionary.TryGetValue(kvp.Key, out T? value) || value == null) + // { + // writer.WritePropertyName(kvp.Key); + // writer.WriteNullValue(); + // } + // else if (_itemHasChanges == null || _itemHasChanges(value)) + // { + // writer.WritePropertyName(kvp.Key); + // _serializeItem(writer, value); + // } + // } + // } + + // writer.WriteEndObject(); + // } + // #endregion + + // #region Deserialize + + // public static MergePatchDictionary Deserialize(JsonElement element, + // Func deserializeItem, + // Action serializeItem, + // Func? itemHasChanges = default) + // { + // return new MergePatchDictionary(element, deserializeItem, serializeItem, itemHasChanges); + // } + + // MergePatchDictionary IModelJsonSerializable>.Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) + // { + // using JsonDocument doc = JsonDocument.ParseValue(ref reader); + // return Deserialize(doc.RootElement, + // _deserializeItem, + // _serializeItem, + // _itemHasChanges); + // } + + // MergePatchDictionary IModelSerializable>.Deserialize(BinaryData data, ModelSerializerOptions options) + // { + // using JsonDocument doc = JsonDocument.Parse(data); + // return Deserialize(doc.RootElement, + // _deserializeItem, + // _serializeItem, + // _itemHasChanges); + // } + + // #endregion + //} +} diff --git a/sdk/core/Azure.Core/src/Shared/MergePatchDictionary.cs b/sdk/core/Azure.Core/src/Shared/MergePatchDictionary.cs new file mode 100644 index 000000000000..6aa5116cbd25 --- /dev/null +++ b/sdk/core/Azure.Core/src/Shared/MergePatchDictionary.cs @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text.Json; + +namespace Azure.Core.Serialization +{ + //internal partial class MergePatchDictionary //: IDictionary + //{ + // public static MergePatchDictionary GetStringDictionary() + // => new(e => e.GetString(), (w, s) => w.WriteStringValue(s), default); + + // private readonly MergePatchChanges _changes; + // private readonly Dictionary _indexes; + // private readonly T?[] _values; + + // private readonly Func _deserializeItem; + // private readonly Action _serializeItem; + // private readonly Func? _itemHasChanges; + + // private bool _checkChanges; + // private bool _hasChanges; + + // public MergePatchDictionary( + // Func deserializeItem, + // Action serializeItem, + // Func? hasChanges = default) + // { + // // TODO: How to size it? + // _changes = new(100); + // _indexes = new Dictionary(); + // _values = new T?[100]; + + // _deserializeItem = deserializeItem; + // _serializeItem = serializeItem; + // _itemHasChanges = hasChanges; + // } + + // /// + // /// Deserialization constructor + // /// + // internal MergePatchDictionary( + // JsonElement element, + // Func deserializeItem, + // Action serializeItem, + // Func? hasChanges = default) + // { + // // TODO: How to size it? + // _changes = new(100); + // _indexes = new Dictionary(); + // _values = new T?[100]; + + // _deserializeItem = deserializeItem; + // _serializeItem = serializeItem; + // _itemHasChanges = hasChanges; + + // // Deserialize the values from the JsonElement + // foreach (JsonProperty property in element.EnumerateObject()) + // { + // Add(property.Name, deserializeItem(property.Value)); + // } + // } + + // public bool HasChanges => _hasChanges || ItemsChanged(); + + // private bool ItemsChanged() + // { + // if (!_checkChanges) + // { + // return false; + // } + + // foreach (KeyValuePair item in _indexes) + // { + // bool mightHaveChanged = _changes.HasChanged(item.Value); + // if (mightHaveChanged) + // { + // T? value = _values[item.Value]; + // if (_itemHasChanges != null && _itemHasChanges(value)) + // { + // return true; + // } + // } + // } + + // return false; + // } + + // public T? this[string key] + // { + // get + // { + // // If the value is read and a reference value, it might get changed + // _checkChanges = _itemHasChanges != null; + // if (_itemHasChanges != null) + // { + // _changes.SetChanged(_indexes[key]); + // } + // return _values[_indexes[key]]; + // } + + // set + // { + // _hasChanges = true; + // if (_indexes.TryGetValue(key, out int index)) + // { + // _changes.SetChanged(index); + // _values[index] = value; + // } + // else + // { + // Add(key, value); + // } + // } + // } + + // ICollection IDictionary.Keys => _indexes.Keys; + + // //ICollection IDictionary.Values => _dictionary.Values; + + // //int ICollection>.Count => _indexes.Count; + + // //bool ICollection>.IsReadOnly => false; + + // //public void Add(string key, T? value) + // //{ + // // int index = GetNextIndex(); + // // _indexes[key] = index; + // // _values[index] = value; + // // _hasChanges = true; + // // _changes.SetChanged(index); + // //} + + // //private int GetNextIndex() + // //{ + // // // This will handle Resize() as well. + // // // See example here: https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs#L848 + // // throw new NotImplementedException(); + // //} + + // //void ICollection>.Add(KeyValuePair item) + // //{ + // // int index = GetNextIndex(); + // // _indexes[item.Key] = index; + // // _values[index] = item.Value; + // // _hasChanges = true; + // // _changes.SetChanged(index); + // //} + + // //void ICollection>.Clear() + // //{ + // // // TODO: this raises the question of how we track changes for deleted elements. + // // // Solve it here. + + // // _hasChanges = true; + // // foreach (int index in _indexes.Values) + // // { + // // _changes.SetChanged(index); + // // } + + // // (_dictionary as ICollection>).Clear(); + // //} + + // //bool ICollection>.Contains(KeyValuePair item) => + // // (_dictionary as ICollection>).Contains(item); + + // //bool IDictionary.ContainsKey(string key) + // // => _dictionary.ContainsKey(key); + + // //void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) + // // => (_dictionary as ICollection>).CopyTo(array, arrayIndex); + + // //IEnumerator> IEnumerable>.GetEnumerator() + // //{ + // // // TODO: handle item changes + // // return _dictionary.GetEnumerator(); + // //} + + // //IEnumerator IEnumerable.GetEnumerator() + // //{ + // // // TODO: handle item changes + // // return (_dictionary as IEnumerable).GetEnumerator(); + // //} + + // //bool IDictionary.Remove(string key) + // //{ + // // _hasChanges = true; + // // _changed[key] = true; + // // return _dictionary.Remove(key); + // //} + + // //bool ICollection>.Remove(KeyValuePair item) + // //{ + // // _hasChanges = true; + // // _changed[item.Key] = true; + // // return (_dictionary as ICollection>).Remove(item); + // //} + + // //public bool TryGetValue(string key, out T? value) + // //{ + // // if (_indexes.TryGetValue(key, out int index)) + // // { + // // _checkChanges = _itemHasChanges != null; + // // _changed[key] = _itemHasChanges != null; + // // return true; + // // } + + // // return false; + // //} + //} +} diff --git a/sdk/core/Azure.Core/src/Shared/ModelSerializerHelper.cs b/sdk/core/Azure.Core/src/Shared/ModelSerializerHelper.cs index 45481db3c91a..47e790f59a74 100644 --- a/sdk/core/Azure.Core/src/Shared/ModelSerializerHelper.cs +++ b/sdk/core/Azure.Core/src/Shared/ModelSerializerHelper.cs @@ -22,5 +22,15 @@ public static void ValidateFormat(IModelSerializable model, ModelSerialize [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateFormat(IModelSerializable model, ModelSerializerFormat format) => ValidateFormat(model, format); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ValidatePatchFormat(IModelSerializable model, ModelSerializerFormat format) + { + bool isValidPatchFormat = model is IModelJsonSerializable && format == ModelSerializerFormat.JsonMergePatch; + if (!isValidPatchFormat) + { + ValidateFormat(model, format); + } + } } } diff --git a/sdk/core/Azure.Core/src/StatusCodeClassifier.cs b/sdk/core/Azure.Core/src/StatusCodeClassifier.cs index 64869985d8d4..1b1223862aa0 100644 --- a/sdk/core/Azure.Core/src/StatusCodeClassifier.cs +++ b/sdk/core/Azure.Core/src/StatusCodeClassifier.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. using System; -using System.Diagnostics; #nullable enable @@ -15,90 +14,52 @@ namespace Azure.Core public class StatusCodeClassifier : ResponseClassifier { // We need 10 ulongs to represent status codes 100 - 599. - private const int Length = 10; - private ulong[] _successCodes; + private BitVector640 _successCodes; internal ResponseClassificationHandler[]? Handlers { get; set; } /// - /// Creates a new instance of + /// Creates a new instance of . /// /// The status codes that this classifier will consider /// not to be errors. public StatusCodeClassifier(ReadOnlySpan successStatusCodes) { - _successCodes = new ulong[Length]; - foreach (int statusCode in successStatusCodes) { AddClassifier(statusCode, isError: false); } } - private StatusCodeClassifier(ulong[] successCodes, ResponseClassificationHandler[]? handlers) + private StatusCodeClassifier(BitVector640 successCodes, ResponseClassificationHandler[]? handlers) { - Debug.Assert(successCodes?.Length == Length); - - _successCodes = successCodes!; + _successCodes = successCodes; Handlers = handlers; } /// public override bool IsErrorResponse(HttpMessage message) { - bool isError; - if (Handlers != null) { - foreach (var handler in Handlers) + foreach (ResponseClassificationHandler handler in Handlers) { - if (handler.TryClassify(message, out isError)) + if (handler.TryClassify(message, out bool isError)) { return isError; } } } - return !IsSuccessCode(message.Response.Status); + return !_successCodes[message.Response.Status]; } - internal virtual StatusCodeClassifier Clone() - { - ulong[] successCodes = new ulong[Length]; - Array.Copy(_successCodes, successCodes, Length); - - return new StatusCodeClassifier(successCodes, Handlers); - } + internal virtual StatusCodeClassifier Clone() => new(_successCodes, Handlers); internal void AddClassifier(int statusCode, bool isError) { Argument.AssertInRange(statusCode, 0, 639, nameof(statusCode)); - - var index = statusCode >> 6; // divides by 64 - int bit = statusCode & 0b111111; // keeps the bits up to 63 - ulong mask = 1ul << bit; // shifts a 1 to the position of code - - ulong value = _successCodes[index]; - if (!isError) - { - value |= mask; - } - else - { - value &= ~mask; - } - - _successCodes[index] = value; - } - - private bool IsSuccessCode(int statusCode) - { - var index = statusCode >> 6; // divides by 64 - int bit = statusCode & 0b111111; // keeps the bits up to 63 - ulong mask = 1ul << bit; // shifts a 1 to the position of code - - ulong value = _successCodes[index]; - return (value & mask) != 0; + _successCodes[statusCode] = isError; } } } diff --git a/sdk/core/Azure.Core/tests/public/Azure.Core.Tests.Public.csproj b/sdk/core/Azure.Core/tests/public/Azure.Core.Tests.Public.csproj index dd5cf6cebc4f..7991e030352b 100644 --- a/sdk/core/Azure.Core/tests/public/Azure.Core.Tests.Public.csproj +++ b/sdk/core/Azure.Core/tests/public/Azure.Core.Tests.Public.csproj @@ -23,7 +23,10 @@ + + + diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/ChildPatchModel.Serialization.cs b/sdk/core/Azure.Core/tests/public/PatchModels/ChildPatchModel.Serialization.cs new file mode 100644 index 000000000000..a800a63eec8e --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/ChildPatchModel.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Text.Json; +using Azure.Core.Serialization; + +namespace Azure.Core.Tests.PatchModels +{ + public partial class ChildPatchModel : IModelJsonSerializable, IUtf8JsonSerializable + { + internal static ChildPatchModel Deserialize(JsonElement element) + { + string a = default; + string b = default; + + foreach (JsonProperty property in element.EnumerateObject()) + { + if (property.NameEquals("a")) + { + a = property.Value.GetString(); + continue; + } + + if (property.NameEquals("b")) + { + b = property.Value.GetString(); + continue; + } + } + + return new ChildPatchModel(a, b); + } + + ChildPatchModel IModelJsonSerializable.Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + return Deserialize(ref reader, options); + } + + private static ChildPatchModel Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) + { + JsonElement element = JsonDocument.ParseValue(ref reader).RootElement; + return Deserialize(element); + } + + ChildPatchModel IModelSerializable.Deserialize(BinaryData data, ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + return Deserialize(data, options); + } + + private static ChildPatchModel Deserialize(BinaryData data, ModelSerializerOptions options) + { + JsonElement element = JsonDocument.Parse(data).RootElement; + return Deserialize(element); + } + + internal void SerializeFull(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + + writer.WritePropertyName("a"); + writer.WriteStringValue(A); + + writer.WritePropertyName("b"); + writer.WriteStringValue(B); + + writer.WriteEndObject(); + } + + internal void SerializePatch(Utf8JsonWriter writer) + { + if (HasChanges) + { + writer.WriteStartObject(); + + if (_changed[AProperty]) + { + writer.WritePropertyName("a"); + writer.WriteStringValue(A); + } + + if (_changed[BProperty]) + { + writer.WritePropertyName("b"); + writer.WriteStringValue(B); + } + + writer.WriteEndObject(); + } + } + + void IModelJsonSerializable.Serialize(Utf8JsonWriter writer, ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + + if (options.Format.ToString() == ModelSerializerFormat.Json || + options.Format.ToString() == ModelSerializerFormat.Wire) + { + SerializeFull(writer); + } + else if (options.Format.ToString() == ModelSerializerFormat.JsonMergePatch) + { + SerializePatch(writer); + } + } + + BinaryData IModelSerializable.Serialize(ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + return ModelSerializer.SerializeCore(this, options); + } + + public static implicit operator RequestContent(ChildPatchModel model) + => RequestContent.Create(model, ModelSerializerOptions.DefaultWireOptions); + + public static explicit operator ChildPatchModel(Response response) + { + Argument.AssertNotNull(response, nameof(response)); + return Deserialize(response.Content, ModelSerializerOptions.DefaultWireOptions); + } + + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IModelJsonSerializable)this).Serialize(writer, ModelSerializerOptions.DefaultWireOptions); + } +} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/ChildPatchModel.cs b/sdk/core/Azure.Core/tests/public/PatchModels/ChildPatchModel.cs new file mode 100644 index 000000000000..dbcec293bb1c --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/ChildPatchModel.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Azure.Core.Tests.PatchModels +{ + /// + /// This model illustrates a nested child model in a parent model. + /// + public partial class ChildPatchModel + { + private BitVector64 _changed; + + /// + /// Serialization constructor. + /// + internal ChildPatchModel() + { + } + + /// Deserialization constructor. + internal ChildPatchModel(string a, string b) + { + _a = a; + _b = b; + } + + public bool HasChanges => _changed.IsNonzero(); + + private string _a; + private const int AProperty = 0; + /// + /// Optional string property corresponding to JSON """{"a": "aaa"}""". + /// + public string A + { + get => _a; + set + { + _changed[AProperty] = true; + _a = value; + } + } + + private string _b; + private const int BProperty = 1; + /// + /// Optional string property corresponding to JSON """{"b": "bbb"}""". + /// + public string B + { + get => _b; + set + { + _changed[BProperty] = true; + _b = value; + } + } + } +} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/ChildPatchModelTests.cs b/sdk/core/Azure.Core/tests/public/PatchModels/ChildPatchModelTests.cs new file mode 100644 index 000000000000..eeeb7a56a74c --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/ChildPatchModelTests.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using Azure.Core.Serialization; +using Azure.Core.Tests.PatchModels; +using NUnit.Framework; + +namespace Azure.Core.Tests.Public.ModelSerializationTests +{ + internal class ChildPatchModelTests : ModelJsonTests + { + protected override string JsonPayload => """ + { + "a": "aa", "b": "bb" + } + """; + + protected override string WirePayload => JsonPayload; + + protected override Func ToRequestContent => m => m == null ? null : RequestContent.Create(m, ModelSerializerOptions.DefaultWireOptions); + + protected override Func FromResponse => r => (ChildPatchModel)r; + + protected override void CompareModels(ChildPatchModel model, ChildPatchModel model2, ModelSerializerFormat format) + { + Assert.AreEqual(model.A, model2.A); + Assert.AreEqual(model.B, model2.B); + } + + protected override string GetExpectedResult(ModelSerializerFormat format) + { + return RemoveWhitespace(JsonPayload); + } + + protected override void VerifyModel(ChildPatchModel model, ModelSerializerFormat format) + { + Assert.AreEqual("aa", model.A); + Assert.AreEqual("bb", model.B); + } + + private static string RemoveWhitespace(string value) => value.Replace("\r", "").Replace("\n", "").Replace(" ", ""); + } +} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/CollectionPatchModel.Serialization.cs b/sdk/core/Azure.Core/tests/public/PatchModels/CollectionPatchModel.Serialization.cs new file mode 100644 index 000000000000..b39256e74e32 --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/CollectionPatchModel.Serialization.cs @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +//using System; +//using System.Collections.Generic; +//using System.Text.Json; +//using Azure.Core.Serialization; + +//namespace Azure.Core.Tests.PatchModels +//{ +// public partial class CollectionPatchModel : IModelJsonSerializable, IUtf8JsonSerializable +// { +// internal static CollectionPatchModel Deserialize(JsonElement element) +// { +// string id = default; +// MergePatchDictionary variables = default; +// MergePatchDictionary children = default; + +// foreach (JsonProperty property in element.EnumerateObject()) +// { +// if (property.NameEquals("id")) +// { +// id = property.Value.GetString(); +// continue; +// } + +// if (property.NameEquals("variables")) +// { +// variables = MergePatchDictionary.Deserialize( +// property.Value, +// e => e.GetString(), +// (w, s) => w.WriteStringValue(s)); +// } + +// if (property.NameEquals("children")) +// { +// children = MergePatchDictionary.Deserialize( +// property.Value, +// ChildPatchModel.Deserialize, +// (w, m) => m.SerializePatch(w), +// c => c.HasChanges); +// } +// } + +// return new CollectionPatchModel(id, variables, children); +// } + +// CollectionPatchModel IModelJsonSerializable.Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) +// { +// ModelSerializerHelper.ValidatePatchFormat(this, options.Format); +// return Deserialize(ref reader, options); +// } + +// private static CollectionPatchModel Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) +// { +// using JsonDocument doc = JsonDocument.ParseValue(ref reader); +// return Deserialize(doc.RootElement); +// } + +// CollectionPatchModel IModelSerializable.Deserialize(BinaryData data, ModelSerializerOptions options) +// { +// ModelSerializerHelper.ValidatePatchFormat(this, options.Format); +// return Deserialize(data, options); +// } + +// private static CollectionPatchModel Deserialize(BinaryData data, ModelSerializerOptions options) +// { +// using JsonDocument doc = JsonDocument.Parse(data); +// return Deserialize(doc.RootElement); +// } + +// private void SerializeFull(Utf8JsonWriter writer) +// { +// writer.WriteStartObject(); + +// writer.WritePropertyName("id"); +// writer.WriteStringValue(Id); + +// writer.WritePropertyName("variables"); +// writer.WriteStartObject(); +// foreach (KeyValuePair item in Variables) +// { +// writer.WritePropertyName(item.Key); +// writer.WriteStringValue(item.Value); +// } +// writer.WriteEndObject(); + +// if (_children != null) +// { +// writer.WritePropertyName("children"); +// writer.WriteStartObject(); +// foreach (KeyValuePair item in Children) +// { +// writer.WritePropertyName(item.Key); +// item.Value.SerializeFull(writer); +// } +// writer.WriteEndObject(); +// } + +// writer.WriteEndObject(); +// } + +// private void SerializePatch(Utf8JsonWriter writer) +// { +// writer.WriteStartObject(); + +// if (_changes.HasChanged(IdProperty)) +// { +// writer.WritePropertyName("id"); +// writer.WriteStringValue(Id); +// } + +// if (_variables != null && _variables.HasChanges) +// { +// writer.WritePropertyName("variables"); + +// (_variables as IModelJsonSerializable>) +// .Serialize(writer, new ModelSerializerOptions(ModelSerializerFormat.JsonMergePatch)); +// } + +// if (_children != null && _children.HasChanges) +// { +// writer.WritePropertyName("children"); + +// (_children as IModelJsonSerializable>) +// .Serialize(writer, new ModelSerializerOptions(ModelSerializerFormat.JsonMergePatch)); +// } + +// writer.WriteEndObject(); +// } + +// void IModelJsonSerializable.Serialize(Utf8JsonWriter writer, ModelSerializerOptions options) +// { +// ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + +// if (options.Format.ToString() == ModelSerializerFormat.Json || +// options.Format.ToString() == ModelSerializerFormat.Wire) +// { +// SerializeFull(writer); +// } +// else if (options.Format.ToString() == ModelSerializerFormat.JsonMergePatch) +// { +// SerializePatch(writer); +// } +// } + +// BinaryData IModelSerializable.Serialize(ModelSerializerOptions options) +// { +// ModelSerializerHelper.ValidatePatchFormat(this, options.Format); +// return ModelSerializer.SerializeCore(this, options); +// } + +// public static implicit operator RequestContent(CollectionPatchModel model) +// => RequestContent.Create(model, ModelSerializerOptions.DefaultWireOptions); + +// public static explicit operator CollectionPatchModel(Response response) +// { +// Argument.AssertNotNull(response, nameof(response)); +// return Deserialize(response.Content, ModelSerializerOptions.DefaultWireOptions); +// } + +// void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IModelJsonSerializable)this).Serialize(writer, ModelSerializerOptions.DefaultWireOptions); +// } +//} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/CollectionPatchModel.cs b/sdk/core/Azure.Core/tests/public/PatchModels/CollectionPatchModel.cs new file mode 100644 index 000000000000..2ffced27c29d --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/CollectionPatchModel.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +//using System.Collections.Generic; +//using Azure.Core.Serialization; + +//namespace Azure.Core.Tests.PatchModels +//{ +// /// +// /// This model illustrates collection properties on Patch models. +// /// +// public partial class CollectionPatchModel +// { +// private readonly MergePatchChanges _changes; + +// /// +// /// Public constructor. +// /// +// public CollectionPatchModel() +// { +// // Size is 1 b/c we don't need to track changes to read-only values. +// _changes = new MergePatchChanges(1); +// } + +// /// +// /// Serialization constructor. +// /// +// internal CollectionPatchModel(string id, MergePatchDictionary variables, MergePatchDictionary children) +// { +// _changes = new MergePatchChanges(1); + +// _id = id; +// _variables = variables; +// _children = children; +// } + +// private string _id; +// private static int IdProperty => 0; +// /// +// /// Optional string property corresponding to JSON """{"id": "abc"}""". +// /// +// public string Id +// { +// get => _id; +// set +// { +// _changes.SetChanged(IdProperty); +// _id = value; +// } +// } + +// private MergePatchDictionary _variables; +// /// Environment variables which are defined as a set of <name,value> pairs. +// public IDictionary Variables +// { +// get +// { +// _variables ??= MergePatchDictionary.GetStringDictionary(); +// return _variables; +// } +// } + +// private MergePatchDictionary _children; +// /// +// public IDictionary Children +// { +// get +// { +// _children ??= +// new MergePatchDictionary( +// ChildPatchModel.Deserialize, +// (w, m) => m.SerializePatch(w), +// c => c.HasChanges); +// return _children; +// } +// } +// } +//} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/ParentPatchModel.Serialization.cs b/sdk/core/Azure.Core/tests/public/PatchModels/ParentPatchModel.Serialization.cs new file mode 100644 index 000000000000..ca71d1c97938 --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/ParentPatchModel.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Text.Json; +using Azure.Core.Serialization; + +namespace Azure.Core.Tests.PatchModels +{ + public partial class ParentPatchModel : IModelJsonSerializable, IUtf8JsonSerializable + { + internal static ParentPatchModel Deserialize(JsonElement element) + { + string id = default; + ChildPatchModel child = default; + + foreach (JsonProperty property in element.EnumerateObject()) + { + if (property.NameEquals("id")) + { + id = property.Value.GetString(); + continue; + } + + if (property.NameEquals("child")) + { + child = ChildPatchModel.Deserialize(property.Value); + continue; + } + } + + return new ParentPatchModel(id, child); + } + + ParentPatchModel IModelJsonSerializable.Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + return Deserialize(ref reader, options); + } + + private static ParentPatchModel Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) + { + JsonElement element = JsonDocument.ParseValue(ref reader).RootElement; + return Deserialize(element); + } + + ParentPatchModel IModelSerializable.Deserialize(BinaryData data, ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + return Deserialize(data, options); + } + + private static ParentPatchModel Deserialize(BinaryData data, ModelSerializerOptions options) + { + JsonElement element = JsonDocument.Parse(data).RootElement; + return Deserialize(element); + } + + private void SerializeFull(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + + writer.WritePropertyName("id"); + writer.WriteStringValue(Id); + + writer.WritePropertyName("child"); + Child.SerializeFull(writer); + + writer.WriteEndObject(); + } + + private void SerializePatch(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + + if (_changed[IdProperty]) + { + writer.WritePropertyName("id"); + writer.WriteStringValue(Id); + } + + if (_changed[ChildProperty]) + { + writer.WritePropertyName("child"); + if (Child == null) + { + writer.WriteNullValue(); + } + else + { + Child.SerializeFull(writer); + } + } + else if (_child.HasChanges) + { + writer.WritePropertyName("child"); + Child.SerializePatch(writer); + } + + writer.WriteEndObject(); + } + + void IModelJsonSerializable.Serialize(Utf8JsonWriter writer, ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + + if (options.Format.ToString() == ModelSerializerFormat.Json || + options.Format.ToString() == ModelSerializerFormat.Wire) + { + SerializeFull(writer); + } + else if (options.Format.ToString() == ModelSerializerFormat.JsonMergePatch) + { + SerializePatch(writer); + } + } + + BinaryData IModelSerializable.Serialize(ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + return ModelSerializer.SerializeCore(this, options); + } + + public static implicit operator RequestContent(ParentPatchModel model) + => RequestContent.Create(model, ModelSerializerOptions.DefaultWireOptions); + + public static explicit operator ParentPatchModel(Response response) + { + Argument.AssertNotNull(response, nameof(response)); + return Deserialize(response.Content, ModelSerializerOptions.DefaultWireOptions); + } + + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IModelJsonSerializable)this).Serialize(writer, ModelSerializerOptions.DefaultWireOptions); + } +} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/ParentPatchModel.cs b/sdk/core/Azure.Core/tests/public/PatchModels/ParentPatchModel.cs new file mode 100644 index 000000000000..9aed7699b312 --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/ParentPatchModel.cs @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Azure.Core.Tests.PatchModels +{ + /// + /// This model illustrates a patch model with properties that are nested models. + /// + public partial class ParentPatchModel + { + private BitVector64 _changed; + + /// + /// Public constructor. + /// + public ParentPatchModel() + { + } + + /// + /// Serialization constructor. + /// + internal ParentPatchModel(string id, ChildPatchModel child) + { + _id = id; + _child = child; + } + + private string _id; + private const int IdProperty = 0; + /// + /// Optional string property corresponding to JSON """{"id": "abc"}""". + /// + public string Id + { + get => _id; + set + { + _changed[IdProperty] = true; + _id = value; + } + } + + private ChildPatchModel _child; + private const int ChildProperty = 1; + /// + /// Optional ChildPatchModel property corresponding to JSON """{"child": {"a":"aa", "b": "bb"}}""". + /// + public ChildPatchModel Child + { + get + { + if (_child == null && !_changed[ChildProperty]) + { + _child = new ChildPatchModel(); + } + + return _child; + } + set + { + _changed[ChildProperty] = true; + _child = value; + } + } + } +} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/ParentPatchModelTests.cs b/sdk/core/Azure.Core/tests/public/PatchModels/ParentPatchModelTests.cs new file mode 100644 index 000000000000..a0469e6e640e --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/ParentPatchModelTests.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using Azure.Core.Serialization; +using Azure.Core.Tests.PatchModels; +using NUnit.Framework; + +namespace Azure.Core.Tests.Public.ModelSerializationTests +{ + internal class ParentPatchModelTests : ModelJsonTests + { + protected override string JsonPayload => """ + { + "id": "abc", + "child": {"a": "aa", "b": "bb"} + } + """; + + protected override string WirePayload => JsonPayload; + + protected override Func ToRequestContent => m => m == null ? null: RequestContent.Create(m, ModelSerializerOptions.DefaultWireOptions); + + protected override Func FromResponse => r => (ParentPatchModel)r; + + protected override void CompareModels(ParentPatchModel model, ParentPatchModel model2, ModelSerializerFormat format) + { + Assert.AreEqual(model.Child.A, model2.Child.A); + Assert.AreEqual(model.Child.B, model2.Child.B); + Assert.AreEqual(model.Id, model2.Id); + } + + protected override string GetExpectedResult(ModelSerializerFormat format) + { + return RemoveWhitespace(JsonPayload); + } + + protected override void VerifyModel(ParentPatchModel model, ModelSerializerFormat format) + { + Assert.AreEqual("aa", model.Child.A); + Assert.AreEqual("bb", model.Child.B); + Assert.AreEqual("abc", model.Id); + } + + private static string RemoveWhitespace(string value) => value.Replace("\r", "").Replace("\n", "").Replace(" ", ""); + } +} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/PatchModelTests.cs b/sdk/core/Azure.Core/tests/public/PatchModels/PatchModelTests.cs new file mode 100644 index 000000000000..a2756323957d --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/PatchModelTests.cs @@ -0,0 +1,398 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.Text.Json; +using Azure.Core.Serialization; +using Azure.Core.Tests.PatchModels; +using NUnit.Framework; + +namespace Azure.Core.Tests.Public +{ + public class PatchModelTests + { + #region SimplePatchModel + [Test] + public void CanPatchIntProperty() + { + SimplePatchModel model = new(); + model.Count = 2; + + ValidatePatch("""{"count":2}""", model); + } + + [Test] + public void CanPatchStringProperty() + { + SimplePatchModel model = new(); + model.Name = "abc"; + + ValidatePatch("""{"name":"abc"}""", model); + } + + [Test] + public void CanPatchDateTimeProperty() + { + DateTimeOffset updateTime = DateTimeOffset.Parse("2023-10-19T10:19:10.0190001Z"); + + SimplePatchModel model = new(); + model.UpdatedOn = updateTime; + + // TODO: fix test + Assert.AreEqual($"{{\"updatedOn\":\"{updateTime.UtcDateTime:O}\"}}", GetPatchJson(model)); + //ValidatePatch($"{{\"updatedOn\":\"{updateTime:O}\"}}", model); + } + + [Test] + public void CanRoundTripSimpleModel() + { + BinaryData json = BinaryData.FromString(""" + { + "name": "abc", + "count": 1 + } + """); + + SimplePatchModel model = ModelSerializer.Deserialize(json); + + Assert.AreEqual(1, model.Count); + Assert.AreEqual("abc", model.Name); + + model.Name = "xyz"; + model.Count = 2; + + ValidatePatch("""{"name":"xyz", "count":2}""", model); + } + #endregion + + #region NestedPatchModel + [Test] + public void CanPatchNestedModel() + { + ParentPatchModel model = new(); + + model.Child.B = "bb"; + + ValidatePatch("""{"child": {"b": "bb"}}""", model); + + model.Child.A = "aa"; + + ValidatePatch("""{"child": {"a": "aa", "b": "bb"}}""", model); + } + + [Test] + public void CanPatchNestedModel_DeleteChild() + { + ParentPatchModel model = new(); + model.Child = null; + + ValidatePatch("""{"child": null}""", model); + } + + [Test] + public void CanPatchNestedModelOneProperty() + { + ParentPatchModel model = new(); + + model.Child.A = "aa"; + + ValidatePatch("""{"child": {"a": "aa"}}""", model); + } + + [Test] + public void CanPatchNestedModelOnePropertyAndChangeIt() + { + ParentPatchModel model = new(); + + model.Child.A = "a1"; + + ValidatePatch("""{"child": {"a": "a1"}}""", model); + + model.Child.A = "a2"; + + ValidatePatch("""{"child": {"a": "a2"}}""", model); + } + + [Test] + public void CanPatchNestedModelInterleaveChanges() + { + ParentPatchModel model = new(); + + model.Id = "id1"; + model.Child.B = "b1"; + model.Child.A = "a1"; + + ValidatePatch("""{"id": "id1", "child": {"a": "a1", "b": "b1"}}""", model); + + model.Child.A = "a2"; + model.Id = "id2"; + + ValidatePatch("""{"id": "id2", "child": {"a": "a2", "b": "b1"}}""", model); + + model.Child.A = null; + model.Child.B = null; + + ValidatePatch("""{"id": "id2", "child": {"a": null, "b": null}}""", model); + } + + [Test] + public void CanRoundTripNestedModel() + { + BinaryData json = BinaryData.FromString(""" + { + "id": "123", + "child": { + "a": "aa", + "b": "bb" + } + } + """); + + ParentPatchModel model = ModelSerializer.Deserialize(json); + + Assert.AreEqual("123", model.Id); + Assert.AreEqual("aa", model.Child.A); + Assert.AreEqual("bb", model.Child.B); + + ValidateSerialize("""{"id": "123", "child": {"a": "aa", "b": "bb"}}""", model); + + // TODO: "{}" or "" ? Either is doable. + ValidatePatch("{}", model); + + model.Child.A = "a2"; + model.Child.B = null; + + ValidateSerialize("""{"id": "123", "child": {"a": "a2", "b": null}}""", model); + ValidatePatch("""{"child": {"a": "a2", "b": null}}""", model); + } + #endregion + + #region RoundTripPatchModel + [Test] + public void CanPatchInputOutputPatchProperty() + { + RoundTripPatchModel model = new("abc"); + model.Value = 1; + + Assert.AreEqual("abc", model.Id); + Assert.AreEqual(1, model.Value); + + ValidatePatch("""{"value":1}""", model); + } + + [Test] + public void CanRoundTripInputOutputPatchModel() + { + BinaryData json = BinaryData.FromString(""" + { + "id": "abc", + "value": 1 + } + """); + + RoundTripPatchModel model = ModelSerializer.Deserialize(json); + + Assert.AreEqual("abc", model.Id); + Assert.AreEqual(1, model.Value); + + ValidateSerialize("""{"id": "abc", "value": 1}""", model); + ValidatePatch("{}", model); + + model.Value = 2; + + ValidateSerialize("""{"id": "abc", "value": 2}""", model); + ValidatePatch("""{"value": 2}""", model); + } + #endregion + + //#region CollectionPatchModel + //[Test] + //public void CanPatchCollectionProperty() + //{ + // CollectionPatchModel model = new(); + // model.Variables["abc"] = "123"; + // model.Variables["xyz"] = "456"; + + // ValidatePatch("""{"variables": {"abc":"123", "xyz":"456"}}""", model); + //} + + //[Test] + //public void CanPatchCollectionProperty_DeleteItem() + //{ + // CollectionPatchModel model = new(); + // model.Variables["abc"] = "123"; + // model.Variables.Remove("abc"); + + // ValidatePatch("""{"variables": {"abc": null}}""", model); + //} + + //[Test] + //public void CanPatchCollectionProperty_ClearItems() + //{ + // BinaryData json = BinaryData.FromString(""" + // { + // "id": "abc", + // "variables": + // { + // "a": "aa", + // "b": "bb" + // } + // } + // """); + + // CollectionPatchModel model = ModelSerializer.Deserialize(json); + // model.Variables.Clear(); + + // ValidatePatch("""{"variables": {"a": null, "b":null}}""", model); + //} + + //[Test] + //public void CanRoundTripCollectionPatchModel() + //{ + // BinaryData json = BinaryData.FromString(""" + // { + // "id": "abc", + // "variables": + // { + // "a": "aa", + // "b": "bb" + // } + // } + // """); + + // CollectionPatchModel model = ModelSerializer.Deserialize(json); + + // Assert.AreEqual("abc", model.Id); + // Assert.AreEqual("aa", model.Variables["a"]); + // Assert.AreEqual("bb", model.Variables["b"]); + + // ValidateSerialize("""{"id": "abc","variables":{"a": "aa","b": "bb"}}""", model); + // ValidatePatch("{}", model); + + // model.Variables["a"] = "a2"; + + // ValidateSerialize("""{"id": "abc","variables":{"a": "a2","b": "bb"}}""", model); + // ValidatePatch("""{"variables": {"a":"a2"}}""", model); + + // model.Variables.Remove("b"); + + // ValidateSerialize("""{"id": "abc","variables":{"a": "a2"}}""", model); + // ValidatePatch("""{"variables": {"a":"a2", "b": null}}""", model); + //} + + //[Test] + //public void CanRoundTripCollectionPatchModel_ChangeChildren() + //{ + // string jsonString = """ + // { + // "id": "abc", + // "variables": + // { + // "a": "aa", + // "b": "bb" + // }, + // "children" : + // { + // "first": + // { + // "a": "a1", + // "b": "b1" + // }, + // "second": + // { + // "a": "a2", + // "b": "b2" + // } + // } + // } + // """; + // BinaryData json = BinaryData.FromString(jsonString); + + // CollectionPatchModel model = ModelSerializer.Deserialize(json); + + // Assert.AreEqual("abc", model.Id); + // Assert.AreEqual("aa", model.Variables["a"]); + // Assert.AreEqual("bb", model.Variables["b"]); + + // Assert.AreEqual("a1", model.Children["first"].A); + // Assert.AreEqual("b1", model.Children["first"].B); + + // Assert.AreEqual("a2", model.Children["second"].A); + // Assert.AreEqual("b2", model.Children["second"].B); + + // ValidateSerialize(jsonString, model); + // ValidatePatch("{}", model); + + // model.Children["first"].A = "a11"; + + // ValidateSerialize("""{"id": "abc","variables":{"a": "aa","b": "bb"},"children":{"first": {"a":"a11","b":"b1"},"second": {"a":"a2","b":"b2"}}}""", model); + // ValidatePatch("""{"children": {"first":{"a":"a11"}}}""", model); + + // model.Variables.Remove("b"); + + // ValidateSerialize("""{"id": "abc","variables":{"a": "aa"},"children":{"first": {"a":"a11","b":"b1"},"second": {"a":"a2","b":"b2"}}}""", model); + // ValidatePatch("""{"variables": {"b": null}, "children": {"first":{"a":"a11"}}}""", model); + //} + //#endregion + + #region Helpers + private static void ValidateSerialize(string expected, IModelJsonSerializable model) + { + using Stream stream = new MemoryStream(); + using Utf8JsonWriter writer = new(stream); + model.Serialize(writer, new ModelSerializerOptions("J")); + writer.Flush(); + stream.Position = 0; + + string actual = BinaryData.FromStream(stream).ToString(); + + AreEqualJson(expected, actual); + } + + private string GetPatchJson(IModelJsonSerializable model) + { + using Stream stream = new MemoryStream(); + using Utf8JsonWriter writer = new(stream); + model.Serialize(writer, new ModelSerializerOptions("P")); + writer.Flush(); + stream.Position = 0; + + return BinaryData.FromStream(stream).ToString(); + } + + private static void ValidatePatch(string expected, IModelJsonSerializable model) + { + using Stream stream = new MemoryStream(); + using Utf8JsonWriter writer = new(stream); + model.Serialize(writer, new ModelSerializerOptions("P")); + writer.Flush(); + stream.Position = 0; + + string actual = BinaryData.FromStream(stream).ToString(); + + if (expected.Length == 0) + { + Assert.AreEqual(expected, actual); + return; + } + + AreEqualJson(expected, actual); + } + + private static void AreEqualJson(string expected, string actual) + { + JsonDocument doc = JsonDocument.Parse(expected); + + using MemoryStream stream = new(); + using Utf8JsonWriter writer = new(stream); + doc.WriteTo(writer); + writer.Flush(); + stream.Position = 0; + BinaryData buffer = BinaryData.FromStream(stream); + + Assert.AreEqual(buffer.ToString(), actual); + } + #endregion + } +} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/RoundTripPatchModel.Serialization.cs b/sdk/core/Azure.Core/tests/public/PatchModels/RoundTripPatchModel.Serialization.cs new file mode 100644 index 000000000000..a326cb52cc16 --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/RoundTripPatchModel.Serialization.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Text.Json; +using Azure.Core.Serialization; + +namespace Azure.Core.Tests.PatchModels +{ + public partial class RoundTripPatchModel : IModelJsonSerializable, IUtf8JsonSerializable + { + private static RoundTripPatchModel Deserialize(JsonElement element) + { + string id = default; + int value = default; + + foreach (JsonProperty property in element.EnumerateObject()) + { + if (property.NameEquals("id")) + { + id = property.Value.GetString(); + continue; + } + + if (property.NameEquals("value")) + { + value = property.Value.GetInt32(); + continue; + } + } + + return new RoundTripPatchModel(id, value); + } + + RoundTripPatchModel IModelJsonSerializable.Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + + return Deserialize(ref reader, options); + } + + private static RoundTripPatchModel Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) + { + JsonElement element = JsonDocument.ParseValue(ref reader).RootElement; + return Deserialize(element); + } + + RoundTripPatchModel IModelSerializable.Deserialize(BinaryData data, ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + + return Deserialize(data, options); + } + + private static RoundTripPatchModel Deserialize(BinaryData data, ModelSerializerOptions options) + { + JsonElement element = JsonDocument.Parse(data).RootElement; + return Deserialize(element); + } + + private void SerializeFull(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + + writer.WritePropertyName("id"); + writer.WriteStringValue(Id); + + writer.WritePropertyName("value"); + if (Value is null) + { + writer.WriteNullValue(); + } + else + { + writer.WriteNumberValue(Value.Value); + } + + writer.WriteEndObject(); + } + + private void SerializePatch(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + + // Id isn't modifiable. + + if (_valuePatchFlag) + { + writer.WritePropertyName("value"); + if (Value is null) + { + writer.WriteNullValue(); + } + else + { + writer.WriteNumberValue(Value.Value); + } + } + + writer.WriteEndObject(); + } + + void IModelJsonSerializable.Serialize(Utf8JsonWriter writer, ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + + if (options.Format.ToString() == ModelSerializerFormat.Json || + options.Format.ToString() == ModelSerializerFormat.Wire) + { + SerializeFull(writer); + } + else if (options.Format.ToString() == ModelSerializerFormat.JsonMergePatch) + { + SerializePatch(writer); + } + } + + BinaryData IModelSerializable.Serialize(ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + + return ModelSerializer.SerializeCore(this, options); + } + + public static implicit operator RequestContent(RoundTripPatchModel model) + => RequestContent.Create(model, ModelSerializerOptions.DefaultWireOptions); + + public static explicit operator RoundTripPatchModel(Response response) + { + Argument.AssertNotNull(response, nameof(response)); + + return Deserialize(response.Content, ModelSerializerOptions.DefaultWireOptions); + } + + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IModelJsonSerializable)this).Serialize(writer, ModelSerializerOptions.DefaultWireOptions); + } +} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/RoundTripPatchModel.cs b/sdk/core/Azure.Core/tests/public/PatchModels/RoundTripPatchModel.cs new file mode 100644 index 000000000000..382f2673d40f --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/RoundTripPatchModel.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Azure.Core.Tests.PatchModels +{ + /// + /// This model illustrates a model that can be used for both GET and PATCH operations. + /// + /// For GET operations, a model is an output model, as described by https://github.com/Azure/autorest.csharp/issues/2341 + /// For PATCH operations, a model is an input model, as described by https://github.com/Azure/autorest.csharp/issues/2339 + /// For both, a model is a round-trip model, as described by https://github.com/Azure/autorest.csharp/issues/2463 + /// + public partial class RoundTripPatchModel + { + /// + /// Public constructor. + /// + public RoundTripPatchModel(string id) + { + _id = id; + } + + /// + /// Deserialization constructor. + /// + internal RoundTripPatchModel() { } + + /// + /// Serialization constructor. + /// + internal RoundTripPatchModel(string id, int value) + { + _id = id; + _value = value; + } + + private string _id; + /// + /// Required and read-only string property corresponding to JSON """{"id": "abc"}""". + /// + public string Id => _id; + + private int? _value; + private bool _valuePatchFlag; + /// + /// Optional read/write int property corresponding to JSON """{"value": 1}""". + /// + public int? Value + { + get => _value; + set + { + _value = value; + _valuePatchFlag = true; + } + } +#pragma warning restore AZC0020 // Avoid using banned types in libraries + } +} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/RoundTripPatchModelTests.cs b/sdk/core/Azure.Core/tests/public/PatchModels/RoundTripPatchModelTests.cs new file mode 100644 index 000000000000..6a2925f47420 --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/RoundTripPatchModelTests.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using Azure.Core.Serialization; +using Azure.Core.Tests.PatchModels; +using NUnit.Framework; + +namespace Azure.Core.Tests.Public.ModelSerializationTests +{ + internal class RoundTripPatchModelTests : ModelJsonTests + { + protected override string JsonPayload => """ + { + "id": "abc", + "value": 1 + } + """; + + protected override string WirePayload => JsonPayload; + + protected override Func ToRequestContent => m => m == null ? null: RequestContent.Create(m, ModelSerializerOptions.DefaultWireOptions); + + protected override Func FromResponse => r => (RoundTripPatchModel)r; + + protected override void CompareModels(RoundTripPatchModel model, RoundTripPatchModel model2, ModelSerializerFormat format) + { + Assert.AreEqual(model.Id, model2.Id); + Assert.AreEqual(model.Value, model2.Value); + } + + protected override string GetExpectedResult(ModelSerializerFormat format) + { + return RemoveWhitespace(JsonPayload); + } + + protected override void VerifyModel(RoundTripPatchModel model, ModelSerializerFormat format) + { + Assert.AreEqual("abc", model.Id); + Assert.AreEqual(1, model.Value); + } + + private static string RemoveWhitespace(string value) => value.Replace("\r", "").Replace("\n", "").Replace(" ", ""); + } +} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/SimplePatchModel.Serialization.cs b/sdk/core/Azure.Core/tests/public/PatchModels/SimplePatchModel.Serialization.cs new file mode 100644 index 000000000000..05bb6ffd864b --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/SimplePatchModel.Serialization.cs @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Text.Json; +using Azure.Core.Serialization; + +namespace Azure.Core.Tests.PatchModels +{ + public partial class SimplePatchModel : IModelJsonSerializable, IUtf8JsonSerializable + { + private static SimplePatchModel Deserialize(JsonElement element) + { + string name = default; + int count = default; + DateTimeOffset updatedOn = default; + + foreach (JsonProperty property in element.EnumerateObject()) + { + if (property.NameEquals("name")) + { + name = property.Value.GetString(); + continue; + } + + if (property.NameEquals("count")) + { + count = property.Value.GetInt32(); + continue; + } + + if (property.NameEquals("updatedOn")) + { + updatedOn = property.Value.GetDateTimeOffset("O"); + continue; + } + } + + return new SimplePatchModel(name, count, updatedOn); + } + + SimplePatchModel IModelJsonSerializable.Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + return Deserialize(ref reader, options); + } + + private static SimplePatchModel Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) + { + JsonElement element = JsonDocument.ParseValue(ref reader).RootElement; + return Deserialize(element); + } + + SimplePatchModel IModelSerializable.Deserialize(BinaryData data, ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + return Deserialize(data, options); + } + + private static SimplePatchModel Deserialize(BinaryData data, ModelSerializerOptions options) + { + JsonElement element = JsonDocument.Parse(data).RootElement; + return Deserialize(element); + } + + private void SerializeFull(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + + writer.WritePropertyName("name"); + writer.WriteStringValue(Name); + + writer.WritePropertyName("count"); + writer.WriteNumberValue(Count); + + writer.WritePropertyName("updatedOn"); + writer.WriteStringValue(UpdatedOn, "O"); + + writer.WriteEndObject(); + } + + private void SerializePatch(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + + if (_changed[NameProperty]) + { + writer.WritePropertyName("name"); + writer.WriteStringValue(Name); + } + + if (_changed[CountProperty]) + { + writer.WritePropertyName("count"); + writer.WriteNumberValue(Count); + } + + if (_changed[UpdatedOnProperty]) + { + writer.WritePropertyName("updatedOn"); + writer.WriteStringValue(UpdatedOn, "O"); + } + + writer.WriteEndObject(); + } + + void IModelJsonSerializable.Serialize(Utf8JsonWriter writer, ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + + if (options.Format.ToString() == ModelSerializerFormat.Json || + options.Format.ToString() == ModelSerializerFormat.Wire) + { + SerializeFull(writer); + } + else if (options.Format.ToString() == ModelSerializerFormat.JsonMergePatch) + { + SerializePatch(writer); + } + } + + BinaryData IModelSerializable.Serialize(ModelSerializerOptions options) + { + ModelSerializerHelper.ValidatePatchFormat(this, options.Format); + return ModelSerializer.SerializeCore(this, options); + } + + public static implicit operator RequestContent(SimplePatchModel model) + => RequestContent.Create(model, ModelSerializerOptions.DefaultWireOptions); + + public static explicit operator SimplePatchModel(Response response) + { + Argument.AssertNotNull(response, nameof(response)); + return Deserialize(response.Content, ModelSerializerOptions.DefaultWireOptions); + } + + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IModelJsonSerializable)this).Serialize(writer, ModelSerializerOptions.DefaultWireOptions); + } +} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/SimplePatchModel.cs b/sdk/core/Azure.Core/tests/public/PatchModels/SimplePatchModel.cs new file mode 100644 index 000000000000..655147a53df5 --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/SimplePatchModel.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; + +namespace Azure.Core.Tests.PatchModels +{ + /// + /// This model illustrates optional read/write "primitive" properties. + /// + public partial class SimplePatchModel + { + private BitVector64 _changed; + + /// + /// Public constructor. + /// + public SimplePatchModel() + { + } + + /// + /// Serialization constructor. + /// + /// + internal SimplePatchModel(string name, int count, DateTimeOffset updatedOn) + { + _name = name; + _count = count; + _updatedOn = updatedOn; + } + + private string _name; + private const int NameProperty = 0; + /// + /// Optional string property corresponding to JSON """{"name": "abc"}""". + /// + public string Name + { + get => _name; + set + { + _changed[NameProperty] = true; + _name = value; + } + } + + private int _count; + private const int CountProperty = 1; + /// + /// Optional int property corresponding to JSON """{"count": 1}""". + /// + public int Count + { + get => _count; + set + { + _changed[CountProperty] = true; + _count = value; + } + } + + private DateTimeOffset _updatedOn; + private const int UpdatedOnProperty = 2; + /// + /// Optional DateTimeOffset property corresponding to JSON """{"updatedOn": "2020-06-25T17:44:37.6830000Z"}""". + /// + public DateTimeOffset UpdatedOn + { + get => _updatedOn; + set + { + _changed[UpdatedOnProperty] = true; + _updatedOn = value; + } + } + } +} diff --git a/sdk/core/Azure.Core/tests/public/PatchModels/SimplePatchModelTests.cs b/sdk/core/Azure.Core/tests/public/PatchModels/SimplePatchModelTests.cs new file mode 100644 index 000000000000..1e846b7b2925 --- /dev/null +++ b/sdk/core/Azure.Core/tests/public/PatchModels/SimplePatchModelTests.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using Azure.Core.Serialization; +using Azure.Core.Tests.PatchModels; +using NUnit.Framework; + +namespace Azure.Core.Tests.Public.ModelSerializationTests +{ + internal class SimplePatchModelTests : ModelJsonTests + { + protected override string JsonPayload => """ + { + "name": "abc", + "count": 1, + "updatedOn": "2023-10-19T10:19:10.0190001Z" + } + """; + + protected override string WirePayload => JsonPayload; + + protected override Func ToRequestContent => m => m == null ? null: RequestContent.Create(m, ModelSerializerOptions.DefaultWireOptions); + + protected override Func FromResponse => r => (SimplePatchModel)r; + + protected override void CompareModels(SimplePatchModel model, SimplePatchModel model2, ModelSerializerFormat format) + { + Assert.AreEqual(model.Name, model2.Name); + Assert.AreEqual(model.Count, model2.Count); + Assert.AreEqual(model.UpdatedOn, model2.UpdatedOn); + } + + protected override string GetExpectedResult(ModelSerializerFormat format) + { + return RemoveWhitespace(JsonPayload); + } + + protected override void VerifyModel(SimplePatchModel model, ModelSerializerFormat format) + { + Assert.AreEqual("abc", model.Name); + Assert.AreEqual(1, model.Count); + Assert.AreEqual(DateTimeOffset.Parse("2023-10-19T10:19:10.0190001Z"), model.UpdatedOn); + } + + private static string RemoveWhitespace(string value) => value.Replace("\r", "").Replace("\n", "").Replace(" ", ""); + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/Azure.Developer.LoadTesting.sln b/sdk/loadtestservice/Azure.Developer.LoadTesting/Azure.Developer.LoadTesting.sln index 606ba56f6d8d..ff6624c11f62 100644 --- a/sdk/loadtestservice/Azure.Developer.LoadTesting/Azure.Developer.LoadTesting.sln +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/Azure.Developer.LoadTesting.sln @@ -13,6 +13,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Developer.LoadTesting EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Test.Perf", "..\..\..\common\Perf\Azure.Test.Perf\Azure.Test.Perf.csproj", "{1FEEF7F8-FE15-4A10-9E00-13F9DBC07D4B}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core", "..\..\core\Azure.Core\src\Azure.Core.csproj", "{D2EFFAEB-5CFE-4C50-AC4C-A58627F6653D}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core.Tests.Public", "..\..\core\Azure.Core\tests\public\Azure.Core.Tests.Public.csproj", "{B3B59E54-AF72-4353-AA9C-AAFF525833B1}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core.Tests.Common", "..\..\core\Azure.Core\tests\common\Azure.Core.Tests.Common.csproj", "{5AF9B5AD-629A-4BF1-988F-494A0D481B68}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -39,6 +45,18 @@ Global {1FEEF7F8-FE15-4A10-9E00-13F9DBC07D4B}.Debug|Any CPU.Build.0 = Debug|Any CPU {1FEEF7F8-FE15-4A10-9E00-13F9DBC07D4B}.Release|Any CPU.ActiveCfg = Release|Any CPU {1FEEF7F8-FE15-4A10-9E00-13F9DBC07D4B}.Release|Any CPU.Build.0 = Release|Any CPU + {D2EFFAEB-5CFE-4C50-AC4C-A58627F6653D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D2EFFAEB-5CFE-4C50-AC4C-A58627F6653D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D2EFFAEB-5CFE-4C50-AC4C-A58627F6653D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D2EFFAEB-5CFE-4C50-AC4C-A58627F6653D}.Release|Any CPU.Build.0 = Release|Any CPU + {B3B59E54-AF72-4353-AA9C-AAFF525833B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B3B59E54-AF72-4353-AA9C-AAFF525833B1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B3B59E54-AF72-4353-AA9C-AAFF525833B1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B3B59E54-AF72-4353-AA9C-AAFF525833B1}.Release|Any CPU.Build.0 = Release|Any CPU + {5AF9B5AD-629A-4BF1-988F-494A0D481B68}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5AF9B5AD-629A-4BF1-988F-494A0D481B68}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5AF9B5AD-629A-4BF1-988F-494A0D481B68}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5AF9B5AD-629A-4BF1-988F-494A0D481B68}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/api/Azure.Developer.LoadTesting.netstandard2.0.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/api/Azure.Developer.LoadTesting.netstandard2.0.cs index 9b6fafbf3afe..d86853795593 100644 --- a/sdk/loadtestservice/Azure.Developer.LoadTesting/api/Azure.Developer.LoadTesting.netstandard2.0.cs +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/api/Azure.Developer.LoadTesting.netstandard2.0.cs @@ -22,7 +22,9 @@ public LoadTestAdministrationClient(System.Uri endpoint, Azure.Core.TokenCredent public virtual System.Threading.Tasks.Task CreateOrUpdateAppComponentsAsync(string testId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } public virtual Azure.Response CreateOrUpdateServerMetricsConfig(string testId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } public virtual System.Threading.Tasks.Task CreateOrUpdateServerMetricsConfigAsync(string testId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response CreateOrUpdateTest(Azure.Developer.LoadTesting.Models.Test test, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response CreateOrUpdateTest(string testId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> CreateOrUpdateTestAsync(Azure.Developer.LoadTesting.Models.Test test, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task CreateOrUpdateTestAsync(string testId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } public virtual Azure.Response DeleteTest(string testId, Azure.RequestContext context = null) { throw null; } public virtual System.Threading.Tasks.Task DeleteTestAsync(string testId, Azure.RequestContext context = null) { throw null; } @@ -99,13 +101,261 @@ public TestRunResultOperation(string testRunId, Azure.Developer.LoadTesting.Load public override System.Threading.Tasks.ValueTask UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } } +namespace Azure.Developer.LoadTesting.Models +{ + public partial class CertificateMetadata + { + public CertificateMetadata() { } + public string Name { get { throw null; } set { } } + public Azure.Developer.LoadTesting.Models.CertificateType? Type { get { throw null; } set { } } + public string Value { get { throw null; } set { } } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct CertificateType : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public CertificateType(string value) { throw null; } + public static Azure.Developer.LoadTesting.Models.CertificateType AKVCertURI { get { throw null; } } + public bool Equals(Azure.Developer.LoadTesting.Models.CertificateType other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Developer.LoadTesting.Models.CertificateType left, Azure.Developer.LoadTesting.Models.CertificateType right) { throw null; } + public static implicit operator Azure.Developer.LoadTesting.Models.CertificateType (string value) { throw null; } + public static bool operator !=(Azure.Developer.LoadTesting.Models.CertificateType left, Azure.Developer.LoadTesting.Models.CertificateType right) { throw null; } + public override string ToString() { throw null; } + } + public partial class FileInfo + { + internal FileInfo() { } + public System.DateTimeOffset? ExpireDateTime { get { throw null; } } + public string FileName { get { throw null; } } + public Azure.Developer.LoadTesting.Models.FileType? FileType { get { throw null; } } + public string Url { get { throw null; } } + public string ValidationFailureDetails { get { throw null; } } + public Azure.Developer.LoadTesting.Models.FileStatus? ValidationStatus { get { throw null; } } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct FileStatus : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public FileStatus(string value) { throw null; } + public static Azure.Developer.LoadTesting.Models.FileStatus NOTValidated { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.FileStatus ValidationFailure { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.FileStatus ValidationInitiated { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.FileStatus ValidationNOTRequired { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.FileStatus ValidationSuccess { get { throw null; } } + public bool Equals(Azure.Developer.LoadTesting.Models.FileStatus other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Developer.LoadTesting.Models.FileStatus left, Azure.Developer.LoadTesting.Models.FileStatus right) { throw null; } + public static implicit operator Azure.Developer.LoadTesting.Models.FileStatus (string value) { throw null; } + public static bool operator !=(Azure.Developer.LoadTesting.Models.FileStatus left, Azure.Developer.LoadTesting.Models.FileStatus right) { throw null; } + public override string ToString() { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct FileType : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public FileType(string value) { throw null; } + public static Azure.Developer.LoadTesting.Models.FileType AdditionalArtifacts { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.FileType JMXFile { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.FileType UserProperties { get { throw null; } } + public bool Equals(Azure.Developer.LoadTesting.Models.FileType other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Developer.LoadTesting.Models.FileType left, Azure.Developer.LoadTesting.Models.FileType right) { throw null; } + public static implicit operator Azure.Developer.LoadTesting.Models.FileType (string value) { throw null; } + public static bool operator !=(Azure.Developer.LoadTesting.Models.FileType left, Azure.Developer.LoadTesting.Models.FileType right) { throw null; } + public override string ToString() { throw null; } + } + public partial class LoadTestConfiguration + { + public LoadTestConfiguration() { } + public int? EngineInstances { get { throw null; } set { } } + public Azure.Developer.LoadTesting.Models.OptionalLoadTestConfig OptionalLoadTestConfig { get { throw null; } set { } } + public bool? QuickStartTest { get { throw null; } set { } } + public bool? SplitAllCSVs { get { throw null; } set { } } + } + public partial class OptionalLoadTestConfig + { + public OptionalLoadTestConfig() { } + public int? Duration { get { throw null; } set { } } + public string EndpointUrl { get { throw null; } set { } } + public int? RampUpTime { get { throw null; } set { } } + public int? VirtualUsers { get { throw null; } set { } } + } + public partial class PassFailCriteria + { + public PassFailCriteria() { } + public System.Collections.Generic.IDictionary PassFailMetrics { get { throw null; } } + } + public partial class PassFailMetric + { + public PassFailMetric() { } + public Azure.Developer.LoadTesting.Models.PFAction? Action { get { throw null; } set { } } + public double? ActualValue { get { throw null; } } + public Azure.Developer.LoadTesting.Models.PFAgFunc? Aggregate { get { throw null; } set { } } + public Azure.Developer.LoadTesting.Models.PFMetrics? ClientMetric { get { throw null; } set { } } + public string Condition { get { throw null; } set { } } + public string RequestName { get { throw null; } set { } } + public Azure.Developer.LoadTesting.Models.PFResult? Result { get { throw null; } } + public double? Value { get { throw null; } set { } } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct PFAction : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public PFAction(string value) { throw null; } + public static Azure.Developer.LoadTesting.Models.PFAction Continue { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFAction Stop { get { throw null; } } + public bool Equals(Azure.Developer.LoadTesting.Models.PFAction other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Developer.LoadTesting.Models.PFAction left, Azure.Developer.LoadTesting.Models.PFAction right) { throw null; } + public static implicit operator Azure.Developer.LoadTesting.Models.PFAction (string value) { throw null; } + public static bool operator !=(Azure.Developer.LoadTesting.Models.PFAction left, Azure.Developer.LoadTesting.Models.PFAction right) { throw null; } + public override string ToString() { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct PFAgFunc : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public PFAgFunc(string value) { throw null; } + public static Azure.Developer.LoadTesting.Models.PFAgFunc Avg { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFAgFunc Count { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFAgFunc Max { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFAgFunc Min { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFAgFunc P50 { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFAgFunc P90 { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFAgFunc P95 { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFAgFunc P99 { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFAgFunc Percentage { get { throw null; } } + public bool Equals(Azure.Developer.LoadTesting.Models.PFAgFunc other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Developer.LoadTesting.Models.PFAgFunc left, Azure.Developer.LoadTesting.Models.PFAgFunc right) { throw null; } + public static implicit operator Azure.Developer.LoadTesting.Models.PFAgFunc (string value) { throw null; } + public static bool operator !=(Azure.Developer.LoadTesting.Models.PFAgFunc left, Azure.Developer.LoadTesting.Models.PFAgFunc right) { throw null; } + public override string ToString() { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct PFMetrics : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public PFMetrics(string value) { throw null; } + public static Azure.Developer.LoadTesting.Models.PFMetrics Error { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFMetrics Latency { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFMetrics Requests { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFMetrics RequestsPerSec { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFMetrics ResponseTimeMs { get { throw null; } } + public bool Equals(Azure.Developer.LoadTesting.Models.PFMetrics other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Developer.LoadTesting.Models.PFMetrics left, Azure.Developer.LoadTesting.Models.PFMetrics right) { throw null; } + public static implicit operator Azure.Developer.LoadTesting.Models.PFMetrics (string value) { throw null; } + public static bool operator !=(Azure.Developer.LoadTesting.Models.PFMetrics left, Azure.Developer.LoadTesting.Models.PFMetrics right) { throw null; } + public override string ToString() { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct PFResult : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public PFResult(string value) { throw null; } + public static Azure.Developer.LoadTesting.Models.PFResult Failed { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFResult Passed { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.PFResult Undetermined { get { throw null; } } + public bool Equals(Azure.Developer.LoadTesting.Models.PFResult other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Developer.LoadTesting.Models.PFResult left, Azure.Developer.LoadTesting.Models.PFResult right) { throw null; } + public static implicit operator Azure.Developer.LoadTesting.Models.PFResult (string value) { throw null; } + public static bool operator !=(Azure.Developer.LoadTesting.Models.PFResult left, Azure.Developer.LoadTesting.Models.PFResult right) { throw null; } + public override string ToString() { throw null; } + } + public partial class Secret + { + public Secret() { } + public Azure.Developer.LoadTesting.Models.SecretType? Type { get { throw null; } set { } } + public string Value { get { throw null; } set { } } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct SecretType : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public SecretType(string value) { throw null; } + public static Azure.Developer.LoadTesting.Models.SecretType AKVSecretURI { get { throw null; } } + public static Azure.Developer.LoadTesting.Models.SecretType SecretValue { get { throw null; } } + public bool Equals(Azure.Developer.LoadTesting.Models.SecretType other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Developer.LoadTesting.Models.SecretType left, Azure.Developer.LoadTesting.Models.SecretType right) { throw null; } + public static implicit operator Azure.Developer.LoadTesting.Models.SecretType (string value) { throw null; } + public static bool operator !=(Azure.Developer.LoadTesting.Models.SecretType left, Azure.Developer.LoadTesting.Models.SecretType right) { throw null; } + public override string ToString() { throw null; } + } + public partial class Test : Azure.Core.Serialization.IModelJsonSerializable, Azure.Core.Serialization.IModelSerializable + { + public Test() { } + public Azure.Developer.LoadTesting.Models.CertificateMetadata Certificate { get { throw null; } set { } } + public string CreatedBy { get { throw null; } } + public System.DateTimeOffset? CreatedDateTime { get { throw null; } } + public string Description { get { throw null; } set { } } + public string DisplayName { get { throw null; } set { } } + public System.Collections.Generic.IDictionary EnvironmentVariables { get { throw null; } } + public Azure.Developer.LoadTesting.Models.TestInputArtifacts InputArtifacts { get { throw null; } } + public string KeyvaultReferenceIdentityId { get { throw null; } set { } } + public string KeyvaultReferenceIdentityType { get { throw null; } set { } } + public string LastModifiedBy { get { throw null; } } + public System.DateTimeOffset? LastModifiedDateTime { get { throw null; } } + public Azure.Developer.LoadTesting.Models.LoadTestConfiguration LoadTestConfiguration { get { throw null; } set { } } + public Azure.Developer.LoadTesting.Models.PassFailCriteria PassFailCriteria { get { throw null; } set { } } + public System.Collections.Generic.IDictionary Secrets { get { throw null; } } + public string SubnetId { get { throw null; } set { } } + public string TestId { get { throw null; } } + Azure.Developer.LoadTesting.Models.Test Azure.Core.Serialization.IModelJsonSerializable.Deserialize(ref System.Text.Json.Utf8JsonReader reader, Azure.Core.Serialization.ModelSerializerOptions options) { throw null; } + void Azure.Core.Serialization.IModelJsonSerializable.Serialize(System.Text.Json.Utf8JsonWriter writer, Azure.Core.Serialization.ModelSerializerOptions options) { } + Azure.Developer.LoadTesting.Models.Test Azure.Core.Serialization.IModelSerializable.Deserialize(System.BinaryData data, Azure.Core.Serialization.ModelSerializerOptions options) { throw null; } + System.BinaryData Azure.Core.Serialization.IModelSerializable.Serialize(Azure.Core.Serialization.ModelSerializerOptions options) { throw null; } + public static explicit operator Azure.Developer.LoadTesting.Models.Test (Azure.Response response) { throw null; } + public static implicit operator Azure.Core.RequestContent (Azure.Developer.LoadTesting.Models.Test model) { throw null; } + } + public partial class TestInputArtifacts + { + internal TestInputArtifacts() { } + public System.Collections.Generic.IReadOnlyList AdditionalFileInfo { get { throw null; } } + public Azure.Developer.LoadTesting.Models.FileInfo ConfigFileInfo { get { throw null; } } + public Azure.Developer.LoadTesting.Models.FileInfo InputArtifactsZipFileInfo { get { throw null; } } + public Azure.Developer.LoadTesting.Models.FileInfo TestScriptFileInfo { get { throw null; } } + public Azure.Developer.LoadTesting.Models.FileInfo UserPropFileInfo { get { throw null; } } + } +} namespace Microsoft.Extensions.Azure { public static partial class AzureLoadTestingClientBuilderExtensions { - public static Azure.Core.Extensions.IAzureClientBuilder AddLoadTestAdministrationClient(this TBuilder builder, System.Uri endpoint) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } - public static Azure.Core.Extensions.IAzureClientBuilder AddLoadTestAdministrationClient(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration { throw null; } - public static Azure.Core.Extensions.IAzureClientBuilder AddLoadTestRunClient(this TBuilder builder, System.Uri endpoint) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } - public static Azure.Core.Extensions.IAzureClientBuilder AddLoadTestRunClient(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration { throw null; } } } diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Azure.Developer.LoadTesting.csproj b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Azure.Developer.LoadTesting.csproj index 7909176cc8ce..ecc6042b31b4 100644 --- a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Azure.Developer.LoadTesting.csproj +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Azure.Developer.LoadTesting.csproj @@ -8,6 +8,7 @@ Azure LoadTestService $(RequiredTargetFrameworks) true + AZC0012;AZC0001;CS1591 @@ -17,8 +18,12 @@ - + + + + + diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Generated/LoadTestAdministrationClient.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Generated/LoadTestAdministrationClient.cs index ec331b121210..5b42d20b3a93 100644 --- a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Generated/LoadTestAdministrationClient.cs +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Generated/LoadTestAdministrationClient.cs @@ -221,7 +221,7 @@ public virtual Response DeleteTest(string testId, RequestContext context = null) /// Service returned a non-success status code. /// The response returned from the service. /// - public virtual async Task GetTestAsync(string testId, RequestContext context = null) + public virtual async Task GetTestAsync(string testId, RequestContext context) { Argument.AssertNotNullOrEmpty(testId, nameof(testId)); @@ -256,7 +256,7 @@ public virtual async Task GetTestAsync(string testId, RequestContext c /// Service returned a non-success status code. /// The response returned from the service. /// - public virtual Response GetTest(string testId, RequestContext context = null) + public virtual Response GetTest(string testId, RequestContext context) { Argument.AssertNotNullOrEmpty(testId, nameof(testId)); diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/LoadTestAdministrationClient.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/LoadTestAdministrationClient.cs index 0a8725651190..82ba1a586f2d 100644 --- a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/LoadTestAdministrationClient.cs +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/LoadTestAdministrationClient.cs @@ -2,9 +2,13 @@ // Licensed under the MIT License. using System; +using System.IO; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure.Core; +using Azure.Core.Serialization; +using Azure.Developer.LoadTesting.Models; namespace Azure.Developer.LoadTesting { @@ -127,5 +131,74 @@ public virtual Pageable GetTests(string orderby = null, string searc HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetTestsNextPageRequest(nextLink, orderby, search, lastModifiedStartTime, lastModifiedEndTime, pageSizeHint, context); return PageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "LoadTestAdministrationClient.GetTests", "value", "nextLink", context); } + + public virtual async Task> GetTestAsync(string id, CancellationToken cancellationToken = default) + { + Response response = await GetTestAsync(id, new RequestContext() { CancellationToken = cancellationToken }).ConfigureAwait(false); + return Response.FromValue((Test)response, response); + } + + public virtual Response GetTest(string id, CancellationToken cancellationToken = default) + { + Response response = GetTest(id, new RequestContext() { CancellationToken = cancellationToken }); + return Response.FromValue((Test)response, response); + } + + /// + /// + /// + /// + /// + public virtual async Task> CreateOrUpdateTestAsync(Test test, CancellationToken cancellationToken = default) + { + if (test is not IModelJsonSerializable serializable) + { + throw new InvalidCastException("model is not serializable"); + } + + using Stream stream = new MemoryStream(); + using (Utf8JsonWriter writer = new(stream)) + { + serializable.Serialize(writer, new ModelSerializerOptions("P")); + } + + stream.Position = 0; + RequestContent content = RequestContent.Create(stream); + + // TODO: was there a good way to get RequestContext without creating it new? + RequestContext context = new() { CancellationToken = cancellationToken }; + + Response response = await CreateOrUpdateTestAsync(test.TestId, content, context).ConfigureAwait(false); + + return Response.FromValue((Test)response, response); + } + + /// + /// + /// + /// + /// + public virtual Response CreateOrUpdateTest(Test test, CancellationToken cancellationToken = default) + { + if (test is not IModelJsonSerializable serializable) + { + throw new InvalidCastException("model is not serializable"); + } + + using Stream stream = new MemoryStream(); + using (Utf8JsonWriter writer = new(stream)) + { + serializable.Serialize(writer, new ModelSerializerOptions("P")); + } + + stream.Position = 0; + RequestContent content = RequestContent.Create(stream); + + RequestContext context = new() { CancellationToken = cancellationToken }; + + Response response = CreateOrUpdateTest(test.TestId, content, context); + + return Response.FromValue((Test)response, response); + } } } diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/CertificateMetadata.Serialization.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/CertificateMetadata.Serialization.cs new file mode 100644 index 000000000000..893137c90063 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/CertificateMetadata.Serialization.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure.Core; + +namespace Azure.Developer.LoadTesting.Models +{ + public partial class CertificateMetadata : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + if (Optional.IsDefined(Value)) + { + writer.WritePropertyName("value"u8); + writer.WriteStringValue(Value); + } + if (Optional.IsDefined(Type)) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.Value.ToString()); + } + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + writer.WriteEndObject(); + } + + internal static CertificateMetadata DeserializeCertificateMetadata(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional value = default; + Optional type = default; + Optional name = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("value"u8)) + { + value = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + type = new CertificateType(property.Value.GetString()); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + } + return new CertificateMetadata(value.Value, Optional.ToNullable(type), name.Value); + } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/CertificateMetadata.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/CertificateMetadata.cs new file mode 100644 index 000000000000..6549aad351a6 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/CertificateMetadata.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +namespace Azure.Developer.LoadTesting.Models +{ + /// Certificates metadata. + public partial class CertificateMetadata + { + /// Initializes a new instance of CertificateMetadata. + public CertificateMetadata() + { + } + + /// Initializes a new instance of CertificateMetadata. + /// The value of the certificate for respective type. + /// Type of certificate. + /// Name of the certificate. + internal CertificateMetadata(string value, CertificateType? type, string name) + { + Value = value; + Type = type; + Name = name; + } + + /// The value of the certificate for respective type. + public string Value { get; set; } + /// Type of certificate. + public CertificateType? Type { get; set; } + /// Name of the certificate. + public string Name { get; set; } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/CertificateType.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/CertificateType.cs new file mode 100644 index 000000000000..a6bd365c443f --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/CertificateType.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Developer.LoadTesting.Models +{ + /// Type of certificate. + public readonly partial struct CertificateType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public CertificateType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AKVCertURIValue = "AKV_CERT_URI"; + + /// If the certificate is stored in an Azure Key Vault. + public static CertificateType AKVCertURI { get; } = new CertificateType(AKVCertURIValue); + /// Determines if two values are the same. + public static bool operator ==(CertificateType left, CertificateType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(CertificateType left, CertificateType right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator CertificateType(string value) => new CertificateType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is CertificateType other && Equals(other); + /// + public bool Equals(CertificateType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/FileInfo.Serialization.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/FileInfo.Serialization.cs new file mode 100644 index 000000000000..68e4e1c3e687 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/FileInfo.Serialization.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Developer.LoadTesting.Models +{ + public partial class FileInfo + { + internal static FileInfo DeserializeFileInfo(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional url = default; + Optional fileName = default; + Optional fileType = default; + Optional expireDateTime = default; + Optional validationStatus = default; + Optional validationFailureDetails = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("url"u8)) + { + url = property.Value.GetString(); + continue; + } + if (property.NameEquals("fileName"u8)) + { + fileName = property.Value.GetString(); + continue; + } + if (property.NameEquals("fileType"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fileType = new FileType(property.Value.GetString()); + continue; + } + if (property.NameEquals("expireDateTime"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expireDateTime = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("validationStatus"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + validationStatus = new FileStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("validationFailureDetails"u8)) + { + validationFailureDetails = property.Value.GetString(); + continue; + } + } + return new FileInfo(url.Value, fileName.Value, Optional.ToNullable(fileType), Optional.ToNullable(expireDateTime), Optional.ToNullable(validationStatus), validationFailureDetails.Value); + } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/FileInfo.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/FileInfo.cs new file mode 100644 index 000000000000..63ec0d2d8c1e --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/FileInfo.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Azure.Developer.LoadTesting.Models +{ + /// File info. + public partial class FileInfo + { + /// Initializes a new instance of FileInfo. + internal FileInfo() + { + } + + /// Initializes a new instance of FileInfo. + /// File URL. + /// Name of the file. + /// File type. + /// Expiry time of the file (ISO 8601 literal format). + /// Validation status of the file. + /// Validation failure error details. + internal FileInfo(string url, string fileName, FileType? fileType, DateTimeOffset? expireDateTime, FileStatus? validationStatus, string validationFailureDetails) + { + Url = url; + FileName = fileName; + FileType = fileType; + ExpireDateTime = expireDateTime; + ValidationStatus = validationStatus; + ValidationFailureDetails = validationFailureDetails; + } + + /// File URL. + public string Url { get; } + /// Name of the file. + public string FileName { get; } + /// File type. + public FileType? FileType { get; } + /// Expiry time of the file (ISO 8601 literal format). + public DateTimeOffset? ExpireDateTime { get; } + /// Validation status of the file. + public FileStatus? ValidationStatus { get; } + /// Validation failure error details. + public string ValidationFailureDetails { get; } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/FileStatus.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/FileStatus.cs new file mode 100644 index 000000000000..8596a7328469 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/FileStatus.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Developer.LoadTesting.Models +{ + /// Validation status of the file. + public readonly partial struct FileStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FileStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string NOTValidatedValue = "NOT_VALIDATED"; + private const string ValidationSuccessValue = "VALIDATION_SUCCESS"; + private const string ValidationFailureValue = "VALIDATION_FAILURE"; + private const string ValidationInitiatedValue = "VALIDATION_INITIATED"; + private const string ValidationNOTRequiredValue = "VALIDATION_NOT_REQUIRED"; + + /// File is not validated. + public static FileStatus NOTValidated { get; } = new FileStatus(NOTValidatedValue); + /// File is validated. + public static FileStatus ValidationSuccess { get; } = new FileStatus(ValidationSuccessValue); + /// File validation is failed. + public static FileStatus ValidationFailure { get; } = new FileStatus(ValidationFailureValue); + /// File validation is in progress. + public static FileStatus ValidationInitiated { get; } = new FileStatus(ValidationInitiatedValue); + /// Validation is not required. + public static FileStatus ValidationNOTRequired { get; } = new FileStatus(ValidationNOTRequiredValue); + /// Determines if two values are the same. + public static bool operator ==(FileStatus left, FileStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FileStatus left, FileStatus right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator FileStatus(string value) => new FileStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FileStatus other && Equals(other); + /// + public bool Equals(FileStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/FileType.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/FileType.cs new file mode 100644 index 000000000000..5a84716042bb --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/FileType.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Developer.LoadTesting.Models +{ + /// File type. + public readonly partial struct FileType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FileType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string JMXFileValue = "JMX_FILE"; + private const string UserPropertiesValue = "USER_PROPERTIES"; + private const string AdditionalArtifactsValue = "ADDITIONAL_ARTIFACTS"; + + /// If file is jmx script. + public static FileType JMXFile { get; } = new FileType(JMXFileValue); + /// If file is user properties. + public static FileType UserProperties { get; } = new FileType(UserPropertiesValue); + /// If file is not any of other supported type. + public static FileType AdditionalArtifacts { get; } = new FileType(AdditionalArtifactsValue); + /// Determines if two values are the same. + public static bool operator ==(FileType left, FileType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FileType left, FileType right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator FileType(string value) => new FileType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FileType other && Equals(other); + /// + public bool Equals(FileType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/LoadTestConfiguration.Serialization.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/LoadTestConfiguration.Serialization.cs new file mode 100644 index 000000000000..503f04d94fb2 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/LoadTestConfiguration.Serialization.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure.Core; + +namespace Azure.Developer.LoadTesting.Models +{ + public partial class LoadTestConfiguration : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + if (Optional.IsDefined(EngineInstances)) + { + writer.WritePropertyName("engineInstances"u8); + writer.WriteNumberValue(EngineInstances.Value); + } + if (Optional.IsDefined(SplitAllCSVs)) + { + writer.WritePropertyName("splitAllCSVs"u8); + writer.WriteBooleanValue(SplitAllCSVs.Value); + } + if (Optional.IsDefined(QuickStartTest)) + { + writer.WritePropertyName("quickStartTest"u8); + writer.WriteBooleanValue(QuickStartTest.Value); + } + if (Optional.IsDefined(OptionalLoadTestConfig)) + { + writer.WritePropertyName("optionalLoadTestConfig"u8); + writer.WriteObjectValue(OptionalLoadTestConfig); + } + writer.WriteEndObject(); + } + + internal static LoadTestConfiguration DeserializeLoadTestConfiguration(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional engineInstances = default; + Optional splitAllCSVs = default; + Optional quickStartTest = default; + Optional optionalLoadTestConfig = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("engineInstances"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + engineInstances = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("splitAllCSVs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + splitAllCSVs = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("quickStartTest"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + quickStartTest = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("optionalLoadTestConfig"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + optionalLoadTestConfig = OptionalLoadTestConfig.DeserializeOptionalLoadTestConfig(property.Value); + continue; + } + } + return new LoadTestConfiguration(Optional.ToNullable(engineInstances), Optional.ToNullable(splitAllCSVs), Optional.ToNullable(quickStartTest), optionalLoadTestConfig.Value); + } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/LoadTestConfiguration.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/LoadTestConfiguration.cs new file mode 100644 index 000000000000..c547ed66b738 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/LoadTestConfiguration.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +namespace Azure.Developer.LoadTesting.Models +{ + /// The load test configuration. + public partial class LoadTestConfiguration + { + /// Initializes a new instance of LoadTestConfiguration. + public LoadTestConfiguration() + { + } + + /// Initializes a new instance of LoadTestConfiguration. + /// The number of engine instances to execute load test. Supported values are in range of 1-45. Required for creating a new test. + /// If false, Azure Load Testing copies and processes your input files unmodified across all test engine instances. If true, Azure Load Testing splits the CSV input data evenly across all engine instances. If you provide multiple CSV files, each file will be split evenly. + /// If true, optionalLoadTestConfig is required and JMX script for the load test is not required to upload. + /// Optional load test config. + internal LoadTestConfiguration(int? engineInstances, bool? splitAllCSVs, bool? quickStartTest, OptionalLoadTestConfig optionalLoadTestConfig) + { + EngineInstances = engineInstances; + SplitAllCSVs = splitAllCSVs; + QuickStartTest = quickStartTest; + OptionalLoadTestConfig = optionalLoadTestConfig; + } + + /// The number of engine instances to execute load test. Supported values are in range of 1-45. Required for creating a new test. + public int? EngineInstances { get; set; } + /// If false, Azure Load Testing copies and processes your input files unmodified across all test engine instances. If true, Azure Load Testing splits the CSV input data evenly across all engine instances. If you provide multiple CSV files, each file will be split evenly. + public bool? SplitAllCSVs { get; set; } + /// If true, optionalLoadTestConfig is required and JMX script for the load test is not required to upload. + public bool? QuickStartTest { get; set; } + /// Optional load test config. + public OptionalLoadTestConfig OptionalLoadTestConfig { get; set; } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/OptionalLoadTestConfig.Serialization.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/OptionalLoadTestConfig.Serialization.cs new file mode 100644 index 000000000000..2f6d314d6e3c --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/OptionalLoadTestConfig.Serialization.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure.Core; + +namespace Azure.Developer.LoadTesting.Models +{ + public partial class OptionalLoadTestConfig : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + if (Optional.IsDefined(EndpointUrl)) + { + writer.WritePropertyName("endpointUrl"u8); + writer.WriteStringValue(EndpointUrl); + } + if (Optional.IsDefined(VirtualUsers)) + { + writer.WritePropertyName("virtualUsers"u8); + writer.WriteNumberValue(VirtualUsers.Value); + } + if (Optional.IsDefined(RampUpTime)) + { + writer.WritePropertyName("rampUpTime"u8); + writer.WriteNumberValue(RampUpTime.Value); + } + if (Optional.IsDefined(Duration)) + { + writer.WritePropertyName("duration"u8); + writer.WriteNumberValue(Duration.Value); + } + writer.WriteEndObject(); + } + + internal static OptionalLoadTestConfig DeserializeOptionalLoadTestConfig(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional endpointUrl = default; + Optional virtualUsers = default; + Optional rampUpTime = default; + Optional duration = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("endpointUrl"u8)) + { + endpointUrl = property.Value.GetString(); + continue; + } + if (property.NameEquals("virtualUsers"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + virtualUsers = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("rampUpTime"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + rampUpTime = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("duration"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + duration = property.Value.GetInt32(); + continue; + } + } + return new OptionalLoadTestConfig(endpointUrl.Value, Optional.ToNullable(virtualUsers), Optional.ToNullable(rampUpTime), Optional.ToNullable(duration)); + } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/OptionalLoadTestConfig.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/OptionalLoadTestConfig.cs new file mode 100644 index 000000000000..2b93bd5ff0e6 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/OptionalLoadTestConfig.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +namespace Azure.Developer.LoadTesting.Models +{ + /// Optional load test config. + public partial class OptionalLoadTestConfig + { + /// Initializes a new instance of OptionalLoadTestConfig. + public OptionalLoadTestConfig() + { + } + + /// Initializes a new instance of OptionalLoadTestConfig. + /// Test URL. Provide the complete HTTP URL. For example, http://contoso-app.azurewebsites.net/login. + /// No of concurrent virtual users. + /// Ramp up time. + /// Test run duration. + internal OptionalLoadTestConfig(string endpointUrl, int? virtualUsers, int? rampUpTime, int? duration) + { + EndpointUrl = endpointUrl; + VirtualUsers = virtualUsers; + RampUpTime = rampUpTime; + Duration = duration; + } + + /// Test URL. Provide the complete HTTP URL. For example, http://contoso-app.azurewebsites.net/login. + public string EndpointUrl { get; set; } + /// No of concurrent virtual users. + public int? VirtualUsers { get; set; } + /// Ramp up time. + public int? RampUpTime { get; set; } + /// Test run duration. + public int? Duration { get; set; } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PFAction.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PFAction.cs new file mode 100644 index 000000000000..aa2d4695259a --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PFAction.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Developer.LoadTesting.Models +{ + /// Action taken after the threshold is met. Default is ‘continue’. + public readonly partial struct PFAction : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public PFAction(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ContinueValue = "continue"; + private const string StopValue = "stop"; + + /// Test will continue to run even if pass fail metric criteria metric gets failed. + public static PFAction Continue { get; } = new PFAction(ContinueValue); + /// Test run will stop if pass fail criteria metric is not passed. + public static PFAction Stop { get; } = new PFAction(StopValue); + /// Determines if two values are the same. + public static bool operator ==(PFAction left, PFAction right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(PFAction left, PFAction right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator PFAction(string value) => new PFAction(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is PFAction other && Equals(other); + /// + public bool Equals(PFAction other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PFAgFunc.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PFAgFunc.cs new file mode 100644 index 000000000000..27a706b49e08 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PFAgFunc.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Developer.LoadTesting.Models +{ + /// The aggregation function to be applied on the client metric. Allowed functions - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, ‘count’ - for requests. + public readonly partial struct PFAgFunc : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public PFAgFunc(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string CountValue = "count"; + private const string PercentageValue = "percentage"; + private const string AvgValue = "avg"; + private const string P50Value = "p50"; + private const string P90Value = "p90"; + private const string P95Value = "p95"; + private const string P99Value = "p99"; + private const string MinValue = "min"; + private const string MaxValue = "max"; + + /// Criteria applies for count value. + public static PFAgFunc Count { get; } = new PFAgFunc(CountValue); + /// Criteria applies for given percentage value. + public static PFAgFunc Percentage { get; } = new PFAgFunc(PercentageValue); + /// Criteria applies for avg value. + public static PFAgFunc Avg { get; } = new PFAgFunc(AvgValue); + /// Criteria applies for 50th percentile value. + public static PFAgFunc P50 { get; } = new PFAgFunc(P50Value); + /// Criteria applies for 90th percentile value. + public static PFAgFunc P90 { get; } = new PFAgFunc(P90Value); + /// Criteria applies for 95th percentile value. + public static PFAgFunc P95 { get; } = new PFAgFunc(P95Value); + /// Criteria applies for 99th percentile value. + public static PFAgFunc P99 { get; } = new PFAgFunc(P99Value); + /// Criteria applies for minimum value. + public static PFAgFunc Min { get; } = new PFAgFunc(MinValue); + /// Criteria applies for maximum value. + public static PFAgFunc Max { get; } = new PFAgFunc(MaxValue); + /// Determines if two values are the same. + public static bool operator ==(PFAgFunc left, PFAgFunc right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(PFAgFunc left, PFAgFunc right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator PFAgFunc(string value) => new PFAgFunc(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is PFAgFunc other && Equals(other); + /// + public bool Equals(PFAgFunc other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PFMetrics.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PFMetrics.cs new file mode 100644 index 000000000000..a4f5049a1bce --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PFMetrics.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Developer.LoadTesting.Models +{ + /// The client metric on which the criteria should be applied. + public readonly partial struct PFMetrics : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public PFMetrics(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ResponseTimeMsValue = "response_time_ms"; + private const string LatencyValue = "latency"; + private const string ErrorValue = "error"; + private const string RequestsValue = "requests"; + private const string RequestsPerSecValue = "requests_per_sec"; + + /// Pass fail criteria for response time metric. + public static PFMetrics ResponseTimeMs { get; } = new PFMetrics(ResponseTimeMsValue); + /// Pass fail criteria for response time metric. + public static PFMetrics Latency { get; } = new PFMetrics(LatencyValue); + /// Pass fail criteria for error metric. + public static PFMetrics Error { get; } = new PFMetrics(ErrorValue); + /// Pass fail criteria for total requests. + public static PFMetrics Requests { get; } = new PFMetrics(RequestsValue); + /// Pass fail criteria for request rate. + public static PFMetrics RequestsPerSec { get; } = new PFMetrics(RequestsPerSecValue); + /// Determines if two values are the same. + public static bool operator ==(PFMetrics left, PFMetrics right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(PFMetrics left, PFMetrics right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator PFMetrics(string value) => new PFMetrics(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is PFMetrics other && Equals(other); + /// + public bool Equals(PFMetrics other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PFResult.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PFResult.cs new file mode 100644 index 000000000000..535132072c80 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PFResult.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Developer.LoadTesting.Models +{ + /// Outcome of the test run. + public readonly partial struct PFResult : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public PFResult(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string PassedValue = "passed"; + private const string UndeterminedValue = "undetermined"; + private const string FailedValue = "failed"; + + /// Given pass fail criteria metric has passed. + public static PFResult Passed { get; } = new PFResult(PassedValue); + /// Given pass fail criteria metric couldn't determine. + public static PFResult Undetermined { get; } = new PFResult(UndeterminedValue); + /// Given pass fail criteria metric has failed. + public static PFResult Failed { get; } = new PFResult(FailedValue); + /// Determines if two values are the same. + public static bool operator ==(PFResult left, PFResult right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(PFResult left, PFResult right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator PFResult(string value) => new PFResult(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is PFResult other && Equals(other); + /// + public bool Equals(PFResult other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PassFailCriteria.Serialization.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PassFailCriteria.Serialization.cs new file mode 100644 index 000000000000..60ccca4d96c1 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PassFailCriteria.Serialization.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Developer.LoadTesting.Models +{ + public partial class PassFailCriteria : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + if (Optional.IsCollectionDefined(PassFailMetrics)) + { + writer.WritePropertyName("passFailMetrics"u8); + writer.WriteStartObject(); + foreach (var item in PassFailMetrics) + { + writer.WritePropertyName(item.Key); + writer.WriteObjectValue(item.Value); + } + writer.WriteEndObject(); + } + writer.WriteEndObject(); + } + + internal static PassFailCriteria DeserializePassFailCriteria(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional> passFailMetrics = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("passFailMetrics"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, PassFailMetric.DeserializePassFailMetric(property0.Value)); + } + passFailMetrics = dictionary; + continue; + } + } + return new PassFailCriteria(Optional.ToDictionary(passFailMetrics)); + } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PassFailCriteria.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PassFailCriteria.cs new file mode 100644 index 000000000000..7350508ca4d2 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PassFailCriteria.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.Developer.LoadTesting.Models +{ + /// Pass fail criteria for a test. + public partial class PassFailCriteria + { + /// Initializes a new instance of PassFailCriteria. + public PassFailCriteria() + { + PassFailMetrics = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of PassFailCriteria. + /// Map of id and pass fail metrics { id : pass fail metrics }. + internal PassFailCriteria(IDictionary passFailMetrics) + { + PassFailMetrics = passFailMetrics; + } + + /// Map of id and pass fail metrics { id : pass fail metrics }. + public IDictionary PassFailMetrics { get; } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PassFailMetric.Serialization.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PassFailMetric.Serialization.cs new file mode 100644 index 000000000000..d510209dc2db --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PassFailMetric.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure.Core; + +namespace Azure.Developer.LoadTesting.Models +{ + public partial class PassFailMetric : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + if (Optional.IsDefined(ClientMetric)) + { + writer.WritePropertyName("clientMetric"u8); + writer.WriteStringValue(ClientMetric.Value.ToString()); + } + if (Optional.IsDefined(Aggregate)) + { + writer.WritePropertyName("aggregate"u8); + writer.WriteStringValue(Aggregate.Value.ToString()); + } + if (Optional.IsDefined(Condition)) + { + writer.WritePropertyName("condition"u8); + writer.WriteStringValue(Condition); + } + if (Optional.IsDefined(RequestName)) + { + writer.WritePropertyName("requestName"u8); + writer.WriteStringValue(RequestName); + } + if (Optional.IsDefined(Value)) + { + writer.WritePropertyName("value"u8); + writer.WriteNumberValue(Value.Value); + } + if (Optional.IsDefined(Action)) + { + writer.WritePropertyName("action"u8); + writer.WriteStringValue(Action.Value.ToString()); + } + writer.WriteEndObject(); + } + + internal static PassFailMetric DeserializePassFailMetric(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional clientMetric = default; + Optional aggregate = default; + Optional condition = default; + Optional requestName = default; + Optional value = default; + Optional action = default; + Optional actualValue = default; + Optional result = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("clientMetric"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + clientMetric = new PFMetrics(property.Value.GetString()); + continue; + } + if (property.NameEquals("aggregate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + aggregate = new PFAgFunc(property.Value.GetString()); + continue; + } + if (property.NameEquals("condition"u8)) + { + condition = property.Value.GetString(); + continue; + } + if (property.NameEquals("requestName"u8)) + { + requestName = property.Value.GetString(); + continue; + } + if (property.NameEquals("value"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + value = property.Value.GetDouble(); + continue; + } + if (property.NameEquals("action"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + action = new PFAction(property.Value.GetString()); + continue; + } + if (property.NameEquals("actualValue"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + actualValue = property.Value.GetDouble(); + continue; + } + if (property.NameEquals("result"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + result = new PFResult(property.Value.GetString()); + continue; + } + } + return new PassFailMetric(Optional.ToNullable(clientMetric), Optional.ToNullable(aggregate), condition.Value, requestName.Value, Optional.ToNullable(value), Optional.ToNullable(action), Optional.ToNullable(actualValue), Optional.ToNullable(result)); + } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PassFailMetric.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PassFailMetric.cs new file mode 100644 index 000000000000..b05a8d87eb14 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/PassFailMetric.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +namespace Azure.Developer.LoadTesting.Models +{ + /// Pass fail metric. + public partial class PassFailMetric + { + /// Initializes a new instance of PassFailMetric. + public PassFailMetric() + { + } + + /// Initializes a new instance of PassFailMetric. + /// The client metric on which the criteria should be applied. + /// The aggregation function to be applied on the client metric. Allowed functions - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, ‘count’ - for requests. + /// The comparison operator. Supported types ‘>’, ‘<’. + /// Request name for which the Pass fail criteria has to be applied. + /// The value to compare with the client metric. Allowed values - ‘error : [0.0 , 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. + /// Action taken after the threshold is met. Default is ‘continue’. + /// The actual value of the client metric for the test run. + /// Outcome of the test run. + internal PassFailMetric(PFMetrics? clientMetric, PFAgFunc? aggregate, string condition, string requestName, double? value, PFAction? action, double? actualValue, PFResult? result) + { + ClientMetric = clientMetric; + Aggregate = aggregate; + Condition = condition; + RequestName = requestName; + Value = value; + Action = action; + ActualValue = actualValue; + Result = result; + } + + /// The client metric on which the criteria should be applied. + public PFMetrics? ClientMetric { get; set; } + /// The aggregation function to be applied on the client metric. Allowed functions - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, ‘count’ - for requests. + public PFAgFunc? Aggregate { get; set; } + /// The comparison operator. Supported types ‘>’, ‘<’. + public string Condition { get; set; } + /// Request name for which the Pass fail criteria has to be applied. + public string RequestName { get; set; } + /// The value to compare with the client metric. Allowed values - ‘error : [0.0 , 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. + public double? Value { get; set; } + /// Action taken after the threshold is met. Default is ‘continue’. + public PFAction? Action { get; set; } + /// The actual value of the client metric for the test run. + public double? ActualValue { get; } + /// Outcome of the test run. + public PFResult? Result { get; } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/Secret.Serialization.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/Secret.Serialization.cs new file mode 100644 index 000000000000..4ebd8ada30c1 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/Secret.Serialization.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure.Core; + +namespace Azure.Developer.LoadTesting.Models +{ + public partial class Secret : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + if (Optional.IsDefined(Value)) + { + writer.WritePropertyName("value"u8); + writer.WriteStringValue(Value); + } + if (Optional.IsDefined(Type)) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.Value.ToString()); + } + writer.WriteEndObject(); + } + + internal static Secret DeserializeSecret(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional value = default; + Optional type = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("value"u8)) + { + value = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + type = new SecretType(property.Value.GetString()); + continue; + } + } + return new Secret(value.Value, Optional.ToNullable(type)); + } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/Secret.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/Secret.cs new file mode 100644 index 000000000000..663ab99f40aa --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/Secret.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +namespace Azure.Developer.LoadTesting.Models +{ + /// Secret. + public partial class Secret + { + /// Initializes a new instance of Secret. + public Secret() + { + } + + /// Initializes a new instance of Secret. + /// The value of the secret for the respective type. + /// Type of secret. + internal Secret(string value, SecretType? type) + { + Value = value; + Type = type; + } + + /// The value of the secret for the respective type. + public string Value { get; set; } + /// Type of secret. + public SecretType? Type { get; set; } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/SecretType.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/SecretType.cs new file mode 100644 index 000000000000..9e6457ce07dd --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/SecretType.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Developer.LoadTesting.Models +{ + /// Type of secret. + public readonly partial struct SecretType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public SecretType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AKVSecretURIValue = "AKV_SECRET_URI"; + private const string SecretValueValue = "SECRET_VALUE"; + + /// If the secret is stored in an Azure Key Vault. + public static SecretType AKVSecretURI { get; } = new SecretType(AKVSecretURIValue); + /// If the Plain text secret value provided. + public static SecretType SecretValue { get; } = new SecretType(SecretValueValue); + /// Determines if two values are the same. + public static bool operator ==(SecretType left, SecretType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(SecretType left, SecretType right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator SecretType(string value) => new SecretType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is SecretType other && Equals(other); + /// + public bool Equals(SecretType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/Test.Serialization.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/Test.Serialization.cs new file mode 100644 index 000000000000..b1207c31dc3c --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/Test.Serialization.cs @@ -0,0 +1,298 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; +using Azure.Core.Serialization; + +namespace Azure.Developer.LoadTesting.Models +{ + public partial class Test : IUtf8JsonSerializable, IModelJsonSerializable + { + #region Serialize + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IModelJsonSerializable)this).Serialize(writer, ModelSerializerOptions.DefaultWireOptions); + + void IModelJsonSerializable.Serialize(Utf8JsonWriter writer, ModelSerializerOptions options) + { + // TODO: PatchModelHelper.ValidateFormat(this, options.Format); + + switch (options.Format.ToString()) + { + case "J": + case "W": + Serialize(writer, options); + break; + case "P": + SerializePatch(writer); + break; + default: + // Exception was thrown by ValidateFormat. + break; + } + } + + BinaryData IModelSerializable.Serialize(ModelSerializerOptions options) + { + // TODO: PatchModelHelper.ValidateFormat(this, options.Format); + return ModelSerializer.SerializeCore(this, options); + } + + private void Serialize(Utf8JsonWriter writer, ModelSerializerOptions options) + { + writer.WriteStartObject(); + if (Optional.IsDefined(PassFailCriteria)) + { + writer.WritePropertyName("passFailCriteria"u8); + writer.WriteObjectValue(PassFailCriteria); + } + if (Optional.IsCollectionDefined(Secrets)) + { + writer.WritePropertyName("secrets"u8); + writer.WriteStartObject(); + foreach (var item in Secrets) + { + writer.WritePropertyName(item.Key); + writer.WriteObjectValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsDefined(Certificate)) + { + writer.WritePropertyName("certificate"u8); + writer.WriteObjectValue(Certificate); + } + if (Optional.IsCollectionDefined(EnvironmentVariables)) + { + writer.WritePropertyName("environmentVariables"u8); + writer.WriteStartObject(); + foreach (var item in EnvironmentVariables) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsDefined(LoadTestConfiguration)) + { + writer.WritePropertyName("loadTestConfiguration"u8); + writer.WriteObjectValue(LoadTestConfiguration); + } + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + if (Optional.IsDefined(DisplayName)) + { + writer.WritePropertyName("displayName"u8); + writer.WriteStringValue(DisplayName); + } + if (Optional.IsDefined(SubnetId)) + { + writer.WritePropertyName("subnetId"u8); + writer.WriteStringValue(SubnetId); + } + if (Optional.IsDefined(KeyvaultReferenceIdentityType)) + { + writer.WritePropertyName("keyvaultReferenceIdentityType"u8); + writer.WriteStringValue(KeyvaultReferenceIdentityType); + } + if (Optional.IsDefined(KeyvaultReferenceIdentityId)) + { + writer.WritePropertyName("keyvaultReferenceIdentityId"u8); + writer.WriteStringValue(KeyvaultReferenceIdentityId); + } + writer.WriteEndObject(); + } + + private void SerializePatch(Utf8JsonWriter writer) + { + throw new NotImplementedException(); + } + + public static implicit operator RequestContent(Test model) + => RequestContent.Create(model, ModelSerializerOptions.DefaultWireOptions); + #endregion Serialize + + #region Deserialize + internal static Test DeserializeTest(JsonElement element, ModelSerializerOptions options = default) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional passFailCriteria = default; + Optional> secrets = default; + Optional certificate = default; + Optional> environmentVariables = default; + Optional loadTestConfiguration = default; + Optional inputArtifacts = default; + Optional testId = default; + Optional description = default; + Optional displayName = default; + Optional subnetId = default; + Optional keyvaultReferenceIdentityType = default; + Optional keyvaultReferenceIdentityId = default; + Optional createdDateTime = default; + Optional createdBy = default; + Optional lastModifiedDateTime = default; + Optional lastModifiedBy = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("passFailCriteria"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + passFailCriteria = PassFailCriteria.DeserializePassFailCriteria(property.Value); + continue; + } + if (property.NameEquals("secrets"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, Secret.DeserializeSecret(property0.Value)); + } + secrets = dictionary; + continue; + } + if (property.NameEquals("certificate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + certificate = CertificateMetadata.DeserializeCertificateMetadata(property.Value); + continue; + } + if (property.NameEquals("environmentVariables"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + environmentVariables = dictionary; + continue; + } + if (property.NameEquals("loadTestConfiguration"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + loadTestConfiguration = LoadTestConfiguration.DeserializeLoadTestConfiguration(property.Value); + continue; + } + if (property.NameEquals("inputArtifacts"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + inputArtifacts = TestInputArtifacts.DeserializeTestInputArtifacts(property.Value); + continue; + } + if (property.NameEquals("testId"u8)) + { + testId = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("displayName"u8)) + { + displayName = property.Value.GetString(); + continue; + } + if (property.NameEquals("subnetId"u8)) + { + subnetId = property.Value.GetString(); + continue; + } + if (property.NameEquals("keyvaultReferenceIdentityType"u8)) + { + keyvaultReferenceIdentityType = property.Value.GetString(); + continue; + } + if (property.NameEquals("keyvaultReferenceIdentityId"u8)) + { + keyvaultReferenceIdentityId = property.Value.GetString(); + continue; + } + if (property.NameEquals("createdDateTime"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + createdDateTime = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("createdBy"u8)) + { + createdBy = property.Value.GetString(); + continue; + } + if (property.NameEquals("lastModifiedDateTime"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + lastModifiedDateTime = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("lastModifiedBy"u8)) + { + lastModifiedBy = property.Value.GetString(); + continue; + } + } + return new Test(passFailCriteria.Value, Optional.ToDictionary(secrets), certificate.Value, Optional.ToDictionary(environmentVariables), loadTestConfiguration.Value, inputArtifacts.Value, testId.Value, description.Value, displayName.Value, subnetId.Value, keyvaultReferenceIdentityType.Value, keyvaultReferenceIdentityId.Value, Optional.ToNullable(createdDateTime), createdBy.Value, Optional.ToNullable(lastModifiedDateTime), lastModifiedBy.Value); + } + + Test IModelJsonSerializable.Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) + { + // TODO: PatchModelHelper.ValidateFormat(this, options.Format); + using var doc = JsonDocument.ParseValue(ref reader); + return DeserializeTest(doc.RootElement, options); + } + + Test IModelSerializable.Deserialize(BinaryData data, ModelSerializerOptions options) + { + // TODO: PatchModelHelper.ValidateFormat(this, options.Format); + return DeserializeTest(JsonDocument.Parse(data.ToString()).RootElement, options); + } + + public static explicit operator Test(Response response) + { + Argument.AssertNotNull(response, nameof(response)); + + using JsonDocument jsonDocument = JsonDocument.Parse(response.ContentStream); + return DeserializeTest(jsonDocument.RootElement, ModelSerializerOptions.DefaultWireOptions); + } + #endregion Deserialize + + //void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IModelJsonSerializable)this).Serialize(writer, ModelSerializerOptions.DefaultWireOptions); + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/Test.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/Test.cs new file mode 100644 index 000000000000..1a32a4377d79 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/Test.cs @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.Developer.LoadTesting.Models +{ + /// Load test model. + public partial class Test + { + /// Initializes a new instance of Test. + public Test(string id) + { + TestId = id; + + Secrets = new ChangeTrackingDictionary(); + EnvironmentVariables = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of Test. + /// Pass fail criteria for a test. + /// Secrets can be stored in an Azure Key Vault or any other secret store. If the secret is stored in an Azure Key Vault, the value should be the secret identifier and the type should be AKV_SECRET_URI. If the secret is stored elsewhere, the secret value should be provided directly and the type should be SECRET_VALUE. + /// Certificates metadata. + /// Environment variables which are defined as a set of <name,value> pairs. + /// The load test configuration. + /// The input artifacts for the test. + /// Unique test name as identifier. + /// The test description. + /// Display name of a test. + /// Subnet ID on which the load test instances should run. + /// Type of the managed identity referencing the Key vault. + /// Resource Id of the managed identity referencing the Key vault. + /// The creation datetime(ISO 8601 literal format). + /// The user that created. + /// The last Modified datetime(ISO 8601 literal format). + /// The user that last modified. + internal Test(PassFailCriteria passFailCriteria, IDictionary secrets, CertificateMetadata certificate, IDictionary environmentVariables, LoadTestConfiguration loadTestConfiguration, TestInputArtifacts inputArtifacts, string testId, string description, string displayName, string subnetId, string keyvaultReferenceIdentityType, string keyvaultReferenceIdentityId, DateTimeOffset? createdDateTime, string createdBy, DateTimeOffset? lastModifiedDateTime, string lastModifiedBy) + { + PassFailCriteria = passFailCriteria; + Secrets = secrets; + Certificate = certificate; + EnvironmentVariables = environmentVariables; + LoadTestConfiguration = loadTestConfiguration; + InputArtifacts = inputArtifacts; + TestId = testId; + Description = description; + DisplayName = displayName; + SubnetId = subnetId; + KeyvaultReferenceIdentityType = keyvaultReferenceIdentityType; + KeyvaultReferenceIdentityId = keyvaultReferenceIdentityId; + CreatedDateTime = createdDateTime; + CreatedBy = createdBy; + LastModifiedDateTime = lastModifiedDateTime; + LastModifiedBy = lastModifiedBy; + } + + /// Pass fail criteria for a test. + public PassFailCriteria PassFailCriteria { get; set; } + /// Secrets can be stored in an Azure Key Vault or any other secret store. If the secret is stored in an Azure Key Vault, the value should be the secret identifier and the type should be AKV_SECRET_URI. If the secret is stored elsewhere, the secret value should be provided directly and the type should be SECRET_VALUE. + public IDictionary Secrets { get; } + /// Certificates metadata. + public CertificateMetadata Certificate { get; set; } + /// Environment variables which are defined as a set of <name,value> pairs. + public IDictionary EnvironmentVariables { get; } + /// The load test configuration. + public LoadTestConfiguration LoadTestConfiguration { get; set; } + /// The input artifacts for the test. + public TestInputArtifacts InputArtifacts { get; } + /// Unique test name as identifier. + public string TestId { get; } + /// The test description. + public string Description { get; set; } + /// Display name of a test. + public string DisplayName { get; set; } + /// Subnet ID on which the load test instances should run. + public string SubnetId { get; set; } + /// Type of the managed identity referencing the Key vault. + public string KeyvaultReferenceIdentityType { get; set; } + /// Resource Id of the managed identity referencing the Key vault. + public string KeyvaultReferenceIdentityId { get; set; } + /// The creation datetime(ISO 8601 literal format). + public DateTimeOffset? CreatedDateTime { get; } + /// The user that created. + public string CreatedBy { get; } + /// The last Modified datetime(ISO 8601 literal format). + public DateTimeOffset? LastModifiedDateTime { get; } + /// The user that last modified. + public string LastModifiedBy { get; } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/TestInputArtifacts.Serialization.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/TestInputArtifacts.Serialization.cs new file mode 100644 index 000000000000..791170ebc26c --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/TestInputArtifacts.Serialization.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Developer.LoadTesting.Models +{ + public partial class TestInputArtifacts + { + internal static TestInputArtifacts DeserializeTestInputArtifacts(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional configFileInfo = default; + Optional testScriptFileInfo = default; + Optional userPropFileInfo = default; + Optional inputArtifactsZipFileInfo = default; + Optional> additionalFileInfo = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("configFileInfo"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + configFileInfo = FileInfo.DeserializeFileInfo(property.Value); + continue; + } + if (property.NameEquals("testScriptFileInfo"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + testScriptFileInfo = FileInfo.DeserializeFileInfo(property.Value); + continue; + } + if (property.NameEquals("userPropFileInfo"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + userPropFileInfo = FileInfo.DeserializeFileInfo(property.Value); + continue; + } + if (property.NameEquals("inputArtifactsZipFileInfo"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + inputArtifactsZipFileInfo = FileInfo.DeserializeFileInfo(property.Value); + continue; + } + if (property.NameEquals("additionalFileInfo"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(FileInfo.DeserializeFileInfo(item)); + } + additionalFileInfo = array; + continue; + } + } + return new TestInputArtifacts(configFileInfo.Value, testScriptFileInfo.Value, userPropFileInfo.Value, inputArtifactsZipFileInfo.Value, Optional.ToList(additionalFileInfo)); + } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/TestInputArtifacts.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/TestInputArtifacts.cs new file mode 100644 index 000000000000..8710d5bec606 --- /dev/null +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/src/Models/TestInputArtifacts.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.Developer.LoadTesting.Models +{ + /// The input artifacts for the test. + public partial class TestInputArtifacts + { + /// Initializes a new instance of TestInputArtifacts. + internal TestInputArtifacts() + { + AdditionalFileInfo = new ChangeTrackingList(); + } + + /// Initializes a new instance of TestInputArtifacts. + /// File info. + /// File info. + /// File info. + /// File info. + /// Additional supported files for the test run. + internal TestInputArtifacts(FileInfo configFileInfo, FileInfo testScriptFileInfo, FileInfo userPropFileInfo, FileInfo inputArtifactsZipFileInfo, IReadOnlyList additionalFileInfo) + { + ConfigFileInfo = configFileInfo; + TestScriptFileInfo = testScriptFileInfo; + UserPropFileInfo = userPropFileInfo; + InputArtifactsZipFileInfo = inputArtifactsZipFileInfo; + AdditionalFileInfo = additionalFileInfo; + } + + /// File info. + public FileInfo ConfigFileInfo { get; } + /// File info. + public FileInfo TestScriptFileInfo { get; } + /// File info. + public FileInfo UserPropFileInfo { get; } + /// File info. + public FileInfo InputArtifactsZipFileInfo { get; } + /// Additional supported files for the test run. + public IReadOnlyList AdditionalFileInfo { get; } + } +} diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/tests/Generated/Samples/Samples_LoadTestAdministrationClient.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/tests/Generated/Samples/Samples_LoadTestAdministrationClient.cs index 7bdc52dea772..427f264a0cf2 100644 --- a/sdk/loadtestservice/Azure.Developer.LoadTesting/tests/Generated/Samples/Samples_LoadTestAdministrationClient.cs +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/tests/Generated/Samples/Samples_LoadTestAdministrationClient.cs @@ -365,7 +365,7 @@ public void Example_GetTest() var endpoint = new Uri(""); var client = new LoadTestAdministrationClient(endpoint, credential); - Response response = client.GetTest(""); + Response response = client.GetTest("", new RequestContext()); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; Console.WriteLine(result.ToString()); @@ -379,7 +379,7 @@ public void Example_GetTest_AllParameters() var endpoint = new Uri(""); var client = new LoadTestAdministrationClient(endpoint, credential); - Response response = client.GetTest(""); + Response response = client.GetTest("", new RequestContext()); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; Console.WriteLine(result.GetProperty("passFailCriteria").GetProperty("passFailMetrics").GetProperty("").GetProperty("clientMetric").ToString()); @@ -453,7 +453,7 @@ public async Task Example_GetTest_Async() var endpoint = new Uri(""); var client = new LoadTestAdministrationClient(endpoint, credential); - Response response = await client.GetTestAsync(""); + Response response = await client.GetTestAsync("", new RequestContext()); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; Console.WriteLine(result.ToString()); @@ -467,7 +467,7 @@ public async Task Example_GetTest_AllParameters_Async() var endpoint = new Uri(""); var client = new LoadTestAdministrationClient(endpoint, credential); - Response response = await client.GetTestAsync(""); + Response response = await client.GetTestAsync("", new RequestContext()); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; Console.WriteLine(result.GetProperty("passFailCriteria").GetProperty("passFailMetrics").GetProperty("").GetProperty("clientMetric").ToString()); diff --git a/sdk/loadtestservice/Azure.Developer.LoadTesting/tests/LoadTestAdministrationClientTest.cs b/sdk/loadtestservice/Azure.Developer.LoadTesting/tests/LoadTestAdministrationClientTest.cs index 4c3004ccbc8f..36b4ad138817 100644 --- a/sdk/loadtestservice/Azure.Developer.LoadTesting/tests/LoadTestAdministrationClientTest.cs +++ b/sdk/loadtestservice/Azure.Developer.LoadTesting/tests/LoadTestAdministrationClientTest.cs @@ -9,13 +9,12 @@ using System.Threading.Tasks; using Azure.Core; using Azure.Core.TestFramework; -using Azure.Core.TestFramework.Models; -using Azure.Developer.LoadTesting.Tests.Helper; +using Azure.Developer.LoadTesting.Models; using NUnit.Framework; namespace Azure.Developer.LoadTesting.Tests { - public class LoadTestAdministrationClientTest: LoadTestTestsBase + public class LoadTestAdministrationClientTest : LoadTestTestsBase { public LoadTestAdministrationClientTest(bool isAsync) : base(isAsync) { } @@ -44,6 +43,61 @@ public async Task TearDown() } } + [Test] + [Category(SKIP_SET_UP)] + [RecordedTest] + public async Task CreateOrUpdateTestConveninence() + { + Test test = new Test(""); + test.Description = "This test was created through loadtesting C# SDK"; + test.DisplayName = "Dotnet Testing Framework Loadtest"; + test.LoadTestConfiguration = new LoadTestConfiguration(); + test.LoadTestConfiguration.EngineInstances = 1; + test.LoadTestConfiguration.SplitAllCSVs = false; + test.Secrets.Clear(); + test.EnvironmentVariables.Clear(); + test.PassFailCriteria = new PassFailCriteria(); + test.PassFailCriteria.PassFailMetrics.Clear(); + + Response response = await _loadTestAdministrationClient.CreateOrUpdateTestAsync(test); + Assert.AreEqual(_testId, response.Value.TestId); + } + + private Test GetTest() + { + Test test = new Test(""); + test.Description = "This test was created through loadtesting C# SDK"; + test.DisplayName = "Dotnet Testing Framework Loadtest"; + test.LoadTestConfiguration = new LoadTestConfiguration(); + test.LoadTestConfiguration.EngineInstances = 1; + test.LoadTestConfiguration.SplitAllCSVs = false; + test.Secrets.Clear(); + test.EnvironmentVariables.Clear(); + test.PassFailCriteria = new PassFailCriteria(); + test.PassFailCriteria.PassFailMetrics.Clear(); + return test; + } + + [Test] + [Category(SKIP_SET_UP)] + [RecordedTest] + public async Task RoundTripTestValueConvenience() + { + Test orig = GetTest(); + + // Retrieve the value from the service. + Test test = await _loadTestAdministrationClient.CreateOrUpdateTestAsync(orig); + + // Change a value on the model. + test.EnvironmentVariables["NewEnvVar"] = "NewValue"; + + // Update the value on the service. + Test modified = await _loadTestAdministrationClient.CreateOrUpdateTestAsync(test); + + // Confirm update. + Assert.AreEqual("NewValue", modified.EnvironmentVariables["NewEnvVar"]); + } + [Test] [Category(SKIP_SET_UP)] public async Task CreateOrUpdateTest() @@ -97,7 +151,7 @@ public async Task DeleteTest() [Test] public async Task GetLoadTest() { - Response response = await _loadTestAdministrationClient.GetTestAsync(_testId); + Response response = await _loadTestAdministrationClient.GetTestAsync(_testId, new RequestContext()); JsonDocument jsonDocument = JsonDocument.Parse(response.Content.ToString()); Assert.NotNull(response.Content); Assert.AreEqual(_testId, jsonDocument.RootElement.GetProperty("testId").ToString()); @@ -115,13 +169,13 @@ public async Task ListLoadTest() { count++; - foreach (var value in page.Values) - { + foreach (var value in page.Values) + { JsonDocument jsonDocument = JsonDocument.Parse(value.ToString()); Assert.NotNull(jsonDocument.RootElement.GetProperty("testId").ToString()); Console.WriteLine(value.ToString()); - } + } } int i = 0; @@ -129,7 +183,7 @@ public async Task ListLoadTest() { i++; - if (i + +#nullable disable + +using System; +using Azure.Core; +using Azure.Core.Serialization; +using Azure.Developer.LoadTesting.Models; +using Azure.Identity; +using NUnit.Framework; + +namespace Azure.Developer.LoadTesting.Tests.Samples +{ + public class LoadTestingPatchModelSampels + { + [Test] + public void RoundTripLoadTestSample_ProtocolMethods() + { + LoadTestAdministrationClient client = new LoadTestAdministrationClient(new Uri(""), new DefaultAzureCredential()); + + Response response = client.GetTest("", new RequestContext()); + + dynamic loadTest = response.Content.ToDynamicFromJson(JsonPropertyNames.CamelCase); + Console.WriteLine($"Test ID: '{loadTest.TestId}'."); + Console.WriteLine($"Display Name: '{loadTest.DisplayName}'."); + + var patch = new + { + enviornmentVariables = new + { + myVariable = "my-value" + } + }; + + // Sends JSON """{{"enviornmentVariables": {"myVariable": "my-value"}}}""" + client.CreateOrUpdateTest(loadTest.TestId, RequestContent.Create(patch)); + } + + [Test] + public void RoundTripLoadTestSample_ProtocolMethods_DeleteVariable() + { + LoadTestAdministrationClient client = new LoadTestAdministrationClient(new Uri(""), new DefaultAzureCredential()); + + Response response = client.GetTest("", new RequestContext()); + + dynamic loadTest = response.Content.ToDynamicFromJson(JsonPropertyNames.CamelCase); + Console.WriteLine($"Test ID: '{loadTest.TestId}'."); + Console.WriteLine($"Display Name: '{loadTest.DisplayName}'."); + + var patch = new + { + enviornmentVariables = new + { + myVariable = (object)null + } + }; + + // Sends JSON """{{"enviornmentVariables": {"myVariable": "my-value"}}}""" + client.CreateOrUpdateTest(loadTest.TestId, RequestContent.Create(patch)); + } + + [Test] + public void RoundTripRouterJobSample_ProtocolMethods_DeleteLabel_DynamicData() + { + LoadTestAdministrationClient client = new LoadTestAdministrationClient(new Uri(""), new DefaultAzureCredential()); + + Response response = client.GetTest("", new RequestContext()); + + dynamic loadTest = response.Content.ToDynamicFromJson(JsonPropertyNames.CamelCase); + Console.WriteLine($"Test ID: '{loadTest.TestId}'."); + Console.WriteLine($"Display Name: '{loadTest.DisplayName}'."); + + loadTest.EnvironmentVariables["myVariable"] = null; + + // Sends JSON """{{"enviornmentVariables": {"myVariable": "my-value"}}}""" + client.CreateOrUpdateTest(loadTest.TestId, RequestContent.Create(loadTest, new ModelSerializerOptions("P"))); + } + + [Test] + public void RoundTripRouterJobSample_ConvenienceMethods() + { + LoadTestAdministrationClient client = new LoadTestAdministrationClient(new Uri(""), new DefaultAzureCredential()); + + Test loadTest = client.GetTest(""); + + Console.WriteLine($"Test ID: '{loadTest.TestId}'."); + Console.WriteLine($"Display Name: '{loadTest.DisplayName}'."); + + loadTest.EnvironmentVariables["myVariable"] = "my-value"; + + // Sends JSON """{{"enviornmentVariables": {"myVariable": "my-value"}}}""" + client.CreateOrUpdateTest(loadTest); + } + + [Test] + public void RoundTripRouterJobSample_ConvenienceMethods_DeleteLabel() + { + LoadTestAdministrationClient client = new LoadTestAdministrationClient(new Uri(""), new DefaultAzureCredential()); + + Test loadTest = client.GetTest(""); + + Console.WriteLine($"Test ID: '{loadTest.TestId}'."); + Console.WriteLine($"Display Name: '{loadTest.DisplayName}'."); + + loadTest.EnvironmentVariables.Remove("myVariable"); + + // Sends JSON """{{"enviornmentVariables": {"myVariable": "null"}}}""" + client.CreateOrUpdateTest(loadTest); + } + [Test] + public void PatchWithoutGetRouterJobSample_ProtocolMethods() + { + LoadTestAdministrationClient client = new LoadTestAdministrationClient(new Uri(""), new DefaultAzureCredential()); + + var patch = new + { + enviornmentVariables = new + { + myVariable = "my-value" + } + }; + + // Sends JSON """{{"enviornmentVariables": {"myVariable": "my-value"}}}""" + client.CreateOrUpdateTest("", RequestContent.Create(patch)); + } + + [Test] + public void PatchWithoutGetRouterJobSample_ProtocolMethods_DeleteLabel() + { + LoadTestAdministrationClient client = new LoadTestAdministrationClient(new Uri(""), new DefaultAzureCredential()); + + var patch = new + { + enviornmentVariables = new + { + myVariable = (object)null + } + }; + + // Sends JSON """{{"enviornmentVariables": {"myVariable": "null"}}}""" + client.CreateOrUpdateTest("", RequestContent.Create(patch)); + } + + [Test] + public void PatchWithoutGetRouterJobSample_ConvenienceMethods() + { + LoadTestAdministrationClient client = new LoadTestAdministrationClient(new Uri(""), new DefaultAzureCredential()); + + Test loadTest = new Test(""); + + loadTest.EnvironmentVariables["myVariable"] = "my-value"; + + // Sends JSON """{{"enviornmentVariables": {"myVariable": "my-value"}}}""" + client.CreateOrUpdateTest(loadTest); + } + + [Test] + public void PatchWithoutGetRouterJobSample_ConvenienceMethods_DeleteLabel() + { + LoadTestAdministrationClient client = new LoadTestAdministrationClient(new Uri(""), new DefaultAzureCredential()); + + Test loadTest = new Test(""); + + loadTest.EnvironmentVariables.Remove("myVariable"); + + // Sends JSON """{{"enviornmentVariables": {"myVariable": "null"}}}""" + client.CreateOrUpdateTest(loadTest); + } + } +} diff --git a/sdk/template/Azure.Template/Azure.Template.sln b/sdk/template/Azure.Template/Azure.Template.sln index 878fbf3746ed..853bb4cd0db6 100644 --- a/sdk/template/Azure.Template/Azure.Template.sln +++ b/sdk/template/Azure.Template/Azure.Template.sln @@ -1,15 +1,15 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29709.97 +# Visual Studio Version 17 +VisualStudioVersion = 17.7.34003.232 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core.TestFramework", "..\..\core\Azure.Core.TestFramework\src\Azure.Core.TestFramework.csproj", "{ECC730C1-4AEA-420C-916A-66B19B79E4DC}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Template", "src\Azure.Template.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Communication.JobRouter", "src\Azure.Communication.JobRouter.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Template.Perf", "perf\Azure.Template.Perf.csproj", "{30C5FF85-655A-49FC-A324-16438130FF3F}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Communication.JobRouter.Tests", "tests\Azure.Communication.JobRouter.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Template.Tests", "tests\Azure.Template.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core", "..\..\core\Azure.Core\src\Azure.Core.csproj", "{BDBF5A68-31B4-4A0A-86A0-3A270C15BC2A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -17,42 +17,22 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.Build.0 = Release|Any CPU - {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.Build.0 = Release|Any CPU {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Debug|Any CPU.Build.0 = Debug|Any CPU {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Release|Any CPU.ActiveCfg = Release|Any CPU {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Release|Any CPU.Build.0 = Release|Any CPU - {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.Build.0 = Release|Any CPU - {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.Build.0 = Release|Any CPU - {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.Build.0 = Release|Any CPU {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.Build.0 = Debug|Any CPU {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.ActiveCfg = Release|Any CPU {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.Build.0 = Release|Any CPU - {30C5FF85-655A-49FC-A324-16438130FF3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {30C5FF85-655A-49FC-A324-16438130FF3F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {30C5FF85-655A-49FC-A324-16438130FF3F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {30C5FF85-655A-49FC-A324-16438130FF3F}.Release|Any CPU.Build.0 = Release|Any CPU {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.Build.0 = Debug|Any CPU {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.ActiveCfg = Release|Any CPU {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.Build.0 = Release|Any CPU + {BDBF5A68-31B4-4A0A-86A0-3A270C15BC2A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BDBF5A68-31B4-4A0A-86A0-3A270C15BC2A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BDBF5A68-31B4-4A0A-86A0-3A270C15BC2A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BDBF5A68-31B4-4A0A-86A0-3A270C15BC2A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/sdk/template/Azure.Template/api/Azure.Communication.JobRouter.netstandard2.0.cs b/sdk/template/Azure.Template/api/Azure.Communication.JobRouter.netstandard2.0.cs new file mode 100644 index 000000000000..e10d1c9a663e --- /dev/null +++ b/sdk/template/Azure.Template/api/Azure.Communication.JobRouter.netstandard2.0.cs @@ -0,0 +1,285 @@ +namespace Azure.Communication.JobRouter +{ + public partial class AzureCommunicationServicesClientOptions : Azure.Core.ClientOptions + { + public AzureCommunicationServicesClientOptions(Azure.Communication.JobRouter.AzureCommunicationServicesClientOptions.ServiceVersion version = Azure.Communication.JobRouter.AzureCommunicationServicesClientOptions.ServiceVersion.V2022_07_18_Preview) { } + public enum ServiceVersion + { + V2022_07_18_Preview = 1, + } + } + public partial class JobRouterAdministrationClient + { + protected JobRouterAdministrationClient() { } + public JobRouterAdministrationClient(string endpoint, Azure.Core.TokenCredential credential) { } + public JobRouterAdministrationClient(string endpoint, Azure.Core.TokenCredential credential, Azure.Communication.JobRouter.AzureCommunicationServicesClientOptions options) { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Response DeleteClassificationPolicy(string id, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task DeleteClassificationPolicyAsync(string id, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response DeleteDistributionPolicy(string id, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task DeleteDistributionPolicyAsync(string id, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response DeleteExceptionPolicy(string id, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task DeleteExceptionPolicyAsync(string id, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response DeleteQueue(string id, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task DeleteQueueAsync(string id, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Pageable GetClassificationPolicies(int? maxpagesize, Azure.RequestContext context) { throw null; } + public virtual Azure.AsyncPageable GetClassificationPoliciesAsync(int? maxpagesize, Azure.RequestContext context) { throw null; } + public virtual Azure.Response GetClassificationPolicy(string id, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task GetClassificationPolicyAsync(string id, Azure.RequestContext context) { throw null; } + public virtual Azure.Pageable GetDistributionPolicies(int? maxpagesize, Azure.RequestContext context) { throw null; } + public virtual Azure.AsyncPageable GetDistributionPoliciesAsync(int? maxpagesize, Azure.RequestContext context) { throw null; } + public virtual Azure.Response GetDistributionPolicy(string id, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task GetDistributionPolicyAsync(string id, Azure.RequestContext context) { throw null; } + public virtual Azure.Pageable GetExceptionPolicies(int? maxpagesize, Azure.RequestContext context) { throw null; } + public virtual Azure.AsyncPageable GetExceptionPoliciesAsync(int? maxpagesize, Azure.RequestContext context) { throw null; } + public virtual Azure.Response GetExceptionPolicy(string id, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task GetExceptionPolicyAsync(string id, Azure.RequestContext context) { throw null; } + public virtual Azure.Response GetQueue(string id, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task GetQueueAsync(string id, Azure.RequestContext context) { throw null; } + public virtual Azure.Pageable GetQueues(int? maxpagesize, Azure.RequestContext context) { throw null; } + public virtual Azure.AsyncPageable GetQueuesAsync(int? maxpagesize, Azure.RequestContext context) { throw null; } + public virtual Azure.Response UpsertClassificationPolicy(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task UpsertClassificationPolicyAsync(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response UpsertDistributionPolicy(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task UpsertDistributionPolicyAsync(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response UpsertExceptionPolicy(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task UpsertExceptionPolicyAsync(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response UpsertQueue(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task UpsertQueueAsync(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + } + public partial class JobRouterClient + { + protected JobRouterClient() { } + public JobRouterClient(string endpoint, Azure.Core.TokenCredential credential) { } + public JobRouterClient(string endpoint, Azure.Core.TokenCredential credential, Azure.Communication.JobRouter.AzureCommunicationServicesClientOptions options) { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Response AcceptJobAction(string workerId, string offerId, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task AcceptJobActionAsync(string workerId, string offerId, Azure.RequestContext context) { throw null; } + public virtual Azure.Response CancelJobAction(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task CancelJobActionAsync(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response CloseJobAction(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task CloseJobActionAsync(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response CompleteJobAction(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task CompleteJobActionAsync(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response DeclineJobAction(string workerId, string offerId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task DeclineJobActionAsync(string workerId, string offerId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response DeleteJob(string id, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task DeleteJobAsync(string id, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response DeleteWorker(string workerId, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task DeleteWorkerAsync(string workerId, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response GetInQueuePosition(string id, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task GetInQueuePositionAsync(string id, Azure.RequestContext context) { throw null; } + public virtual Azure.Response GetJob(string id, Azure.RequestContext context) { throw null; } + public virtual Azure.Response GetJob(string id, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task GetJobAsync(string id, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task> GetJobAsync(string id, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Pageable GetJobs(string status, string queueId, string channelId, string classificationPolicyId, System.DateTimeOffset? scheduledBefore, System.DateTimeOffset? scheduledAfter, int? maxpagesize, Azure.RequestContext context) { throw null; } + public virtual Azure.AsyncPageable GetJobsAsync(string status, string queueId, string channelId, string classificationPolicyId, System.DateTimeOffset? scheduledBefore, System.DateTimeOffset? scheduledAfter, int? maxpagesize, Azure.RequestContext context) { throw null; } + public virtual Azure.Response GetQueueStatistics(string id, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task GetQueueStatisticsAsync(string id, Azure.RequestContext context) { throw null; } + public virtual Azure.Response GetWorker(string workerId, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task GetWorkerAsync(string workerId, Azure.RequestContext context) { throw null; } + public virtual Azure.Pageable GetWorkers(string state, string channelId, string queueId, bool? hasCapacity, int? maxpagesize, Azure.RequestContext context) { throw null; } + public virtual Azure.AsyncPageable GetWorkersAsync(string state, string channelId, string queueId, bool? hasCapacity, int? maxpagesize, Azure.RequestContext context) { throw null; } + public virtual Azure.Response ReclassifyJobAction(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task ReclassifyJobActionAsync(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response UnassignJobAction(string id, string assignmentId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task UnassignJobActionAsync(string id, string assignmentId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response UpsertJob(Azure.Communication.JobRouter.Models.RouterJob job, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response UpsertJob(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> UpsertJobAsync(Azure.Communication.JobRouter.Models.RouterJob job, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task UpsertJobAsync(string id, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response UpsertWorker(string workerId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task UpsertWorkerAsync(string workerId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + } +} +namespace Azure.Communication.JobRouter.Models +{ + public partial class JobMatchingMode + { + public JobMatchingMode() { } + public Azure.Communication.JobRouter.Models.JobMatchModeType? ModeType { get { throw null; } set { } } + public object QueueAndMatchMode { get { throw null; } set { } } + public Azure.Communication.JobRouter.Models.ScheduleAndSuspendMode ScheduleAndSuspendMode { get { throw null; } set { } } + public object SuspendMode { get { throw null; } set { } } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct JobMatchModeType : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public JobMatchModeType(string value) { throw null; } + public static Azure.Communication.JobRouter.Models.JobMatchModeType QueueAndMatchMode { get { throw null; } } + public static Azure.Communication.JobRouter.Models.JobMatchModeType ScheduleAndSuspendMode { get { throw null; } } + public static Azure.Communication.JobRouter.Models.JobMatchModeType SuspendMode { get { throw null; } } + public bool Equals(Azure.Communication.JobRouter.Models.JobMatchModeType other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Communication.JobRouter.Models.JobMatchModeType left, Azure.Communication.JobRouter.Models.JobMatchModeType right) { throw null; } + public static implicit operator Azure.Communication.JobRouter.Models.JobMatchModeType (string value) { throw null; } + public static bool operator !=(Azure.Communication.JobRouter.Models.JobMatchModeType left, Azure.Communication.JobRouter.Models.JobMatchModeType right) { throw null; } + public override string ToString() { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct LabelOperator : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public LabelOperator(string value) { throw null; } + public static Azure.Communication.JobRouter.Models.LabelOperator Equal { get { throw null; } } + public static Azure.Communication.JobRouter.Models.LabelOperator GreaterThan { get { throw null; } } + public static Azure.Communication.JobRouter.Models.LabelOperator GreaterThanEqual { get { throw null; } } + public static Azure.Communication.JobRouter.Models.LabelOperator LessThan { get { throw null; } } + public static Azure.Communication.JobRouter.Models.LabelOperator LessThanEqual { get { throw null; } } + public static Azure.Communication.JobRouter.Models.LabelOperator NotEqual { get { throw null; } } + public bool Equals(Azure.Communication.JobRouter.Models.LabelOperator other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Communication.JobRouter.Models.LabelOperator left, Azure.Communication.JobRouter.Models.LabelOperator right) { throw null; } + public static implicit operator Azure.Communication.JobRouter.Models.LabelOperator (string value) { throw null; } + public static bool operator !=(Azure.Communication.JobRouter.Models.LabelOperator left, Azure.Communication.JobRouter.Models.LabelOperator right) { throw null; } + public override string ToString() { throw null; } + } + public partial class RouterJob : Azure.Core.Serialization.IModelJsonSerializable, Azure.Core.Serialization.IModelSerializable + { + public RouterJob(string id) { } + public System.Collections.Generic.IReadOnlyDictionary Assignments { get { throw null; } } + public System.Collections.Generic.IReadOnlyList AttachedWorkerSelectors { get { throw null; } } + public string ChannelId { get { throw null; } set { } } + public string ChannelReference { get { throw null; } set { } } + public string ClassificationPolicyId { get { throw null; } set { } } + public string DispositionCode { get { throw null; } set { } } + public System.DateTimeOffset? EnqueuedAt { get { throw null; } } + public string Id { get { throw null; } } + public System.Collections.Generic.IDictionary Labels { get { throw null; } } + public Azure.Communication.JobRouter.Models.JobMatchingMode MatchingMode { get { throw null; } set { } } + public System.Collections.Generic.IDictionary Notes { get { throw null; } } + public int? Priority { get { throw null; } set { } } + public string QueueId { get { throw null; } set { } } + public System.Collections.Generic.IList RequestedWorkerSelectors { get { throw null; } } + public System.DateTimeOffset? ScheduledAt { get { throw null; } } + public Azure.Communication.JobRouter.Models.RouterJobStatus? Status { get { throw null; } } + public System.Collections.Generic.IDictionary Tags { get { throw null; } } + Azure.Communication.JobRouter.Models.RouterJob Azure.Core.Serialization.IModelJsonSerializable.Deserialize(ref System.Text.Json.Utf8JsonReader reader, Azure.Core.Serialization.ModelSerializerOptions options) { throw null; } + void Azure.Core.Serialization.IModelJsonSerializable.Serialize(System.Text.Json.Utf8JsonWriter writer, Azure.Core.Serialization.ModelSerializerOptions options) { } + Azure.Communication.JobRouter.Models.RouterJob Azure.Core.Serialization.IModelSerializable.Deserialize(System.BinaryData data, Azure.Core.Serialization.ModelSerializerOptions options) { throw null; } + System.BinaryData Azure.Core.Serialization.IModelSerializable.Serialize(Azure.Core.Serialization.ModelSerializerOptions options) { throw null; } + public static explicit operator Azure.Communication.JobRouter.Models.RouterJob (Azure.Response response) { throw null; } + public static implicit operator Azure.Core.RequestContent (Azure.Communication.JobRouter.Models.RouterJob model) { throw null; } + } + public partial class RouterJobAssignment + { + internal RouterJobAssignment() { } + public System.DateTimeOffset AssignedAt { get { throw null; } } + public string AssignmentId { get { throw null; } } + public System.DateTimeOffset? ClosedAt { get { throw null; } } + public System.DateTimeOffset? CompletedAt { get { throw null; } } + public string WorkerId { get { throw null; } } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct RouterJobStatus : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public RouterJobStatus(string value) { throw null; } + public static Azure.Communication.JobRouter.Models.RouterJobStatus Assigned { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatus Cancelled { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatus ClassificationFailed { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatus Closed { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatus Completed { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatus Created { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatus PendingClassification { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatus PendingSchedule { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatus Queued { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatus Scheduled { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatus ScheduleFailed { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatus WaitingForActivation { get { throw null; } } + public bool Equals(Azure.Communication.JobRouter.Models.RouterJobStatus other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Communication.JobRouter.Models.RouterJobStatus left, Azure.Communication.JobRouter.Models.RouterJobStatus right) { throw null; } + public static implicit operator Azure.Communication.JobRouter.Models.RouterJobStatus (string value) { throw null; } + public static bool operator !=(Azure.Communication.JobRouter.Models.RouterJobStatus left, Azure.Communication.JobRouter.Models.RouterJobStatus right) { throw null; } + public override string ToString() { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct RouterJobStatusSelector : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public RouterJobStatusSelector(string value) { throw null; } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector Active { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector All { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector Assigned { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector Cancelled { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector ClassificationFailed { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector Closed { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector Completed { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector Created { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector PendingClassification { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector PendingSchedule { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector Queued { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector Scheduled { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector ScheduleFailed { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterJobStatusSelector WaitingForActivation { get { throw null; } } + public bool Equals(Azure.Communication.JobRouter.Models.RouterJobStatusSelector other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Communication.JobRouter.Models.RouterJobStatusSelector left, Azure.Communication.JobRouter.Models.RouterJobStatusSelector right) { throw null; } + public static implicit operator Azure.Communication.JobRouter.Models.RouterJobStatusSelector (string value) { throw null; } + public static bool operator !=(Azure.Communication.JobRouter.Models.RouterJobStatusSelector left, Azure.Communication.JobRouter.Models.RouterJobStatusSelector right) { throw null; } + public override string ToString() { throw null; } + } + public partial class RouterWorkerSelector + { + public RouterWorkerSelector(string key, Azure.Communication.JobRouter.Models.LabelOperator labelOperator) { } + public bool? Expedite { get { throw null; } set { } } + public double? ExpiresAfterSeconds { get { throw null; } set { } } + public System.DateTimeOffset? ExpiresAt { get { throw null; } } + public string Key { get { throw null; } set { } } + public Azure.Communication.JobRouter.Models.LabelOperator LabelOperator { get { throw null; } set { } } + public Azure.Communication.JobRouter.Models.RouterWorkerSelectorStatus? Status { get { throw null; } } + public object Value { get { throw null; } set { } } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct RouterWorkerSelectorStatus : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public RouterWorkerSelectorStatus(string value) { throw null; } + public static Azure.Communication.JobRouter.Models.RouterWorkerSelectorStatus Active { get { throw null; } } + public static Azure.Communication.JobRouter.Models.RouterWorkerSelectorStatus Expired { get { throw null; } } + public bool Equals(Azure.Communication.JobRouter.Models.RouterWorkerSelectorStatus other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.Communication.JobRouter.Models.RouterWorkerSelectorStatus left, Azure.Communication.JobRouter.Models.RouterWorkerSelectorStatus right) { throw null; } + public static implicit operator Azure.Communication.JobRouter.Models.RouterWorkerSelectorStatus (string value) { throw null; } + public static bool operator !=(Azure.Communication.JobRouter.Models.RouterWorkerSelectorStatus left, Azure.Communication.JobRouter.Models.RouterWorkerSelectorStatus right) { throw null; } + public override string ToString() { throw null; } + } + public partial class ScheduleAndSuspendMode + { + public ScheduleAndSuspendMode() { } + public System.DateTimeOffset? ScheduleAt { get { throw null; } set { } } + } +} +namespace Microsoft.Extensions.Azure +{ + public static partial class CommunicationJobRouterClientBuilderExtensions + { + public static Azure.Core.Extensions.IAzureClientBuilder AddJobRouterAdministrationClient(this TBuilder builder, string endpoint) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddJobRouterAdministrationClient(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddJobRouterClient(this TBuilder builder, string endpoint) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddJobRouterClient(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration { throw null; } + } +} diff --git a/sdk/template/Azure.Template/api/Azure.Template.netstandard2.0.cs b/sdk/template/Azure.Template/api/Azure.Template.netstandard2.0.cs deleted file mode 100644 index 28cd3bda804d..000000000000 --- a/sdk/template/Azure.Template/api/Azure.Template.netstandard2.0.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace Azure.Template -{ - public partial class TemplateClient - { - protected TemplateClient() { } - public TemplateClient(string vaultBaseUrl, Azure.Core.TokenCredential credential) { } - public TemplateClient(string vaultBaseUrl, Azure.Core.TokenCredential credential, Azure.Template.TemplateClientOptions options) { } - public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } - public virtual Azure.Response GetSecret(string secretName, Azure.RequestContext context) { throw null; } - public virtual System.Threading.Tasks.Task GetSecretAsync(string secretName, Azure.RequestContext context) { throw null; } - public virtual Azure.Response GetSecretValue(string secretName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } - public virtual System.Threading.Tasks.Task> GetSecretValueAsync(string secretName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } - } - public partial class TemplateClientOptions : Azure.Core.ClientOptions - { - public TemplateClientOptions(Azure.Template.TemplateClientOptions.ServiceVersion version = Azure.Template.TemplateClientOptions.ServiceVersion.V7_0) { } - public enum ServiceVersion - { - V7_0 = 1, - } - } -} -namespace Azure.Template.Models -{ - public partial class SecretBundle - { - internal SecretBundle() { } - public string ContentType { get { throw null; } } - public string Id { get { throw null; } } - public string Kid { get { throw null; } } - public bool? Managed { get { throw null; } } - public System.Collections.Generic.IReadOnlyDictionary Tags { get { throw null; } } - public string Value { get { throw null; } } - } -} -namespace Microsoft.Extensions.Azure -{ - public static partial class TemplateClientBuilderExtensions - { - public static Azure.Core.Extensions.IAzureClientBuilder AddTemplateClient(this TBuilder builder, string vaultBaseUrl) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } - public static Azure.Core.Extensions.IAzureClientBuilder AddTemplateClient(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration { throw null; } - } -} diff --git a/sdk/template/Azure.Template/perf/Azure.Template.Perf.csproj b/sdk/template/Azure.Template/perf/Azure.Communication.JobRouter.Perf.csproj similarity index 80% rename from sdk/template/Azure.Template/perf/Azure.Template.Perf.csproj rename to sdk/template/Azure.Template/perf/Azure.Communication.JobRouter.Perf.csproj index d35274819ae5..65543f0eb0bf 100644 --- a/sdk/template/Azure.Template/perf/Azure.Template.Perf.csproj +++ b/sdk/template/Azure.Template/perf/Azure.Communication.JobRouter.Perf.csproj @@ -5,7 +5,7 @@ - + diff --git a/sdk/template/Azure.Template/perf/TemplateClientTest.cs b/sdk/template/Azure.Template/perf/TemplateClientTest.cs deleted file mode 100644 index 6c6b0f58f2a8..000000000000 --- a/sdk/template/Azure.Template/perf/TemplateClientTest.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Identity; -using Azure.Test.Perf; -using CommandLine; - -namespace Azure.Template.Perf -{ - public class TemplateClientTest : PerfTest - { - private readonly TemplateClient _templateClient; - - public TemplateClientTest(TemplateClientPerfOptions options) : base(options) - { - string keyVaultUri = GetEnvironmentVariable("KEYVAULT_URL"); - _templateClient = new TemplateClient(keyVaultUri, new DefaultAzureCredential()); - } - - public override void Run(CancellationToken cancellationToken) - { - // Throttle requests to avoid exceeding service limits - Thread.Sleep(TimeSpan.FromMilliseconds(Options.Delay)); - - _templateClient.GetSecretValue(Options.SecretName, cancellationToken); - } - - public override async Task RunAsync(CancellationToken cancellationToken) - { - // Throttle requests to avoid exceeding service limits - await Task.Delay(TimeSpan.FromMilliseconds(Options.Delay), cancellationToken); - - await _templateClient.GetSecretValueAsync(Options.SecretName, cancellationToken); - } - - public class TemplateClientPerfOptions : PerfOptions - { - [Option("secret-name", Default = "TestSecret", HelpText = "Name of secret to get")] - public string SecretName { get; set; } - - [Option("delay", Default = 100, HelpText = "Delay between gets (milliseconds)")] - public int Delay { get; set; } - } - } -} diff --git a/sdk/template/Azure.Template/src/Azure.Template.csproj b/sdk/template/Azure.Template/src/Azure.Communication.JobRouter.csproj similarity index 84% rename from sdk/template/Azure.Template/src/Azure.Template.csproj rename to sdk/template/Azure.Template/src/Azure.Communication.JobRouter.csproj index 6fad75958403..e7b5594e8d00 100644 --- a/sdk/template/Azure.Template/src/Azure.Template.csproj +++ b/sdk/template/Azure.Template/src/Azure.Communication.JobRouter.csproj @@ -15,8 +15,13 @@ - + + + + + + \ No newline at end of file diff --git a/sdk/template/Azure.Template/src/Generated/AzureCommunicationServicesClientOptions.cs b/sdk/template/Azure.Template/src/Generated/AzureCommunicationServicesClientOptions.cs new file mode 100644 index 000000000000..1083993b8213 --- /dev/null +++ b/sdk/template/Azure.Template/src/Generated/AzureCommunicationServicesClientOptions.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.Communication.JobRouter +{ + /// Client options for AzureCommunicationServices library clients. + public partial class AzureCommunicationServicesClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2022_07_18_Preview; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2022-07-18-preview". + V2022_07_18_Preview = 1, + } + + internal string Version { get; } + + /// Initializes new instance of AzureCommunicationServicesClientOptions. + public AzureCommunicationServicesClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2022_07_18_Preview => "2022-07-18-preview", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/template/Azure.Template/src/Generated/CommunicationJobRouterClientBuilderExtensions.cs b/sdk/template/Azure.Template/src/Generated/CommunicationJobRouterClientBuilderExtensions.cs new file mode 100644 index 000000000000..9a01e7cddd5b --- /dev/null +++ b/sdk/template/Azure.Template/src/Generated/CommunicationJobRouterClientBuilderExtensions.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using Azure.Communication.JobRouter; +using Azure.Core.Extensions; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add , to client builder. + public static partial class CommunicationJobRouterClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// The endpoint of the Azure Communication resource. + public static IAzureClientBuilder AddJobRouterAdministrationClient(this TBuilder builder, string endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new JobRouterAdministrationClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The endpoint of the Azure Communication resource. + public static IAzureClientBuilder AddJobRouterClient(this TBuilder builder, string endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new JobRouterClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddJobRouterAdministrationClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddJobRouterClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/template/Azure.Template/src/Generated/Docs/JobRouterAdministrationClient.xml b/sdk/template/Azure.Template/src/Generated/Docs/JobRouterAdministrationClient.xml new file mode 100644 index 000000000000..178b7b3a127d --- /dev/null +++ b/sdk/template/Azure.Template/src/Generated/Docs/JobRouterAdministrationClient.xml @@ -0,0 +1,837 @@ + + + + + +This sample shows how to call UpsertClassificationPolicyAsync with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = await client.UpsertClassificationPolicyAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call UpsertClassificationPolicyAsync with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + name = "", + fallbackQueueId = "", + queueSelectors = new[] { + new { + condition = new { + kind = "direct-map-rule", + }, + queueSelectors = new[] { + new { + key = "", + labelOperator = "equal", + value = new {}, + } + }, + kind = "conditional", + } + }, + prioritizationRule = new { + kind = "direct-map-rule", + }, + workerSelectors = new[] { + new { + condition = new { + kind = "direct-map-rule", + }, + workerSelectors = new[] { + new { + key = "", + labelOperator = "equal", + value = new {}, + expiresAfterSeconds = 123.45d, + expedite = true, + } + }, + kind = "conditional", + } + }, +}; + +Response response = await client.UpsertClassificationPolicyAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("fallbackQueueId").ToString()); +Console.WriteLine(result.GetProperty("queueSelectors")[0].GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("prioritizationRule").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("workerSelectors")[0].GetProperty("kind").ToString()); +]]> + + + + +This sample shows how to call UpsertClassificationPolicy with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = client.UpsertClassificationPolicy("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call UpsertClassificationPolicy with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + name = "", + fallbackQueueId = "", + queueSelectors = new[] { + new { + condition = new { + kind = "direct-map-rule", + }, + queueSelectors = new[] { + new { + key = "", + labelOperator = "equal", + value = new {}, + } + }, + kind = "conditional", + } + }, + prioritizationRule = new { + kind = "direct-map-rule", + }, + workerSelectors = new[] { + new { + condition = new { + kind = "direct-map-rule", + }, + workerSelectors = new[] { + new { + key = "", + labelOperator = "equal", + value = new {}, + expiresAfterSeconds = 123.45d, + expedite = true, + } + }, + kind = "conditional", + } + }, +}; + +Response response = client.UpsertClassificationPolicy("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("fallbackQueueId").ToString()); +Console.WriteLine(result.GetProperty("queueSelectors")[0].GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("prioritizationRule").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("workerSelectors")[0].GetProperty("kind").ToString()); +]]> + + + + +This sample shows how to call GetClassificationPolicyAsync with required parameters and parse the result. +", credential); + +Response response = await client.GetClassificationPolicyAsync("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("fallbackQueueId").ToString()); +Console.WriteLine(result.GetProperty("queueSelectors")[0].GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("prioritizationRule").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("workerSelectors")[0].GetProperty("kind").ToString()); +]]> + + + + +This sample shows how to call GetClassificationPolicy with required parameters and parse the result. +", credential); + +Response response = client.GetClassificationPolicy("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("fallbackQueueId").ToString()); +Console.WriteLine(result.GetProperty("queueSelectors")[0].GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("prioritizationRule").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("workerSelectors")[0].GetProperty("kind").ToString()); +]]> + + + + +This sample shows how to call DeleteClassificationPolicyAsync with required parameters. +", credential); + +Response response = await client.DeleteClassificationPolicyAsync(""); +Console.WriteLine(response.Status); +]]> + + + + +This sample shows how to call DeleteClassificationPolicy with required parameters. +", credential); + +Response response = client.DeleteClassificationPolicy(""); +Console.WriteLine(response.Status); +]]> + + + + +This sample shows how to call UpsertDistributionPolicyAsync with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = await client.UpsertDistributionPolicyAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call UpsertDistributionPolicyAsync with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + name = "", + offerExpiresAfterSeconds = 123.45d, + mode = new { + scoringRule = new { + kind = "direct-map-rule", + }, + scoringRuleOptions = new { + batchSize = 1234, + scoringParameters = new[] { + "jobLabels" + }, + allowScoringBatchOfWorkers = true, + descendingOrder = true, + }, + kind = "best-worker", + minConcurrentOffers = 1234, + maxConcurrentOffers = 1234, + bypassSelectors = true, + }, +}; + +Response response = await client.UpsertDistributionPolicyAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("offerExpiresAfterSeconds").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("minConcurrentOffers").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("maxConcurrentOffers").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("bypassSelectors").ToString()); +]]> + + + + +This sample shows how to call UpsertDistributionPolicy with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = client.UpsertDistributionPolicy("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call UpsertDistributionPolicy with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + name = "", + offerExpiresAfterSeconds = 123.45d, + mode = new { + scoringRule = new { + kind = "direct-map-rule", + }, + scoringRuleOptions = new { + batchSize = 1234, + scoringParameters = new[] { + "jobLabels" + }, + allowScoringBatchOfWorkers = true, + descendingOrder = true, + }, + kind = "best-worker", + minConcurrentOffers = 1234, + maxConcurrentOffers = 1234, + bypassSelectors = true, + }, +}; + +Response response = client.UpsertDistributionPolicy("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("offerExpiresAfterSeconds").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("minConcurrentOffers").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("maxConcurrentOffers").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("bypassSelectors").ToString()); +]]> + + + + +This sample shows how to call GetDistributionPolicyAsync with required parameters and parse the result. +", credential); + +Response response = await client.GetDistributionPolicyAsync("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("offerExpiresAfterSeconds").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("minConcurrentOffers").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("maxConcurrentOffers").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("bypassSelectors").ToString()); +]]> + + + + +This sample shows how to call GetDistributionPolicy with required parameters and parse the result. +", credential); + +Response response = client.GetDistributionPolicy("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("offerExpiresAfterSeconds").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("minConcurrentOffers").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("maxConcurrentOffers").ToString()); +Console.WriteLine(result.GetProperty("mode").GetProperty("bypassSelectors").ToString()); +]]> + + + + +This sample shows how to call DeleteDistributionPolicyAsync with required parameters. +", credential); + +Response response = await client.DeleteDistributionPolicyAsync(""); +Console.WriteLine(response.Status); +]]> + + + + +This sample shows how to call DeleteDistributionPolicy with required parameters. +", credential); + +Response response = client.DeleteDistributionPolicy(""); +Console.WriteLine(response.Status); +]]> + + + + +This sample shows how to call UpsertExceptionPolicyAsync with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = await client.UpsertExceptionPolicyAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call UpsertExceptionPolicyAsync with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + name = "", + exceptionRules = new { + key = new { + trigger = new { + threshold = 1234, + kind = "queue-length", + }, + actions = new { + key = new { + note = "", + dispositionCode = "", + kind = "cancel", + }, + }, + }, + }, +}; + +Response response = await client.UpsertExceptionPolicyAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("trigger").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("actions").GetProperty("").GetProperty("kind").ToString()); +]]> + + + + +This sample shows how to call UpsertExceptionPolicy with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = client.UpsertExceptionPolicy("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call UpsertExceptionPolicy with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + name = "", + exceptionRules = new { + key = new { + trigger = new { + threshold = 1234, + kind = "queue-length", + }, + actions = new { + key = new { + note = "", + dispositionCode = "", + kind = "cancel", + }, + }, + }, + }, +}; + +Response response = client.UpsertExceptionPolicy("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("trigger").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("actions").GetProperty("").GetProperty("kind").ToString()); +]]> + + + + +This sample shows how to call GetExceptionPolicyAsync with required parameters and parse the result. +", credential); + +Response response = await client.GetExceptionPolicyAsync("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("trigger").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("actions").GetProperty("").GetProperty("kind").ToString()); +]]> + + + + +This sample shows how to call GetExceptionPolicy with required parameters and parse the result. +", credential); + +Response response = client.GetExceptionPolicy("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("trigger").GetProperty("kind").ToString()); +Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("actions").GetProperty("").GetProperty("kind").ToString()); +]]> + + + + +This sample shows how to call DeleteExceptionPolicyAsync with required parameters. +", credential); + +Response response = await client.DeleteExceptionPolicyAsync(""); +Console.WriteLine(response.Status); +]]> + + + + +This sample shows how to call DeleteExceptionPolicy with required parameters. +", credential); + +Response response = client.DeleteExceptionPolicy(""); +Console.WriteLine(response.Status); +]]> + + + + +This sample shows how to call UpsertQueueAsync with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = await client.UpsertQueueAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call UpsertQueueAsync with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + name = "", + distributionPolicyId = "", + labels = new { + key = new {}, + }, + exceptionPolicyId = "", +}; + +Response response = await client.UpsertQueueAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("distributionPolicyId").ToString()); +Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("exceptionPolicyId").ToString()); +]]> + + + + +This sample shows how to call UpsertQueue with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = client.UpsertQueue("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call UpsertQueue with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + name = "", + distributionPolicyId = "", + labels = new { + key = new {}, + }, + exceptionPolicyId = "", +}; + +Response response = client.UpsertQueue("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("distributionPolicyId").ToString()); +Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("exceptionPolicyId").ToString()); +]]> + + + + +This sample shows how to call GetQueueAsync with required parameters and parse the result. +", credential); + +Response response = await client.GetQueueAsync("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("distributionPolicyId").ToString()); +Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("exceptionPolicyId").ToString()); +]]> + + + + +This sample shows how to call GetQueue with required parameters and parse the result. +", credential); + +Response response = client.GetQueue("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("distributionPolicyId").ToString()); +Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("exceptionPolicyId").ToString()); +]]> + + + + +This sample shows how to call DeleteQueueAsync with required parameters. +", credential); + +Response response = await client.DeleteQueueAsync(""); +Console.WriteLine(response.Status); +]]> + + + + +This sample shows how to call DeleteQueue with required parameters. +", credential); + +Response response = client.DeleteQueue(""); +Console.WriteLine(response.Status); +]]> + + + + +This sample shows how to call GetClassificationPoliciesAsync with required parameters and parse the result. +", credential); + +await foreach (var item in client.GetClassificationPoliciesAsync(1234, new RequestContext())) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("fallbackQueueId").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("queueSelectors")[0].GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("prioritizationRule").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("workerSelectors")[0].GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); +} +]]> + + + + +This sample shows how to call GetClassificationPolicies with required parameters and parse the result. +", credential); + +foreach (var item in client.GetClassificationPolicies(1234, new RequestContext())) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("fallbackQueueId").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("queueSelectors")[0].GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("prioritizationRule").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("workerSelectors")[0].GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); +} +]]> + + + + +This sample shows how to call GetDistributionPoliciesAsync with required parameters and parse the result. +", credential); + +await foreach (var item in client.GetDistributionPoliciesAsync(1234, new RequestContext())) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("offerExpiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("minConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("maxConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("bypassSelectors").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); +} +]]> + + + + +This sample shows how to call GetDistributionPolicies with required parameters and parse the result. +", credential); + +foreach (var item in client.GetDistributionPolicies(1234, new RequestContext())) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("offerExpiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("minConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("maxConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("bypassSelectors").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); +} +]]> + + + + +This sample shows how to call GetExceptionPoliciesAsync with required parameters and parse the result. +", credential); + +await foreach (var item in client.GetExceptionPoliciesAsync(1234, new RequestContext())) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("exceptionRules").GetProperty("").GetProperty("trigger").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("exceptionRules").GetProperty("").GetProperty("actions").GetProperty("").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); +} +]]> + + + + +This sample shows how to call GetExceptionPolicies with required parameters and parse the result. +", credential); + +foreach (var item in client.GetExceptionPolicies(1234, new RequestContext())) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("exceptionRules").GetProperty("").GetProperty("trigger").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("exceptionRules").GetProperty("").GetProperty("actions").GetProperty("").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); +} +]]> + + + + +This sample shows how to call GetQueuesAsync with required parameters and parse the result. +", credential); + +await foreach (var item in client.GetQueuesAsync(1234, new RequestContext())) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("queue").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("distributionPolicyId").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("exceptionPolicyId").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); +} +]]> + + + + +This sample shows how to call GetQueues with required parameters and parse the result. +", credential); + +foreach (var item in client.GetQueues(1234, new RequestContext())) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("queue").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("distributionPolicyId").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("exceptionPolicyId").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); +} +]]> + + + + \ No newline at end of file diff --git a/sdk/template/Azure.Template/src/Generated/Docs/JobRouterClient.xml b/sdk/template/Azure.Template/src/Generated/Docs/JobRouterClient.xml new file mode 100644 index 000000000000..666b766d38e5 --- /dev/null +++ b/sdk/template/Azure.Template/src/Generated/Docs/JobRouterClient.xml @@ -0,0 +1,1161 @@ + + + + + +This sample shows how to call UpsertJobAsync with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = await client.UpsertJobAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call UpsertJobAsync with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + channelReference = "", + channelId = "", + classificationPolicyId = "", + queueId = "", + priority = 1234, + dispositionCode = "", + requestedWorkerSelectors = new[] { + new { + key = "", + labelOperator = "equal", + value = new {}, + expiresAfterSeconds = 123.45d, + expedite = true, + } + }, + labels = new { + key = new {}, + }, + tags = new { + key = new {}, + }, + notes = new { + key = "", + }, + matchingMode = new { + modeType = "queueAndMatchMode", + queueAndMatchMode = new {}, + scheduleAndSuspendMode = new { + scheduleAt = "2022-05-10T18:57:31.2311892Z", + }, + suspendMode = new {}, + }, +}; + +Response response = await client.UpsertJobAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("channelReference").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("enqueuedAt").ToString()); +Console.WriteLine(result.GetProperty("channelId").ToString()); +Console.WriteLine(result.GetProperty("classificationPolicyId").ToString()); +Console.WriteLine(result.GetProperty("queueId").ToString()); +Console.WriteLine(result.GetProperty("priority").ToString()); +Console.WriteLine(result.GetProperty("dispositionCode").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("key").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("value").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expedite").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("key").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("value").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expedite").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); +Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignmentId").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("workerId").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignedAt").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("completedAt").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("closedAt").ToString()); +Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("notes").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("scheduledAt").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("modeType").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("queueAndMatchMode").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("scheduleAndSuspendMode").GetProperty("scheduleAt").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("suspendMode").ToString()); +]]> + + + + +This sample shows how to call UpsertJob with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = client.UpsertJob("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call UpsertJob with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + channelReference = "", + channelId = "", + classificationPolicyId = "", + queueId = "", + priority = 1234, + dispositionCode = "", + requestedWorkerSelectors = new[] { + new { + key = "", + labelOperator = "equal", + value = new {}, + expiresAfterSeconds = 123.45d, + expedite = true, + } + }, + labels = new { + key = new {}, + }, + tags = new { + key = new {}, + }, + notes = new { + key = "", + }, + matchingMode = new { + modeType = "queueAndMatchMode", + queueAndMatchMode = new {}, + scheduleAndSuspendMode = new { + scheduleAt = "2022-05-10T18:57:31.2311892Z", + }, + suspendMode = new {}, + }, +}; + +Response response = client.UpsertJob("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("channelReference").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("enqueuedAt").ToString()); +Console.WriteLine(result.GetProperty("channelId").ToString()); +Console.WriteLine(result.GetProperty("classificationPolicyId").ToString()); +Console.WriteLine(result.GetProperty("queueId").ToString()); +Console.WriteLine(result.GetProperty("priority").ToString()); +Console.WriteLine(result.GetProperty("dispositionCode").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("key").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("value").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expedite").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("key").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("value").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expedite").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); +Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignmentId").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("workerId").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignedAt").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("completedAt").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("closedAt").ToString()); +Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("notes").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("scheduledAt").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("modeType").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("queueAndMatchMode").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("scheduleAndSuspendMode").GetProperty("scheduleAt").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("suspendMode").ToString()); +]]> + + + + +This sample shows how to call GetJobAsync with required parameters and parse the result. +", credential); + +Response response = await client.GetJobAsync("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("channelReference").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("enqueuedAt").ToString()); +Console.WriteLine(result.GetProperty("channelId").ToString()); +Console.WriteLine(result.GetProperty("classificationPolicyId").ToString()); +Console.WriteLine(result.GetProperty("queueId").ToString()); +Console.WriteLine(result.GetProperty("priority").ToString()); +Console.WriteLine(result.GetProperty("dispositionCode").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("key").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("value").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expedite").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("key").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("value").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expedite").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); +Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignmentId").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("workerId").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignedAt").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("completedAt").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("closedAt").ToString()); +Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("notes").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("scheduledAt").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("modeType").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("queueAndMatchMode").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("scheduleAndSuspendMode").GetProperty("scheduleAt").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("suspendMode").ToString()); +]]> + + + + +This sample shows how to call GetJob with required parameters and parse the result. +", credential); + +Response response = client.GetJob("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("channelReference").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("enqueuedAt").ToString()); +Console.WriteLine(result.GetProperty("channelId").ToString()); +Console.WriteLine(result.GetProperty("classificationPolicyId").ToString()); +Console.WriteLine(result.GetProperty("queueId").ToString()); +Console.WriteLine(result.GetProperty("priority").ToString()); +Console.WriteLine(result.GetProperty("dispositionCode").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("key").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("value").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expedite").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("key").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("value").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expedite").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); +Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignmentId").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("workerId").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignedAt").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("completedAt").ToString()); +Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("closedAt").ToString()); +Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("notes").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("scheduledAt").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("modeType").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("queueAndMatchMode").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("scheduleAndSuspendMode").GetProperty("scheduleAt").ToString()); +Console.WriteLine(result.GetProperty("matchingMode").GetProperty("suspendMode").ToString()); +]]> + + + + +This sample shows how to call DeleteJobAsync with required parameters. +", credential); + +Response response = await client.DeleteJobAsync(""); +Console.WriteLine(response.Status); +]]> + + + + +This sample shows how to call DeleteJob with required parameters. +", credential); + +Response response = client.DeleteJob(""); +Console.WriteLine(response.Status); +]]> + + + + +This sample shows how to call ReclassifyJobActionAsync with required parameters and request content and parse the result. +", credential); + +var data = new {}; + +Response response = await client.ReclassifyJobActionAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + + +This sample shows how to call ReclassifyJobAction with required parameters and request content and parse the result. +", credential); + +var data = new {}; + +Response response = client.ReclassifyJobAction("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + + +This sample shows how to call CancelJobActionAsync with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = await client.CancelJobActionAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call CancelJobActionAsync with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + note = "", + dispositionCode = "", +}; + +Response response = await client.CancelJobActionAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + + +This sample shows how to call CancelJobAction with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = client.CancelJobAction("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call CancelJobAction with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + note = "", + dispositionCode = "", +}; + +Response response = client.CancelJobAction("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + + +This sample shows how to call CompleteJobActionAsync with required parameters and request content, and how to parse the result. +", credential); + +var data = new { + assignmentId = "", +}; + +Response response = await client.CompleteJobActionAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call CompleteJobActionAsync with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + assignmentId = "", + note = "", +}; + +Response response = await client.CompleteJobActionAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + + +This sample shows how to call CompleteJobAction with required parameters and request content, and how to parse the result. +", credential); + +var data = new { + assignmentId = "", +}; + +Response response = client.CompleteJobAction("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call CompleteJobAction with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + assignmentId = "", + note = "", +}; + +Response response = client.CompleteJobAction("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + + +This sample shows how to call CloseJobActionAsync with required parameters and request content, and how to parse the result. +", credential); + +var data = new { + assignmentId = "", +}; + +Response response = await client.CloseJobActionAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call CloseJobActionAsync with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + assignmentId = "", + dispositionCode = "", + closeAt = "2022-05-10T18:57:31.2311892Z", + note = "", +}; + +Response response = await client.CloseJobActionAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + + +This sample shows how to call CloseJobAction with required parameters and request content, and how to parse the result. +", credential); + +var data = new { + assignmentId = "", +}; + +Response response = client.CloseJobAction("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call CloseJobAction with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + assignmentId = "", + dispositionCode = "", + closeAt = "2022-05-10T18:57:31.2311892Z", + note = "", +}; + +Response response = client.CloseJobAction("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + + +This sample shows how to call GetInQueuePositionAsync with required parameters and parse the result. +", credential); + +Response response = await client.GetInQueuePositionAsync("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("position").ToString()); +Console.WriteLine(result.GetProperty("queueId").ToString()); +Console.WriteLine(result.GetProperty("queueLength").ToString()); +Console.WriteLine(result.GetProperty("estimatedWaitTimeMinutes").ToString()); +]]> + + + + +This sample shows how to call GetInQueuePosition with required parameters and parse the result. +", credential); + +Response response = client.GetInQueuePosition("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("position").ToString()); +Console.WriteLine(result.GetProperty("queueId").ToString()); +Console.WriteLine(result.GetProperty("queueLength").ToString()); +Console.WriteLine(result.GetProperty("estimatedWaitTimeMinutes").ToString()); +]]> + + + + +This sample shows how to call UnassignJobActionAsync with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = await client.UnassignJobActionAsync("", "", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("unassignmentCount").ToString()); +]]> +This sample shows how to call UnassignJobActionAsync with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + suspendMatching = true, +}; + +Response response = await client.UnassignJobActionAsync("", "", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("unassignmentCount").ToString()); +]]> + + + + +This sample shows how to call UnassignJobAction with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = client.UnassignJobAction("", "", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("unassignmentCount").ToString()); +]]> +This sample shows how to call UnassignJobAction with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + suspendMatching = true, +}; + +Response response = client.UnassignJobAction("", "", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("unassignmentCount").ToString()); +]]> + + + + +This sample shows how to call AcceptJobActionAsync with required parameters and parse the result. +", credential); + +Response response = await client.AcceptJobActionAsync("", "", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("assignmentId").ToString()); +Console.WriteLine(result.GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("workerId").ToString()); +]]> + + + + +This sample shows how to call AcceptJobAction with required parameters and parse the result. +", credential); + +Response response = client.AcceptJobAction("", "", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("assignmentId").ToString()); +Console.WriteLine(result.GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("workerId").ToString()); +]]> + + + + +This sample shows how to call DeclineJobActionAsync with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = await client.DeclineJobActionAsync("", "", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call DeclineJobActionAsync with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + retryOfferAt = "2022-05-10T18:57:31.2311892Z", +}; + +Response response = await client.DeclineJobActionAsync("", "", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + + +This sample shows how to call DeclineJobAction with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = client.DeclineJobAction("", "", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call DeclineJobAction with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + retryOfferAt = "2022-05-10T18:57:31.2311892Z", +}; + +Response response = client.DeclineJobAction("", "", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + + +This sample shows how to call GetQueueStatisticsAsync with required parameters and parse the result. +", credential); + +Response response = await client.GetQueueStatisticsAsync("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("queueId").ToString()); +Console.WriteLine(result.GetProperty("length").ToString()); +Console.WriteLine(result.GetProperty("estimatedWaitTimeMinutes").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("longestJobWaitTimeMinutes").ToString()); +]]> + + + + +This sample shows how to call GetQueueStatistics with required parameters and parse the result. +", credential); + +Response response = client.GetQueueStatistics("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("queueId").ToString()); +Console.WriteLine(result.GetProperty("length").ToString()); +Console.WriteLine(result.GetProperty("estimatedWaitTimeMinutes").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("longestJobWaitTimeMinutes").ToString()); +]]> + + + + +This sample shows how to call UpsertWorkerAsync with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = await client.UpsertWorkerAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call UpsertWorkerAsync with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + queueAssignments = new { + key = new {}, + }, + totalCapacity = 1234, + labels = new { + key = new {}, + }, + tags = new { + key = new {}, + }, + channelConfigurations = new { + key = new { + capacityCostPerJob = 1234, + maxNumberOfJobs = 1234, + }, + }, + availableForOffers = true, +}; + +Response response = await client.UpsertWorkerAsync("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("state").ToString()); +Console.WriteLine(result.GetProperty("queueAssignments").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("totalCapacity").ToString()); +Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("channelConfigurations").GetProperty("").GetProperty("capacityCostPerJob").ToString()); +Console.WriteLine(result.GetProperty("channelConfigurations").GetProperty("").GetProperty("maxNumberOfJobs").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("offerId").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("capacityCost").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("offeredAt").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("expiresAt").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("assignmentId").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("capacityCost").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("assignedAt").ToString()); +Console.WriteLine(result.GetProperty("loadRatio").ToString()); +Console.WriteLine(result.GetProperty("availableForOffers").ToString()); +]]> + + + + +This sample shows how to call UpsertWorker with required parameters and parse the result. +", credential); + +var data = new {}; + +Response response = client.UpsertWorker("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call UpsertWorker with all parameters and request content, and how to parse the result. +", credential); + +var data = new { + queueAssignments = new { + key = new {}, + }, + totalCapacity = 1234, + labels = new { + key = new {}, + }, + tags = new { + key = new {}, + }, + channelConfigurations = new { + key = new { + capacityCostPerJob = 1234, + maxNumberOfJobs = 1234, + }, + }, + availableForOffers = true, +}; + +Response response = client.UpsertWorker("", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("state").ToString()); +Console.WriteLine(result.GetProperty("queueAssignments").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("totalCapacity").ToString()); +Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("channelConfigurations").GetProperty("").GetProperty("capacityCostPerJob").ToString()); +Console.WriteLine(result.GetProperty("channelConfigurations").GetProperty("").GetProperty("maxNumberOfJobs").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("offerId").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("capacityCost").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("offeredAt").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("expiresAt").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("assignmentId").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("capacityCost").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("assignedAt").ToString()); +Console.WriteLine(result.GetProperty("loadRatio").ToString()); +Console.WriteLine(result.GetProperty("availableForOffers").ToString()); +]]> + + + + +This sample shows how to call GetWorkerAsync with required parameters and parse the result. +", credential); + +Response response = await client.GetWorkerAsync("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("state").ToString()); +Console.WriteLine(result.GetProperty("queueAssignments").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("totalCapacity").ToString()); +Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("channelConfigurations").GetProperty("").GetProperty("capacityCostPerJob").ToString()); +Console.WriteLine(result.GetProperty("channelConfigurations").GetProperty("").GetProperty("maxNumberOfJobs").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("offerId").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("capacityCost").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("offeredAt").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("expiresAt").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("assignmentId").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("capacityCost").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("assignedAt").ToString()); +Console.WriteLine(result.GetProperty("loadRatio").ToString()); +Console.WriteLine(result.GetProperty("availableForOffers").ToString()); +]]> + + + + +This sample shows how to call GetWorker with required parameters and parse the result. +", credential); + +Response response = client.GetWorker("", new RequestContext()); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("state").ToString()); +Console.WriteLine(result.GetProperty("queueAssignments").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("totalCapacity").ToString()); +Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); +Console.WriteLine(result.GetProperty("channelConfigurations").GetProperty("").GetProperty("capacityCostPerJob").ToString()); +Console.WriteLine(result.GetProperty("channelConfigurations").GetProperty("").GetProperty("maxNumberOfJobs").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("offerId").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("capacityCost").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("offeredAt").ToString()); +Console.WriteLine(result.GetProperty("offers")[0].GetProperty("expiresAt").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("assignmentId").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("jobId").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("capacityCost").ToString()); +Console.WriteLine(result.GetProperty("assignedJobs")[0].GetProperty("assignedAt").ToString()); +Console.WriteLine(result.GetProperty("loadRatio").ToString()); +Console.WriteLine(result.GetProperty("availableForOffers").ToString()); +]]> + + + + +This sample shows how to call DeleteWorkerAsync with required parameters. +", credential); + +Response response = await client.DeleteWorkerAsync(""); +Console.WriteLine(response.Status); +]]> + + + + +This sample shows how to call DeleteWorker with required parameters. +", credential); + +Response response = client.DeleteWorker(""); +Console.WriteLine(response.Status); +]]> + + + + +This sample shows how to call GetJobsAsync with required parameters and parse the result. +", credential); + +await foreach (var item in client.GetJobsAsync("", "", "", "", DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, 1234, new RequestContext())) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("job").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("channelReference").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("enqueuedAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("channelId").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("classificationPolicyId").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("queueId").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("priority").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("dispositionCode").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("key").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("expedite").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("key").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("expedite").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("assignments").GetProperty("").GetProperty("assignmentId").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("assignments").GetProperty("").GetProperty("workerId").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("assignments").GetProperty("").GetProperty("assignedAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("assignments").GetProperty("").GetProperty("completedAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("assignments").GetProperty("").GetProperty("closedAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("tags").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("notes").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("scheduledAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("matchingMode").GetProperty("modeType").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("matchingMode").GetProperty("queueAndMatchMode").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("matchingMode").GetProperty("scheduleAndSuspendMode").GetProperty("scheduleAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("matchingMode").GetProperty("suspendMode").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); +} +]]> + + + + +This sample shows how to call GetJobs with required parameters and parse the result. +", credential); + +foreach (var item in client.GetJobs("", "", "", "", DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, 1234, new RequestContext())) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("job").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("channelReference").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("enqueuedAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("channelId").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("classificationPolicyId").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("queueId").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("priority").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("dispositionCode").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("key").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("expedite").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("key").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("expedite").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("assignments").GetProperty("").GetProperty("assignmentId").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("assignments").GetProperty("").GetProperty("workerId").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("assignments").GetProperty("").GetProperty("assignedAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("assignments").GetProperty("").GetProperty("completedAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("assignments").GetProperty("").GetProperty("closedAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("tags").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("notes").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("scheduledAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("matchingMode").GetProperty("modeType").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("matchingMode").GetProperty("queueAndMatchMode").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("matchingMode").GetProperty("scheduleAndSuspendMode").GetProperty("scheduleAt").ToString()); + Console.WriteLine(result.GetProperty("job").GetProperty("matchingMode").GetProperty("suspendMode").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); +} +]]> + + + + +This sample shows how to call GetWorkersAsync with required parameters and parse the result. +", credential); + +await foreach (var item in client.GetWorkersAsync("", "", "", true, 1234, new RequestContext())) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("worker").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("state").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("queueAssignments").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("totalCapacity").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("tags").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("channelConfigurations").GetProperty("").GetProperty("capacityCostPerJob").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("channelConfigurations").GetProperty("").GetProperty("maxNumberOfJobs").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("offers")[0].GetProperty("offerId").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("offers")[0].GetProperty("jobId").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("offers")[0].GetProperty("capacityCost").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("offers")[0].GetProperty("offeredAt").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("offers")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("assignedJobs")[0].GetProperty("assignmentId").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("assignedJobs")[0].GetProperty("jobId").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("assignedJobs")[0].GetProperty("capacityCost").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("assignedJobs")[0].GetProperty("assignedAt").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("loadRatio").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("availableForOffers").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); +} +]]> + + + + +This sample shows how to call GetWorkers with required parameters and parse the result. +", credential); + +foreach (var item in client.GetWorkers("", "", "", true, 1234, new RequestContext())) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("worker").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("state").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("queueAssignments").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("totalCapacity").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("tags").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("channelConfigurations").GetProperty("").GetProperty("capacityCostPerJob").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("channelConfigurations").GetProperty("").GetProperty("maxNumberOfJobs").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("offers")[0].GetProperty("offerId").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("offers")[0].GetProperty("jobId").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("offers")[0].GetProperty("capacityCost").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("offers")[0].GetProperty("offeredAt").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("offers")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("assignedJobs")[0].GetProperty("assignmentId").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("assignedJobs")[0].GetProperty("jobId").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("assignedJobs")[0].GetProperty("capacityCost").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("assignedJobs")[0].GetProperty("assignedAt").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("loadRatio").ToString()); + Console.WriteLine(result.GetProperty("worker").GetProperty("availableForOffers").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); +} +]]> + + + + \ No newline at end of file diff --git a/sdk/template/Azure.Template/src/Generated/Docs/TemplateClient.xml b/sdk/template/Azure.Template/src/Generated/Docs/TemplateClient.xml deleted file mode 100644 index 493ff8f5e819..000000000000 --- a/sdk/template/Azure.Template/src/Generated/Docs/TemplateClient.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - -This sample shows how to call GetSecretAsync with required parameters and parse the result. -", credential); - -Response response = await client.GetSecretAsync("", new RequestContext()); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result.GetProperty("value").ToString()); -Console.WriteLine(result.GetProperty("id").ToString()); -Console.WriteLine(result.GetProperty("contentType").ToString()); -Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); -Console.WriteLine(result.GetProperty("kid").ToString()); -Console.WriteLine(result.GetProperty("managed").ToString()); -]]> - - - - -This sample shows how to call GetSecret with required parameters and parse the result. -", credential); - -Response response = client.GetSecret("", new RequestContext()); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result.GetProperty("value").ToString()); -Console.WriteLine(result.GetProperty("id").ToString()); -Console.WriteLine(result.GetProperty("contentType").ToString()); -Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); -Console.WriteLine(result.GetProperty("kid").ToString()); -Console.WriteLine(result.GetProperty("managed").ToString()); -]]> - - - - \ No newline at end of file diff --git a/sdk/template/Azure.Template/src/Generated/JobRouterAdministrationClient.cs b/sdk/template/Azure.Template/src/Generated/JobRouterAdministrationClient.cs new file mode 100644 index 000000000000..7b202453fd61 --- /dev/null +++ b/sdk/template/Azure.Template/src/Generated/JobRouterAdministrationClient.cs @@ -0,0 +1,1414 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.Communication.JobRouter +{ + // Data plane generated client. + /// The JobRouterAdministration service client. + public partial class JobRouterAdministrationClient + { + private static readonly string[] AuthorizationScopes = new string[] { "https://example.azure.net/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly string _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of JobRouterAdministrationClient for mocking. + protected JobRouterAdministrationClient() + { + } + + /// Initializes a new instance of JobRouterAdministrationClient. + /// The endpoint of the Azure Communication resource. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public JobRouterAdministrationClient(string endpoint, TokenCredential credential) : this(endpoint, credential, new AzureCommunicationServicesClientOptions()) + { + } + + /// Initializes a new instance of JobRouterAdministrationClient. + /// The endpoint of the Azure Communication resource. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public JobRouterAdministrationClient(string endpoint, TokenCredential credential, AzureCommunicationServicesClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new AzureCommunicationServicesClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// + /// [Protocol Method] Creates or updates a classification policy. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the classification policy. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task UpsertClassificationPolicyAsync(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.UpsertClassificationPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateUpsertClassificationPolicyRequest(id, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates a classification policy. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the classification policy. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response UpsertClassificationPolicy(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.UpsertClassificationPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateUpsertClassificationPolicyRequest(id, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves an existing classification policy by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the classification policy. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetClassificationPolicyAsync(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.GetClassificationPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateGetClassificationPolicyRequest(id, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves an existing classification policy by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the classification policy. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetClassificationPolicy(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.GetClassificationPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateGetClassificationPolicyRequest(id, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Delete a classification policy by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the classification policy. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteClassificationPolicyAsync(string id, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.DeleteClassificationPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteClassificationPolicyRequest(id, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Delete a classification policy by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the classification policy. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response DeleteClassificationPolicy(string id, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.DeleteClassificationPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteClassificationPolicyRequest(id, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates a distribution policy. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the distribution policy. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task UpsertDistributionPolicyAsync(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.UpsertDistributionPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateUpsertDistributionPolicyRequest(id, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates a distribution policy. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the distribution policy. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response UpsertDistributionPolicy(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.UpsertDistributionPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateUpsertDistributionPolicyRequest(id, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves an existing distribution policy by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the distribution policy. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetDistributionPolicyAsync(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.GetDistributionPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateGetDistributionPolicyRequest(id, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves an existing distribution policy by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the distribution policy. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetDistributionPolicy(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.GetDistributionPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateGetDistributionPolicyRequest(id, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Delete a distribution policy by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the distribution policy. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteDistributionPolicyAsync(string id, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.DeleteDistributionPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteDistributionPolicyRequest(id, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Delete a distribution policy by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the distribution policy. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response DeleteDistributionPolicy(string id, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.DeleteDistributionPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteDistributionPolicyRequest(id, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates a exception policy. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the exception policy. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task UpsertExceptionPolicyAsync(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.UpsertExceptionPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateUpsertExceptionPolicyRequest(id, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates a exception policy. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the exception policy. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response UpsertExceptionPolicy(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.UpsertExceptionPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateUpsertExceptionPolicyRequest(id, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves an existing exception policy by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the exception policy to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetExceptionPolicyAsync(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.GetExceptionPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateGetExceptionPolicyRequest(id, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves an existing exception policy by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the exception policy to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetExceptionPolicy(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.GetExceptionPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateGetExceptionPolicyRequest(id, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Deletes a exception policy by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the exception policy to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteExceptionPolicyAsync(string id, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.DeleteExceptionPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteExceptionPolicyRequest(id, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Deletes a exception policy by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the exception policy to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response DeleteExceptionPolicy(string id, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.DeleteExceptionPolicy"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteExceptionPolicyRequest(id, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates a queue. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the queue. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task UpsertQueueAsync(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.UpsertQueue"); + scope.Start(); + try + { + using HttpMessage message = CreateUpsertQueueRequest(id, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates a queue. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the queue. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response UpsertQueue(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.UpsertQueue"); + scope.Start(); + try + { + using HttpMessage message = CreateUpsertQueueRequest(id, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves an existing queue by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the queue to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetQueueAsync(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.GetQueue"); + scope.Start(); + try + { + using HttpMessage message = CreateGetQueueRequest(id, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves an existing queue by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the queue to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetQueue(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.GetQueue"); + scope.Start(); + try + { + using HttpMessage message = CreateGetQueueRequest(id, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Deletes a queue by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the queue to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteQueueAsync(string id, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.DeleteQueue"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteQueueRequest(id, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Deletes a queue by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the queue to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response DeleteQueue(string id, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterAdministrationClient.DeleteQueue"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteQueueRequest(id, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves existing classification policies + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Maximum page size. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetClassificationPoliciesAsync(int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetClassificationPoliciesRequest(maxpagesize, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetClassificationPoliciesNextPageRequest(nextLink, maxpagesize, context); + return PageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "JobRouterAdministrationClient.GetClassificationPolicies", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Retrieves existing classification policies + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Maximum page size. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetClassificationPolicies(int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetClassificationPoliciesRequest(maxpagesize, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetClassificationPoliciesNextPageRequest(nextLink, maxpagesize, context); + return PageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "JobRouterAdministrationClient.GetClassificationPolicies", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Retrieves existing distribution policies + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Maximum page size. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetDistributionPoliciesAsync(int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetDistributionPoliciesRequest(maxpagesize, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetDistributionPoliciesNextPageRequest(nextLink, maxpagesize, context); + return PageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "JobRouterAdministrationClient.GetDistributionPolicies", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Retrieves existing distribution policies + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Maximum page size. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetDistributionPolicies(int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetDistributionPoliciesRequest(maxpagesize, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetDistributionPoliciesNextPageRequest(nextLink, maxpagesize, context); + return PageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "JobRouterAdministrationClient.GetDistributionPolicies", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Retrieves existing exception policies + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Number of objects to return per page. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetExceptionPoliciesAsync(int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetExceptionPoliciesRequest(maxpagesize, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetExceptionPoliciesNextPageRequest(nextLink, maxpagesize, context); + return PageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "JobRouterAdministrationClient.GetExceptionPolicies", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Retrieves existing exception policies + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Number of objects to return per page. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetExceptionPolicies(int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetExceptionPoliciesRequest(maxpagesize, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetExceptionPoliciesNextPageRequest(nextLink, maxpagesize, context); + return PageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "JobRouterAdministrationClient.GetExceptionPolicies", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Retrieves existing queues + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Number of objects to return per page. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetQueuesAsync(int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetQueuesRequest(maxpagesize, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetQueuesNextPageRequest(nextLink, maxpagesize, context); + return PageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "JobRouterAdministrationClient.GetQueues", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Retrieves existing queues + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Number of objects to return per page. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetQueues(int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetQueuesRequest(maxpagesize, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetQueuesNextPageRequest(nextLink, maxpagesize, context); + return PageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "JobRouterAdministrationClient.GetQueues", "value", "nextLink", context); + } + + internal HttpMessage CreateUpsertClassificationPolicyRequest(string id, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Patch; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/classificationPolicies/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/merge-patch+json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetClassificationPolicyRequest(string id, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/classificationPolicies/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateDeleteClassificationPolicyRequest(string id, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/classificationPolicies/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetClassificationPoliciesRequest(int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/classificationPolicies", false); + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateUpsertDistributionPolicyRequest(string id, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Patch; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/distributionPolicies/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/merge-patch+json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetDistributionPolicyRequest(string id, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/distributionPolicies/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateDeleteDistributionPolicyRequest(string id, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/distributionPolicies/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetDistributionPoliciesRequest(int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/distributionPolicies", false); + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateUpsertExceptionPolicyRequest(string id, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Patch; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/exceptionPolicies/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/merge-patch+json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetExceptionPolicyRequest(string id, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/exceptionPolicies/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateDeleteExceptionPolicyRequest(string id, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/exceptionPolicies/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetExceptionPoliciesRequest(int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/exceptionPolicies", false); + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateUpsertQueueRequest(string id, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Patch; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/queues/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/merge-patch+json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetQueueRequest(string id, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/queues/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateDeleteQueueRequest(string id, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/queues/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetQueuesRequest(int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/queues", false); + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetClassificationPoliciesNextPageRequest(string nextLink, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetDistributionPoliciesNextPageRequest(string nextLink, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetExceptionPoliciesNextPageRequest(string nextLink, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetQueuesNextPageRequest(string nextLink, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + private static ResponseClassifier _responseClassifier200201; + private static ResponseClassifier ResponseClassifier200201 => _responseClassifier200201 ??= new StatusCodeClassifier(stackalloc ushort[] { 200, 201 }); + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + private static ResponseClassifier _responseClassifier204; + private static ResponseClassifier ResponseClassifier204 => _responseClassifier204 ??= new StatusCodeClassifier(stackalloc ushort[] { 204 }); + } +} diff --git a/sdk/template/Azure.Template/src/Generated/JobRouterClient.cs b/sdk/template/Azure.Template/src/Generated/JobRouterClient.cs new file mode 100644 index 000000000000..065571061935 --- /dev/null +++ b/sdk/template/Azure.Template/src/Generated/JobRouterClient.cs @@ -0,0 +1,1630 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.Communication.JobRouter +{ + // Data plane generated client. + /// The JobRouter service client. + public partial class JobRouterClient + { + private static readonly string[] AuthorizationScopes = new string[] { "https://example.azure.net/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly string _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of JobRouterClient for mocking. + protected JobRouterClient() + { + } + + /// Initializes a new instance of JobRouterClient. + /// The endpoint of the Azure Communication resource. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public JobRouterClient(string endpoint, TokenCredential credential) : this(endpoint, credential, new AzureCommunicationServicesClientOptions()) + { + } + + /// Initializes a new instance of JobRouterClient. + /// The endpoint of the Azure Communication resource. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public JobRouterClient(string endpoint, TokenCredential credential, AzureCommunicationServicesClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new AzureCommunicationServicesClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// + /// [Protocol Method] Creates or updates a router job. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task UpsertJobAsync(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.UpsertJob"); + scope.Start(); + try + { + using HttpMessage message = CreateUpsertJobRequest(id, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates a router job. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response UpsertJob(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.UpsertJob"); + scope.Start(); + try + { + using HttpMessage message = CreateUpsertJobRequest(id, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves an existing job by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetJobAsync(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.GetJob"); + scope.Start(); + try + { + using HttpMessage message = CreateGetJobRequest(id, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves an existing job by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetJob(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.GetJob"); + scope.Start(); + try + { + using HttpMessage message = CreateGetJobRequest(id, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Deletes a job and all of its traces. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteJobAsync(string id, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.DeleteJob"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteJobRequest(id, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Deletes a job and all of its traces. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response DeleteJob(string id, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.DeleteJob"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteJobRequest(id, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Reclassify a job. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task ReclassifyJobActionAsync(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.ReclassifyJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateReclassifyJobActionRequest(id, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Reclassify a job. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response ReclassifyJobAction(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.ReclassifyJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateReclassifyJobActionRequest(id, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Submits request to cancel an existing job by Id while supplying free-form cancellation reason. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task CancelJobActionAsync(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.CancelJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelJobActionRequest(id, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Submits request to cancel an existing job by Id while supplying free-form cancellation reason. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response CancelJobAction(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.CancelJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelJobActionRequest(id, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Completes an assigned job. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task CompleteJobActionAsync(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.CompleteJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateCompleteJobActionRequest(id, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Completes an assigned job. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response CompleteJobAction(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.CompleteJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateCompleteJobActionRequest(id, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Closes a completed job. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task CloseJobActionAsync(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.CloseJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateCloseJobActionRequest(id, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Closes a completed job. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response CloseJobAction(string id, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.CloseJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateCloseJobActionRequest(id, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets a job's position details. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetInQueuePositionAsync(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.GetInQueuePosition"); + scope.Start(); + try + { + using HttpMessage message = CreateGetInQueuePositionRequest(id, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets a job's position details. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetInQueuePosition(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.GetInQueuePosition"); + scope.Start(); + try + { + using HttpMessage message = CreateGetInQueuePositionRequest(id, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Un-assign a job. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job to un-assign. + /// Id of the assignment to un-assign. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task UnassignJobActionAsync(string id, string assignmentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNullOrEmpty(assignmentId, nameof(assignmentId)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.UnassignJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateUnassignJobActionRequest(id, assignmentId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Un-assign a job. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the job to un-assign. + /// Id of the assignment to un-assign. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response UnassignJobAction(string id, string assignmentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + Argument.AssertNotNullOrEmpty(assignmentId, nameof(assignmentId)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.UnassignJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateUnassignJobActionRequest(id, assignmentId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Accepts an offer to work on a job and returns a 409/Conflict if another agent accepted the job already. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the worker. + /// Id of the offer. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task AcceptJobActionAsync(string workerId, string offerId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(workerId, nameof(workerId)); + Argument.AssertNotNullOrEmpty(offerId, nameof(offerId)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.AcceptJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateAcceptJobActionRequest(workerId, offerId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Accepts an offer to work on a job and returns a 409/Conflict if another agent accepted the job already. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the worker. + /// Id of the offer. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response AcceptJobAction(string workerId, string offerId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(workerId, nameof(workerId)); + Argument.AssertNotNullOrEmpty(offerId, nameof(offerId)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.AcceptJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateAcceptJobActionRequest(workerId, offerId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Declines an offer to work on a job. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the worker. + /// Id of the offer. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeclineJobActionAsync(string workerId, string offerId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(workerId, nameof(workerId)); + Argument.AssertNotNullOrEmpty(offerId, nameof(offerId)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.DeclineJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateDeclineJobActionRequest(workerId, offerId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Declines an offer to work on a job. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the worker. + /// Id of the offer. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response DeclineJobAction(string workerId, string offerId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(workerId, nameof(workerId)); + Argument.AssertNotNullOrEmpty(offerId, nameof(offerId)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.DeclineJobAction"); + scope.Start(); + try + { + using HttpMessage message = CreateDeclineJobActionRequest(workerId, offerId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves a queue's statistics + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the queue to retrieve statistics. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetQueueStatisticsAsync(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.GetQueueStatistics"); + scope.Start(); + try + { + using HttpMessage message = CreateGetQueueStatisticsRequest(id, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves a queue's statistics + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the queue to retrieve statistics. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetQueueStatistics(string id, RequestContext context) + { + Argument.AssertNotNullOrEmpty(id, nameof(id)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.GetQueueStatistics"); + scope.Start(); + try + { + using HttpMessage message = CreateGetQueueStatisticsRequest(id, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates a worker. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the worker. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task UpsertWorkerAsync(string workerId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(workerId, nameof(workerId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.UpsertWorker"); + scope.Start(); + try + { + using HttpMessage message = CreateUpsertWorkerRequest(workerId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates a worker. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the worker. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response UpsertWorker(string workerId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(workerId, nameof(workerId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.UpsertWorker"); + scope.Start(); + try + { + using HttpMessage message = CreateUpsertWorkerRequest(workerId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves an existing worker by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the worker to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetWorkerAsync(string workerId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(workerId, nameof(workerId)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.GetWorker"); + scope.Start(); + try + { + using HttpMessage message = CreateGetWorkerRequest(workerId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves an existing worker by Id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the worker to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetWorker(string workerId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(workerId, nameof(workerId)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.GetWorker"); + scope.Start(); + try + { + using HttpMessage message = CreateGetWorkerRequest(workerId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Deletes a worker and all of its traces. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the worker to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteWorkerAsync(string workerId, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(workerId, nameof(workerId)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.DeleteWorker"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteWorkerRequest(workerId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Deletes a worker and all of its traces. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Id of the worker to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response DeleteWorker(string workerId, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(workerId, nameof(workerId)); + + using var scope = ClientDiagnostics.CreateScope("JobRouterClient.DeleteWorker"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteWorkerRequest(workerId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves list of jobs based on filter parameters + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// If specified, filter jobs by status. Allowed values: "all" | "pendingClassification" | "queued" | "assigned" | "completed" | "closed" | "cancelled" | "classificationFailed" | "created" | "pendingSchedule" | "scheduled" | "scheduleFailed" | "waitingForActivation" | "active". + /// If specified, filter jobs by queue. + /// If specified, filter jobs by channel. + /// If specified, filter jobs by classificationPolicy. + /// If specified, filter on jobs that was scheduled before or at given timestamp. Range: (-Inf, scheduledBefore]. + /// If specified, filter on jobs that was scheduled at or after given value. Range: [scheduledAfter, +Inf). + /// Number of objects to return per page. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetJobsAsync(string status, string queueId, string channelId, string classificationPolicyId, DateTimeOffset? scheduledBefore, DateTimeOffset? scheduledAfter, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetJobsRequest(status, queueId, channelId, classificationPolicyId, scheduledBefore, scheduledAfter, maxpagesize, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetJobsNextPageRequest(nextLink, status, queueId, channelId, classificationPolicyId, scheduledBefore, scheduledAfter, maxpagesize, context); + return PageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "JobRouterClient.GetJobs", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Retrieves list of jobs based on filter parameters + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// If specified, filter jobs by status. Allowed values: "all" | "pendingClassification" | "queued" | "assigned" | "completed" | "closed" | "cancelled" | "classificationFailed" | "created" | "pendingSchedule" | "scheduled" | "scheduleFailed" | "waitingForActivation" | "active". + /// If specified, filter jobs by queue. + /// If specified, filter jobs by channel. + /// If specified, filter jobs by classificationPolicy. + /// If specified, filter on jobs that was scheduled before or at given timestamp. Range: (-Inf, scheduledBefore]. + /// If specified, filter on jobs that was scheduled at or after given value. Range: [scheduledAfter, +Inf). + /// Number of objects to return per page. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetJobs(string status, string queueId, string channelId, string classificationPolicyId, DateTimeOffset? scheduledBefore, DateTimeOffset? scheduledAfter, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetJobsRequest(status, queueId, channelId, classificationPolicyId, scheduledBefore, scheduledAfter, maxpagesize, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetJobsNextPageRequest(nextLink, status, queueId, channelId, classificationPolicyId, scheduledBefore, scheduledAfter, maxpagesize, context); + return PageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "JobRouterClient.GetJobs", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Retrieves existing workers. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// If specified, select workers by worker state. Allowed values: "active" | "draining" | "inactive" | "all". + /// If specified, select workers who have a channel configuration with this channel. + /// If specified, select workers who are assigned to this queue. + /// + /// If set to true, select only workers who have capacity for the channel specified by `channelId` or for any channel + /// if `channelId` not specified. If set to false, then will return all workers including workers without any capacity for jobs. Defaults to false. + /// + /// Number of objects to return per page. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetWorkersAsync(string state, string channelId, string queueId, bool? hasCapacity, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetWorkersRequest(state, channelId, queueId, hasCapacity, maxpagesize, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetWorkersNextPageRequest(nextLink, state, channelId, queueId, hasCapacity, maxpagesize, context); + return PageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "JobRouterClient.GetWorkers", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Retrieves existing workers. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// If specified, select workers by worker state. Allowed values: "active" | "draining" | "inactive" | "all". + /// If specified, select workers who have a channel configuration with this channel. + /// If specified, select workers who are assigned to this queue. + /// + /// If set to true, select only workers who have capacity for the channel specified by `channelId` or for any channel + /// if `channelId` not specified. If set to false, then will return all workers including workers without any capacity for jobs. Defaults to false. + /// + /// Number of objects to return per page. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetWorkers(string state, string channelId, string queueId, bool? hasCapacity, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetWorkersRequest(state, channelId, queueId, hasCapacity, maxpagesize, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetWorkersNextPageRequest(nextLink, state, channelId, queueId, hasCapacity, maxpagesize, context); + return PageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "JobRouterClient.GetWorkers", "value", "nextLink", context); + } + + internal HttpMessage CreateUpsertJobRequest(string id, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Patch; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/jobs/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/merge-patch+json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetJobRequest(string id, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/jobs/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateDeleteJobRequest(string id, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/jobs/", false); + uri.AppendPath(id, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateReclassifyJobActionRequest(string id, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/jobs/", false); + uri.AppendPath(id, true); + uri.AppendPath(":reclassify", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateCancelJobActionRequest(string id, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/jobs/", false); + uri.AppendPath(id, true); + uri.AppendPath(":cancel", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateCompleteJobActionRequest(string id, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/jobs/", false); + uri.AppendPath(id, true); + uri.AppendPath(":complete", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateCloseJobActionRequest(string id, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200202); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/jobs/", false); + uri.AppendPath(id, true); + uri.AppendPath(":close", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetJobsRequest(string status, string queueId, string channelId, string classificationPolicyId, DateTimeOffset? scheduledBefore, DateTimeOffset? scheduledAfter, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/jobs", false); + if (status != null) + { + uri.AppendQuery("status", status, true); + } + if (queueId != null) + { + uri.AppendQuery("queueId", queueId, true); + } + if (channelId != null) + { + uri.AppendQuery("channelId", channelId, true); + } + if (classificationPolicyId != null) + { + uri.AppendQuery("classificationPolicyId", classificationPolicyId, true); + } + if (scheduledBefore != null) + { + uri.AppendQuery("scheduledBefore", scheduledBefore.Value, "O", true); + } + if (scheduledAfter != null) + { + uri.AppendQuery("scheduledAfter", scheduledAfter.Value, "O", true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetInQueuePositionRequest(string id, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/jobs/", false); + uri.AppendPath(id, true); + uri.AppendPath("/position", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateUnassignJobActionRequest(string id, string assignmentId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/jobs/", false); + uri.AppendPath(id, true); + uri.AppendPath("/assignments/", false); + uri.AppendPath(assignmentId, true); + uri.AppendPath(":unassign", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateAcceptJobActionRequest(string workerId, string offerId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/workers/", false); + uri.AppendPath(workerId, true); + uri.AppendPath("/offers/", false); + uri.AppendPath(offerId, true); + uri.AppendPath(":accept", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateDeclineJobActionRequest(string workerId, string offerId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/workers/", false); + uri.AppendPath(workerId, true); + uri.AppendPath("/offers/", false); + uri.AppendPath(offerId, true); + uri.AppendPath(":decline", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetQueueStatisticsRequest(string id, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/queues/", false); + uri.AppendPath(id, true); + uri.AppendPath("/statistics", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateUpsertWorkerRequest(string workerId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Patch; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/workers/", false); + uri.AppendPath(workerId, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/merge-patch+json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetWorkerRequest(string workerId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/workers/", false); + uri.AppendPath(workerId, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateDeleteWorkerRequest(string workerId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/workers/", false); + uri.AppendPath(workerId, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetWorkersRequest(string state, string channelId, string queueId, bool? hasCapacity, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendPath("/routing/workers", false); + if (state != null) + { + uri.AppendQuery("state", state, true); + } + if (channelId != null) + { + uri.AppendQuery("channelId", channelId, true); + } + if (queueId != null) + { + uri.AppendQuery("queueId", queueId, true); + } + if (hasCapacity != null) + { + uri.AppendQuery("hasCapacity", hasCapacity.Value, true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetJobsNextPageRequest(string nextLink, string status, string queueId, string channelId, string classificationPolicyId, DateTimeOffset? scheduledBefore, DateTimeOffset? scheduledAfter, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetWorkersNextPageRequest(string nextLink, string state, string channelId, string queueId, bool? hasCapacity, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.AppendRaw(_endpoint, false); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + private static ResponseClassifier _responseClassifier200201; + private static ResponseClassifier ResponseClassifier200201 => _responseClassifier200201 ??= new StatusCodeClassifier(stackalloc ushort[] { 200, 201 }); + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + private static ResponseClassifier _responseClassifier204; + private static ResponseClassifier ResponseClassifier204 => _responseClassifier204 ??= new StatusCodeClassifier(stackalloc ushort[] { 204 }); + private static ResponseClassifier _responseClassifier200202; + private static ResponseClassifier ResponseClassifier200202 => _responseClassifier200202 ??= new StatusCodeClassifier(stackalloc ushort[] { 200, 202 }); + } +} diff --git a/sdk/template/Azure.Template/src/Generated/TemplateClient.cs b/sdk/template/Azure.Template/src/Generated/TemplateClient.cs deleted file mode 100644 index 015b41c55f16..000000000000 --- a/sdk/template/Azure.Template/src/Generated/TemplateClient.cs +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Threading.Tasks; -using Azure; -using Azure.Core; -using Azure.Core.Pipeline; - -namespace Azure.Template -{ - // Data plane generated client. - /// The Template service client. - public partial class TemplateClient - { - private static readonly string[] AuthorizationScopes = new string[] { "https://vault.azure.net/.default" }; - private readonly TokenCredential _tokenCredential; - private readonly HttpPipeline _pipeline; - private readonly string _vaultBaseUrl; - private readonly string _apiVersion; - - /// The ClientDiagnostics is used to provide tracing support for the client library. - internal ClientDiagnostics ClientDiagnostics { get; } - - /// The HTTP pipeline for sending and receiving REST requests and responses. - public virtual HttpPipeline Pipeline => _pipeline; - - /// Initializes a new instance of TemplateClient for mocking. - protected TemplateClient() - { - } - - /// Initializes a new instance of TemplateClient. - /// The vault name, for example https://myvault.vault.azure.net. - /// A credential used to authenticate to an Azure Service. - /// or is null. - public TemplateClient(string vaultBaseUrl, TokenCredential credential) : this(vaultBaseUrl, credential, new TemplateClientOptions()) - { - } - - /// Initializes a new instance of TemplateClient. - /// The vault name, for example https://myvault.vault.azure.net. - /// A credential used to authenticate to an Azure Service. - /// The options for configuring the client. - /// or is null. - public TemplateClient(string vaultBaseUrl, TokenCredential credential, TemplateClientOptions options) - { - Argument.AssertNotNull(vaultBaseUrl, nameof(vaultBaseUrl)); - Argument.AssertNotNull(credential, nameof(credential)); - options ??= new TemplateClientOptions(); - - ClientDiagnostics = new ClientDiagnostics(options, true); - _tokenCredential = credential; - _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); - _vaultBaseUrl = vaultBaseUrl; - _apiVersion = options.Version; - } - - /// - /// [Protocol Method] Get a specified secret from a given key vault. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// The name of the secret. - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// Service returned a non-success status code. - /// The response returned from the service. - /// - public virtual async Task GetSecretAsync(string secretName, RequestContext context) - { - Argument.AssertNotNullOrEmpty(secretName, nameof(secretName)); - - using var scope = ClientDiagnostics.CreateScope("TemplateClient.GetSecret"); - scope.Start(); - try - { - using HttpMessage message = CreateGetSecretRequest(secretName, context); - return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// [Protocol Method] Get a specified secret from a given key vault. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// The name of the secret. - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// Service returned a non-success status code. - /// The response returned from the service. - /// - public virtual Response GetSecret(string secretName, RequestContext context) - { - Argument.AssertNotNullOrEmpty(secretName, nameof(secretName)); - - using var scope = ClientDiagnostics.CreateScope("TemplateClient.GetSecret"); - scope.Start(); - try - { - using HttpMessage message = CreateGetSecretRequest(secretName, context); - return _pipeline.ProcessMessage(message, context); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - internal HttpMessage CreateGetSecretRequest(string secretName, RequestContext context) - { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.AppendRaw(_vaultBaseUrl, false); - uri.AppendPath("/secrets/", false); - uri.AppendPath(secretName, true); - uri.AppendQuery("api-version", _apiVersion, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; - } - - private static ResponseClassifier _responseClassifier200; - private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); - } -} diff --git a/sdk/template/Azure.Template/src/Generated/TemplateClientBuilderExtensions.cs b/sdk/template/Azure.Template/src/Generated/TemplateClientBuilderExtensions.cs deleted file mode 100644 index 426cfb23e1d4..000000000000 --- a/sdk/template/Azure.Template/src/Generated/TemplateClientBuilderExtensions.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using Azure.Core.Extensions; -using Azure.Template; - -namespace Microsoft.Extensions.Azure -{ - /// Extension methods to add to client builder. - public static partial class TemplateClientBuilderExtensions - { - /// Registers a instance. - /// The builder to register with. - /// The vault name, for example https://myvault.vault.azure.net. - public static IAzureClientBuilder AddTemplateClient(this TBuilder builder, string vaultBaseUrl) - where TBuilder : IAzureClientFactoryBuilderWithCredential - { - return builder.RegisterClientFactory((options, cred) => new TemplateClient(vaultBaseUrl, cred, options)); - } - - /// Registers a instance. - /// The builder to register with. - /// The configuration values. - public static IAzureClientBuilder AddTemplateClient(this TBuilder builder, TConfiguration configuration) - where TBuilder : IAzureClientFactoryBuilderWithConfiguration - { - return builder.RegisterClientFactory(configuration); - } - } -} diff --git a/sdk/template/Azure.Template/src/Generated/TemplateClientOptions.cs b/sdk/template/Azure.Template/src/Generated/TemplateClientOptions.cs deleted file mode 100644 index 8e50363f92a8..000000000000 --- a/sdk/template/Azure.Template/src/Generated/TemplateClientOptions.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using Azure.Core; - -namespace Azure.Template -{ - /// Client options for TemplateClient. - public partial class TemplateClientOptions : ClientOptions - { - private const ServiceVersion LatestVersion = ServiceVersion.V7_0; - - /// The version of the service to use. - public enum ServiceVersion - { - /// Service version "7.0". - V7_0 = 1, - } - - internal string Version { get; } - - /// Initializes new instance of TemplateClientOptions. - public TemplateClientOptions(ServiceVersion version = LatestVersion) - { - Version = version switch - { - ServiceVersion.V7_0 => "7.0", - _ => throw new NotSupportedException() - }; - } - } -} diff --git a/sdk/template/Azure.Template/src/JobRouterClient.cs b/sdk/template/Azure.Template/src/JobRouterClient.cs new file mode 100644 index 000000000000..97efe049be0d --- /dev/null +++ b/sdk/template/Azure.Template/src/JobRouterClient.cs @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Diagnostics; +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Communication.JobRouter.Models; +using Azure.Core; +using Azure.Core.Serialization; + +namespace Azure.Communication.JobRouter +{ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + // Data plane generated client. + /// The JobRouter service client. + public partial class JobRouterClient + { + public virtual async Task> UpsertJobAsync(RouterJob job, CancellationToken cancellationToken = default) + { + if (job is not IModelJsonSerializable model) + { + throw new InvalidCastException("Model is not serializable."); + } + + RequestContent content = RequestContent.Create(model, new ModelSerializerOptions("P")); + Response response = await UpsertJobAsync(job.Id, content, new() { CancellationToken = cancellationToken }).ConfigureAwait(false); + + return Response.FromValue((RouterJob)response, response); + } + + public virtual Response UpsertJob(RouterJob job, CancellationToken cancellationToken = default) + { + if (job is not IModelJsonSerializable model) + { + throw new InvalidCastException("Model is not serializable."); + } + + RequestContent content = RequestContent.Create(model, new ModelSerializerOptions("P")); + Response response = UpsertJob(job.Id, content, new() { CancellationToken = cancellationToken }); + + return Response.FromValue((RouterJob)response, response); + } + + + public virtual async Task> GetJobAsync(string id, CancellationToken cancellationToken = default) + { + Response response = await GetJobAsync(id, new RequestContext() { CancellationToken = cancellationToken }).ConfigureAwait(false); + + return Response.FromValue((RouterJob)response, response); + } + + public virtual Response GetJob(string id, CancellationToken cancellationToken = default) + { + Response response = GetJob(id, new RequestContext() { CancellationToken = cancellationToken }); + + return Response.FromValue((RouterJob)response, response); + } + } +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member +} diff --git a/sdk/template/Azure.Template/src/Models/JobMatchModeType.cs b/sdk/template/Azure.Template/src/Models/JobMatchModeType.cs new file mode 100644 index 000000000000..41468c82e2a7 --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/JobMatchModeType.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Communication.JobRouter.Models +{ + /// The JobMatchModeType. + public readonly partial struct JobMatchModeType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public JobMatchModeType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string QueueAndMatchModeValue = "queueAndMatchMode"; + private const string ScheduleAndSuspendModeValue = "scheduleAndSuspendMode"; + private const string SuspendModeValue = "suspendMode"; + + /// queueAndMatchMode. + public static JobMatchModeType QueueAndMatchMode { get; } = new JobMatchModeType(QueueAndMatchModeValue); + /// scheduleAndSuspendMode. + public static JobMatchModeType ScheduleAndSuspendMode { get; } = new JobMatchModeType(ScheduleAndSuspendModeValue); + /// suspendMode. + public static JobMatchModeType SuspendMode { get; } = new JobMatchModeType(SuspendModeValue); + /// Determines if two values are the same. + public static bool operator ==(JobMatchModeType left, JobMatchModeType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(JobMatchModeType left, JobMatchModeType right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator JobMatchModeType(string value) => new JobMatchModeType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is JobMatchModeType other && Equals(other); + /// + public bool Equals(JobMatchModeType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/template/Azure.Template/src/Models/JobMatchingMode.Serialization.cs b/sdk/template/Azure.Template/src/Models/JobMatchingMode.Serialization.cs new file mode 100644 index 000000000000..06c5e115f12c --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/JobMatchingMode.Serialization.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.JobRouter.Models +{ + public partial class JobMatchingMode : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + if (Optional.IsDefined(ModeType)) + { + writer.WritePropertyName("modeType"u8); + writer.WriteStringValue(ModeType.Value.ToString()); + } + if (Optional.IsDefined(QueueAndMatchMode)) + { + writer.WritePropertyName("queueAndMatchMode"u8); + writer.WriteObjectValue(QueueAndMatchMode); + } + if (Optional.IsDefined(ScheduleAndSuspendMode)) + { + writer.WritePropertyName("scheduleAndSuspendMode"u8); + writer.WriteObjectValue(ScheduleAndSuspendMode); + } + if (Optional.IsDefined(SuspendMode)) + { + writer.WritePropertyName("suspendMode"u8); + writer.WriteObjectValue(SuspendMode); + } + writer.WriteEndObject(); + } + + internal static JobMatchingMode DeserializeJobMatchingMode(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional modeType = default; + Optional queueAndMatchMode = default; + Optional scheduleAndSuspendMode = default; + Optional suspendMode = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("modeType"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + modeType = new JobMatchModeType(property.Value.GetString()); + continue; + } + if (property.NameEquals("queueAndMatchMode"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + queueAndMatchMode = property.Value.GetObject(); + continue; + } + if (property.NameEquals("scheduleAndSuspendMode"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + scheduleAndSuspendMode = ScheduleAndSuspendMode.DeserializeScheduleAndSuspendMode(property.Value); + continue; + } + if (property.NameEquals("suspendMode"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + suspendMode = property.Value.GetObject(); + continue; + } + } + return new JobMatchingMode(Optional.ToNullable(modeType), queueAndMatchMode.Value, scheduleAndSuspendMode.Value, suspendMode.Value); + } + } +} diff --git a/sdk/template/Azure.Template/src/Models/JobMatchingMode.cs b/sdk/template/Azure.Template/src/Models/JobMatchingMode.cs new file mode 100644 index 000000000000..bb4808e337ee --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/JobMatchingMode.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +namespace Azure.Communication.JobRouter.Models +{ + /// The JobMatchingMode. + public partial class JobMatchingMode + { + /// Initializes a new instance of JobMatchingMode. + public JobMatchingMode() + { + } + + /// Initializes a new instance of JobMatchingMode. + /// + /// Any object. + /// + /// Any object. + internal JobMatchingMode(JobMatchModeType? modeType, object queueAndMatchMode, ScheduleAndSuspendMode scheduleAndSuspendMode, object suspendMode) + { + ModeType = modeType; + QueueAndMatchMode = queueAndMatchMode; + ScheduleAndSuspendMode = scheduleAndSuspendMode; + SuspendMode = suspendMode; + } + + /// Gets or sets the mode type. + public JobMatchModeType? ModeType { get; set; } + /// Any object. + public object QueueAndMatchMode { get; set; } + /// Gets or sets the schedule and suspend mode. + public ScheduleAndSuspendMode ScheduleAndSuspendMode { get; set; } + /// Any object. + public object SuspendMode { get; set; } + } +} diff --git a/sdk/template/Azure.Template/src/Models/LabelOperator.cs b/sdk/template/Azure.Template/src/Models/LabelOperator.cs new file mode 100644 index 000000000000..0e99ec962d8b --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/LabelOperator.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Communication.JobRouter.Models +{ + /// Describes how the value of the label is compared to the value pass through. + public readonly partial struct LabelOperator : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public LabelOperator(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string EqualValue = "equal"; + private const string NotEqualValue = "notEqual"; + private const string LessThanValue = "lessThan"; + private const string LessThanEqualValue = "lessThanEqual"; + private const string GreaterThanValue = "greaterThan"; + private const string GreaterThanEqualValue = "greaterThanEqual"; + + /// equal. + public static LabelOperator Equal { get; } = new LabelOperator(EqualValue); + /// notEqual. + public static LabelOperator NotEqual { get; } = new LabelOperator(NotEqualValue); + /// lessThan. + public static LabelOperator LessThan { get; } = new LabelOperator(LessThanValue); + /// lessThanEqual. + public static LabelOperator LessThanEqual { get; } = new LabelOperator(LessThanEqualValue); + /// greaterThan. + public static LabelOperator GreaterThan { get; } = new LabelOperator(GreaterThanValue); + /// greaterThanEqual. + public static LabelOperator GreaterThanEqual { get; } = new LabelOperator(GreaterThanEqualValue); + /// Determines if two values are the same. + public static bool operator ==(LabelOperator left, LabelOperator right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(LabelOperator left, LabelOperator right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator LabelOperator(string value) => new LabelOperator(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is LabelOperator other && Equals(other); + /// + public bool Equals(LabelOperator other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/template/Azure.Template/src/Models/RouterJob.Serialization.cs b/sdk/template/Azure.Template/src/Models/RouterJob.Serialization.cs new file mode 100644 index 000000000000..a70f53607315 --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/RouterJob.Serialization.cs @@ -0,0 +1,378 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; +using Azure.Core.Serialization; + +namespace Azure.Communication.JobRouter.Models +{ + public partial class RouterJob : IModelJsonSerializable, IUtf8JsonSerializable + { + #region Serialize + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IModelJsonSerializable)this).Serialize(writer, ModelSerializerOptions.DefaultWireOptions); + + void IModelJsonSerializable.Serialize(Utf8JsonWriter writer, ModelSerializerOptions options) + { + // TODO: PatchModelHelper.ValidateFormat(this, options.Format); + + switch (options.Format.ToString()) + { + case "J": + case "W": + Serialize(writer, options); + break; + case "P": + SerializePatch(writer); + break; + default: + // Exception was thrown by ValidateFormat. + break; + } + } + + BinaryData IModelSerializable.Serialize(ModelSerializerOptions options) + { + // TODO: PatchModelHelper.ValidateFormat(this, options.Format); + return ModelSerializer.SerializeCore(this, options); + } + + private void Serialize(Utf8JsonWriter writer, ModelSerializerOptions options) + { + writer.WriteStartObject(); + if (Optional.IsDefined(ChannelReference)) + { + writer.WritePropertyName("channelReference"u8); + writer.WriteStringValue(ChannelReference); + } + if (Optional.IsDefined(ChannelId)) + { + writer.WritePropertyName("channelId"u8); + writer.WriteStringValue(ChannelId); + } + if (Optional.IsDefined(ClassificationPolicyId)) + { + writer.WritePropertyName("classificationPolicyId"u8); + writer.WriteStringValue(ClassificationPolicyId); + } + if (Optional.IsDefined(QueueId)) + { + writer.WritePropertyName("queueId"u8); + writer.WriteStringValue(QueueId); + } + if (Optional.IsDefined(Priority)) + { + writer.WritePropertyName("priority"u8); + writer.WriteNumberValue(Priority.Value); + } + if (Optional.IsDefined(DispositionCode)) + { + writer.WritePropertyName("dispositionCode"u8); + writer.WriteStringValue(DispositionCode); + } + if (Optional.IsCollectionDefined(RequestedWorkerSelectors)) + { + writer.WritePropertyName("requestedWorkerSelectors"u8); + writer.WriteStartArray(); + foreach (var item in RequestedWorkerSelectors) + { + writer.WriteObjectValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Labels)) + { + writer.WritePropertyName("labels"u8); + writer.WriteStartObject(); + foreach (var item in Labels) + { + writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteObjectValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsCollectionDefined(Tags)) + { + writer.WritePropertyName("tags"u8); + writer.WriteStartObject(); + foreach (var item in Tags) + { + writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteObjectValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsCollectionDefined(Notes)) + { + writer.WritePropertyName("notes"u8); + writer.WriteStartObject(); + foreach (var item in Notes) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsDefined(MatchingMode)) + { + writer.WritePropertyName("matchingMode"u8); + writer.WriteObjectValue(MatchingMode); + } + writer.WriteEndObject(); + } + + private void SerializePatch(Utf8JsonWriter writer) + { + throw new NotImplementedException(); + } + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + public static implicit operator RequestContent(RouterJob model) +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member + => RequestContent.Create(model, ModelSerializerOptions.DefaultWireOptions); + #endregion + + #region Deserialize + internal static RouterJob DeserializeRouterJob(JsonElement element, ModelSerializerOptions options = default) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional id = default; + Optional channelReference = default; + Optional status = default; + Optional enqueuedAt = default; + Optional channelId = default; + Optional classificationPolicyId = default; + Optional queueId = default; + Optional priority = default; + Optional dispositionCode = default; + Optional> requestedWorkerSelectors = default; + Optional> attachedWorkerSelectors = default; + Optional> labels = default; + Optional> assignments = default; + Optional> tags = default; + Optional> notes = default; + Optional scheduledAt = default; + Optional matchingMode = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("channelReference"u8)) + { + channelReference = property.Value.GetString(); + continue; + } + if (property.NameEquals("status"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new RouterJobStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("enqueuedAt"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + enqueuedAt = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("channelId"u8)) + { + channelId = property.Value.GetString(); + continue; + } + if (property.NameEquals("classificationPolicyId"u8)) + { + classificationPolicyId = property.Value.GetString(); + continue; + } + if (property.NameEquals("queueId"u8)) + { + queueId = property.Value.GetString(); + continue; + } + if (property.NameEquals("priority"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + priority = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("dispositionCode"u8)) + { + dispositionCode = property.Value.GetString(); + continue; + } + if (property.NameEquals("requestedWorkerSelectors"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(RouterWorkerSelector.DeserializeRouterWorkerSelector(item)); + } + requestedWorkerSelectors = array; + continue; + } + if (property.NameEquals("attachedWorkerSelectors"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(RouterWorkerSelector.DeserializeRouterWorkerSelector(item)); + } + attachedWorkerSelectors = array; + continue; + } + if (property.NameEquals("labels"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + if (property0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(property0.Name, null); + } + else + { + dictionary.Add(property0.Name, property0.Value.GetObject()); + } + } + labels = dictionary; + continue; + } + if (property.NameEquals("assignments"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, RouterJobAssignment.DeserializeRouterJobAssignment(property0.Value)); + } + assignments = dictionary; + continue; + } + if (property.NameEquals("tags"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + if (property0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(property0.Name, null); + } + else + { + dictionary.Add(property0.Name, property0.Value.GetObject()); + } + } + tags = dictionary; + continue; + } + if (property.NameEquals("notes"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + notes = dictionary; + continue; + } + if (property.NameEquals("scheduledAt"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + scheduledAt = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("matchingMode"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + matchingMode = JobMatchingMode.DeserializeJobMatchingMode(property.Value); + continue; + } + } + return new RouterJob(id.Value, channelReference.Value, Optional.ToNullable(status), Optional.ToNullable(enqueuedAt), channelId.Value, classificationPolicyId.Value, queueId.Value, Optional.ToNullable(priority), dispositionCode.Value, Optional.ToList(requestedWorkerSelectors), Optional.ToList(attachedWorkerSelectors), Optional.ToDictionary(labels), Optional.ToDictionary(assignments), Optional.ToDictionary(tags), Optional.ToDictionary(notes), Optional.ToNullable(scheduledAt), matchingMode.Value); + } + + RouterJob IModelJsonSerializable.Deserialize(ref Utf8JsonReader reader, ModelSerializerOptions options) + { + // TODO: PatchModelHelper.ValidateFormat(this, options.Format); + using var doc = JsonDocument.ParseValue(ref reader); + return DeserializeRouterJob(doc.RootElement, options); + } + + RouterJob IModelSerializable.Deserialize(BinaryData data, ModelSerializerOptions options) + { + // TODO: PatchModelHelper.ValidateFormat(this, options.Format); + return DeserializeRouterJob(JsonDocument.Parse(data.ToString()).RootElement, options); + } + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + public static explicit operator RouterJob(Response response) +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member + { + Argument.AssertNotNull(response, nameof(response)); + + using JsonDocument jsonDocument = JsonDocument.Parse(response.ContentStream); + return DeserializeRouterJob(jsonDocument.RootElement, ModelSerializerOptions.DefaultWireOptions); + } + #endregion + } +} diff --git a/sdk/template/Azure.Template/src/Models/RouterJob.cs b/sdk/template/Azure.Template/src/Models/RouterJob.cs new file mode 100644 index 000000000000..9e59ea1e791e --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/RouterJob.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.Communication.JobRouter.Models +{ + /// A unit of work to be routed. + public partial class RouterJob + { + /// Initializes a new instance of RouterJob. + public RouterJob(string id) + { + Id = id; + + RequestedWorkerSelectors = new ChangeTrackingList(); + AttachedWorkerSelectors = new ChangeTrackingList(); + Labels = new ChangeTrackingDictionary(); + Assignments = new ChangeTrackingDictionary(); + Tags = new ChangeTrackingDictionary(); + Notes = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of RouterJob. + /// The id of the job. + /// Reference to an external parent context, eg. call ID. + /// The status of the Job. + /// The time a job was queued in UTC. + /// The channel identifier. eg. voice, chat, etc. + /// The Id of the Classification policy used for classifying a job. + /// The Id of the Queue that this job is queued to. + /// The priority of this job. + /// Reason code for cancelled or closed jobs. + /// A collection of manually specified label selectors, which a worker must satisfy in order to process this job. + /// A collection of label selectors attached by a classification policy, which a worker must satisfy in order to process this job. + /// A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. + /// + /// A collection of the assignments of the job. + /// Key is AssignmentId. + /// + /// A set of non-identifying attributes attached to this job. + /// Notes attached to a job, sorted by timestamp. + /// If set, job will be scheduled to be enqueued at a given time. + /// + internal RouterJob(string id, string channelReference, RouterJobStatus? status, DateTimeOffset? enqueuedAt, string channelId, string classificationPolicyId, string queueId, int? priority, string dispositionCode, IList requestedWorkerSelectors, IReadOnlyList attachedWorkerSelectors, IDictionary labels, IReadOnlyDictionary assignments, IDictionary tags, IDictionary notes, DateTimeOffset? scheduledAt, JobMatchingMode matchingMode) + { + Id = id; + ChannelReference = channelReference; + Status = status; + EnqueuedAt = enqueuedAt; + ChannelId = channelId; + ClassificationPolicyId = classificationPolicyId; + QueueId = queueId; + Priority = priority; + DispositionCode = dispositionCode; + RequestedWorkerSelectors = requestedWorkerSelectors; + AttachedWorkerSelectors = attachedWorkerSelectors; + Labels = labels; + Assignments = assignments; + Tags = tags; + Notes = notes; + ScheduledAt = scheduledAt; + MatchingMode = matchingMode; + } + + /// The id of the job. + public string Id { get; } + /// Reference to an external parent context, eg. call ID. + public string ChannelReference { get; set; } + /// The status of the Job. + public RouterJobStatus? Status { get; } + /// The time a job was queued in UTC. + public DateTimeOffset? EnqueuedAt { get; } + /// The channel identifier. eg. voice, chat, etc. + public string ChannelId { get; set; } + /// The Id of the Classification policy used for classifying a job. + public string ClassificationPolicyId { get; set; } + /// The Id of the Queue that this job is queued to. + public string QueueId { get; set; } + /// The priority of this job. + public int? Priority { get; set; } + /// Reason code for cancelled or closed jobs. + public string DispositionCode { get; set; } + /// A collection of manually specified label selectors, which a worker must satisfy in order to process this job. + public IList RequestedWorkerSelectors { get; } + /// A collection of label selectors attached by a classification policy, which a worker must satisfy in order to process this job. + public IReadOnlyList AttachedWorkerSelectors { get; } + /// A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. + public IDictionary Labels { get; } + /// + /// A collection of the assignments of the job. + /// Key is AssignmentId. + /// + public IReadOnlyDictionary Assignments { get; } + /// A set of non-identifying attributes attached to this job. + public IDictionary Tags { get; } + /// Notes attached to a job, sorted by timestamp. + public IDictionary Notes { get; } + /// If set, job will be scheduled to be enqueued at a given time. + public DateTimeOffset? ScheduledAt { get; } + /// Gets or sets the matching mode. + public JobMatchingMode MatchingMode { get; set; } + } +} diff --git a/sdk/template/Azure.Template/src/Models/RouterJobAssignment.Serialization.cs b/sdk/template/Azure.Template/src/Models/RouterJobAssignment.Serialization.cs new file mode 100644 index 000000000000..ded886157399 --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/RouterJobAssignment.Serialization.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.JobRouter.Models +{ + public partial class RouterJobAssignment + { + internal static RouterJobAssignment DeserializeRouterJobAssignment(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string assignmentId = default; + Optional workerId = default; + DateTimeOffset assignedAt = default; + Optional completedAt = default; + Optional closedAt = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("assignmentId"u8)) + { + assignmentId = property.Value.GetString(); + continue; + } + if (property.NameEquals("workerId"u8)) + { + workerId = property.Value.GetString(); + continue; + } + if (property.NameEquals("assignedAt"u8)) + { + assignedAt = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("completedAt"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + completedAt = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("closedAt"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + closedAt = property.Value.GetDateTimeOffset("O"); + continue; + } + } + return new RouterJobAssignment(assignmentId, workerId.Value, assignedAt, Optional.ToNullable(completedAt), Optional.ToNullable(closedAt)); + } + } +} diff --git a/sdk/template/Azure.Template/src/Models/RouterJobAssignment.cs b/sdk/template/Azure.Template/src/Models/RouterJobAssignment.cs new file mode 100644 index 000000000000..4c3f4fb5f8fe --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/RouterJobAssignment.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.Communication.JobRouter.Models +{ + /// Assignment details of a job to a worker. + public partial class RouterJobAssignment + { + /// Initializes a new instance of RouterJobAssignment. + /// The Id of the job assignment. + /// The assignment time of the job in UTC. + /// is null. + internal RouterJobAssignment(string assignmentId, DateTimeOffset assignedAt) + { + Argument.AssertNotNull(assignmentId, nameof(assignmentId)); + + AssignmentId = assignmentId; + AssignedAt = assignedAt; + } + + /// Initializes a new instance of RouterJobAssignment. + /// The Id of the job assignment. + /// The Id of the Worker assigned to the job. + /// The assignment time of the job in UTC. + /// The time the job was marked as completed after being assigned in UTC. + /// The time the job was marked as closed after being completed in UTC. + internal RouterJobAssignment(string assignmentId, string workerId, DateTimeOffset assignedAt, DateTimeOffset? completedAt, DateTimeOffset? closedAt) + { + AssignmentId = assignmentId; + WorkerId = workerId; + AssignedAt = assignedAt; + CompletedAt = completedAt; + ClosedAt = closedAt; + } + + /// The Id of the job assignment. + public string AssignmentId { get; } + /// The Id of the Worker assigned to the job. + public string WorkerId { get; } + /// The assignment time of the job in UTC. + public DateTimeOffset AssignedAt { get; } + /// The time the job was marked as completed after being assigned in UTC. + public DateTimeOffset? CompletedAt { get; } + /// The time the job was marked as closed after being completed in UTC. + public DateTimeOffset? ClosedAt { get; } + } +} diff --git a/sdk/template/Azure.Template/src/Models/RouterJobStatus.cs b/sdk/template/Azure.Template/src/Models/RouterJobStatus.cs new file mode 100644 index 000000000000..af78cdc21ca2 --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/RouterJobStatus.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Communication.JobRouter.Models +{ + /// The status of the Job. + public readonly partial struct RouterJobStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public RouterJobStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string PendingClassificationValue = "pendingClassification"; + private const string QueuedValue = "queued"; + private const string AssignedValue = "assigned"; + private const string CompletedValue = "completed"; + private const string ClosedValue = "closed"; + private const string CancelledValue = "cancelled"; + private const string ClassificationFailedValue = "classificationFailed"; + private const string CreatedValue = "created"; + private const string PendingScheduleValue = "pendingSchedule"; + private const string ScheduledValue = "scheduled"; + private const string ScheduleFailedValue = "scheduleFailed"; + private const string WaitingForActivationValue = "waitingForActivation"; + + /// pendingClassification. + public static RouterJobStatus PendingClassification { get; } = new RouterJobStatus(PendingClassificationValue); + /// queued. + public static RouterJobStatus Queued { get; } = new RouterJobStatus(QueuedValue); + /// assigned. + public static RouterJobStatus Assigned { get; } = new RouterJobStatus(AssignedValue); + /// completed. + public static RouterJobStatus Completed { get; } = new RouterJobStatus(CompletedValue); + /// closed. + public static RouterJobStatus Closed { get; } = new RouterJobStatus(ClosedValue); + /// cancelled. + public static RouterJobStatus Cancelled { get; } = new RouterJobStatus(CancelledValue); + /// classificationFailed. + public static RouterJobStatus ClassificationFailed { get; } = new RouterJobStatus(ClassificationFailedValue); + /// created. + public static RouterJobStatus Created { get; } = new RouterJobStatus(CreatedValue); + /// pendingSchedule. + public static RouterJobStatus PendingSchedule { get; } = new RouterJobStatus(PendingScheduleValue); + /// scheduled. + public static RouterJobStatus Scheduled { get; } = new RouterJobStatus(ScheduledValue); + /// scheduleFailed. + public static RouterJobStatus ScheduleFailed { get; } = new RouterJobStatus(ScheduleFailedValue); + /// waitingForActivation. + public static RouterJobStatus WaitingForActivation { get; } = new RouterJobStatus(WaitingForActivationValue); + /// Determines if two values are the same. + public static bool operator ==(RouterJobStatus left, RouterJobStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(RouterJobStatus left, RouterJobStatus right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator RouterJobStatus(string value) => new RouterJobStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is RouterJobStatus other && Equals(other); + /// + public bool Equals(RouterJobStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/template/Azure.Template/src/Models/RouterJobStatusSelector.cs b/sdk/template/Azure.Template/src/Models/RouterJobStatusSelector.cs new file mode 100644 index 000000000000..c6f22da23a55 --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/RouterJobStatusSelector.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Communication.JobRouter.Models +{ + /// The RouterJobStatusSelector. + public readonly partial struct RouterJobStatusSelector : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public RouterJobStatusSelector(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AllValue = "all"; + private const string PendingClassificationValue = "pendingClassification"; + private const string QueuedValue = "queued"; + private const string AssignedValue = "assigned"; + private const string CompletedValue = "completed"; + private const string ClosedValue = "closed"; + private const string CancelledValue = "cancelled"; + private const string ClassificationFailedValue = "classificationFailed"; + private const string CreatedValue = "created"; + private const string PendingScheduleValue = "pendingSchedule"; + private const string ScheduledValue = "scheduled"; + private const string ScheduleFailedValue = "scheduleFailed"; + private const string WaitingForActivationValue = "waitingForActivation"; + private const string ActiveValue = "active"; + + /// all. + public static RouterJobStatusSelector All { get; } = new RouterJobStatusSelector(AllValue); + /// pendingClassification. + public static RouterJobStatusSelector PendingClassification { get; } = new RouterJobStatusSelector(PendingClassificationValue); + /// queued. + public static RouterJobStatusSelector Queued { get; } = new RouterJobStatusSelector(QueuedValue); + /// assigned. + public static RouterJobStatusSelector Assigned { get; } = new RouterJobStatusSelector(AssignedValue); + /// completed. + public static RouterJobStatusSelector Completed { get; } = new RouterJobStatusSelector(CompletedValue); + /// closed. + public static RouterJobStatusSelector Closed { get; } = new RouterJobStatusSelector(ClosedValue); + /// cancelled. + public static RouterJobStatusSelector Cancelled { get; } = new RouterJobStatusSelector(CancelledValue); + /// classificationFailed. + public static RouterJobStatusSelector ClassificationFailed { get; } = new RouterJobStatusSelector(ClassificationFailedValue); + /// created. + public static RouterJobStatusSelector Created { get; } = new RouterJobStatusSelector(CreatedValue); + /// pendingSchedule. + public static RouterJobStatusSelector PendingSchedule { get; } = new RouterJobStatusSelector(PendingScheduleValue); + /// scheduled. + public static RouterJobStatusSelector Scheduled { get; } = new RouterJobStatusSelector(ScheduledValue); + /// scheduleFailed. + public static RouterJobStatusSelector ScheduleFailed { get; } = new RouterJobStatusSelector(ScheduleFailedValue); + /// waitingForActivation. + public static RouterJobStatusSelector WaitingForActivation { get; } = new RouterJobStatusSelector(WaitingForActivationValue); + /// active. + public static RouterJobStatusSelector Active { get; } = new RouterJobStatusSelector(ActiveValue); + /// Determines if two values are the same. + public static bool operator ==(RouterJobStatusSelector left, RouterJobStatusSelector right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(RouterJobStatusSelector left, RouterJobStatusSelector right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator RouterJobStatusSelector(string value) => new RouterJobStatusSelector(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is RouterJobStatusSelector other && Equals(other); + /// + public bool Equals(RouterJobStatusSelector other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/template/Azure.Template/src/Models/RouterWorkerSelector.Serialization.cs b/sdk/template/Azure.Template/src/Models/RouterWorkerSelector.Serialization.cs new file mode 100644 index 000000000000..10aeacf93984 --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/RouterWorkerSelector.Serialization.cs @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.JobRouter.Models +{ + public partial class RouterWorkerSelector : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + writer.WritePropertyName("key"u8); + writer.WriteStringValue(Key); + writer.WritePropertyName("labelOperator"u8); + writer.WriteStringValue(LabelOperator.ToString()); + if (Optional.IsDefined(Value)) + { + writer.WritePropertyName("value"u8); + writer.WriteObjectValue(Value); + } + if (Optional.IsDefined(ExpiresAfterSeconds)) + { + writer.WritePropertyName("expiresAfterSeconds"u8); + writer.WriteNumberValue(ExpiresAfterSeconds.Value); + } + if (Optional.IsDefined(Expedite)) + { + writer.WritePropertyName("expedite"u8); + writer.WriteBooleanValue(Expedite.Value); + } + writer.WriteEndObject(); + } + + internal static RouterWorkerSelector DeserializeRouterWorkerSelector(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string key = default; + LabelOperator labelOperator = default; + Optional value = default; + Optional expiresAfterSeconds = default; + Optional expedite = default; + Optional status = default; + Optional expiresAt = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("key"u8)) + { + key = property.Value.GetString(); + continue; + } + if (property.NameEquals("labelOperator"u8)) + { + labelOperator = new LabelOperator(property.Value.GetString()); + continue; + } + if (property.NameEquals("value"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + value = property.Value.GetObject(); + continue; + } + if (property.NameEquals("expiresAfterSeconds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expiresAfterSeconds = property.Value.GetDouble(); + continue; + } + if (property.NameEquals("expedite"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expedite = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("status"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new RouterWorkerSelectorStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("expiresAt"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expiresAt = property.Value.GetDateTimeOffset("O"); + continue; + } + } + return new RouterWorkerSelector(key, labelOperator, value.Value, Optional.ToNullable(expiresAfterSeconds), Optional.ToNullable(expedite), Optional.ToNullable(status), Optional.ToNullable(expiresAt)); + } + } +} diff --git a/sdk/template/Azure.Template/src/Models/RouterWorkerSelector.cs b/sdk/template/Azure.Template/src/Models/RouterWorkerSelector.cs new file mode 100644 index 000000000000..ab13e536dffe --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/RouterWorkerSelector.cs @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.Communication.JobRouter.Models +{ + /// Describes a condition that must be met against a set of labels for worker selection. + public partial class RouterWorkerSelector + { + /// Initializes a new instance of RouterWorkerSelector. + /// The label key to query against. + /// Describes how the value of the label is compared to the value defined on the label selector. + /// is null. + public RouterWorkerSelector(string key, LabelOperator labelOperator) + { + Argument.AssertNotNull(key, nameof(key)); + + Key = key; + LabelOperator = labelOperator; + } + + /// Initializes a new instance of RouterWorkerSelector. + /// The label key to query against. + /// Describes how the value of the label is compared to the value defined on the label selector. + /// The value to compare against the actual label value with the given operator. + /// Describes how long this label selector is valid in seconds. + /// Pushes the job to the front of the queue as long as this selector is active. + /// The status of the worker selector. + /// The time at which this worker selector expires in UTC. + internal RouterWorkerSelector(string key, LabelOperator labelOperator, object value, double? expiresAfterSeconds, bool? expedite, RouterWorkerSelectorStatus? status, DateTimeOffset? expiresAt) + { + Key = key; + LabelOperator = labelOperator; + Value = value; + ExpiresAfterSeconds = expiresAfterSeconds; + Expedite = expedite; + Status = status; + ExpiresAt = expiresAt; + } + + /// The label key to query against. + public string Key { get; set; } + /// Describes how the value of the label is compared to the value defined on the label selector. + public LabelOperator LabelOperator { get; set; } + /// The value to compare against the actual label value with the given operator. + public object Value { get; set; } + /// Describes how long this label selector is valid in seconds. + public double? ExpiresAfterSeconds { get; set; } + /// Pushes the job to the front of the queue as long as this selector is active. + public bool? Expedite { get; set; } + /// The status of the worker selector. + public RouterWorkerSelectorStatus? Status { get; } + /// The time at which this worker selector expires in UTC. + public DateTimeOffset? ExpiresAt { get; } + } +} diff --git a/sdk/template/Azure.Template/src/Models/RouterWorkerSelectorStatus.cs b/sdk/template/Azure.Template/src/Models/RouterWorkerSelectorStatus.cs new file mode 100644 index 000000000000..e3cb273b0b25 --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/RouterWorkerSelectorStatus.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.Communication.JobRouter.Models +{ + /// The status of the worker selector. + public readonly partial struct RouterWorkerSelectorStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public RouterWorkerSelectorStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ActiveValue = "active"; + private const string ExpiredValue = "expired"; + + /// active. + public static RouterWorkerSelectorStatus Active { get; } = new RouterWorkerSelectorStatus(ActiveValue); + /// expired. + public static RouterWorkerSelectorStatus Expired { get; } = new RouterWorkerSelectorStatus(ExpiredValue); + /// Determines if two values are the same. + public static bool operator ==(RouterWorkerSelectorStatus left, RouterWorkerSelectorStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(RouterWorkerSelectorStatus left, RouterWorkerSelectorStatus right) => !left.Equals(right); + /// Converts a string to a . + public static implicit operator RouterWorkerSelectorStatus(string value) => new RouterWorkerSelectorStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is RouterWorkerSelectorStatus other && Equals(other); + /// + public bool Equals(RouterWorkerSelectorStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/template/Azure.Template/src/Models/ScheduleAndSuspendMode.Serialization.cs b/sdk/template/Azure.Template/src/Models/ScheduleAndSuspendMode.Serialization.cs new file mode 100644 index 000000000000..1abc6b2e81cf --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/ScheduleAndSuspendMode.Serialization.cs @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.JobRouter.Models +{ + public partial class ScheduleAndSuspendMode : IUtf8JsonSerializable + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + if (Optional.IsDefined(ScheduleAt)) + { + writer.WritePropertyName("scheduleAt"u8); + writer.WriteStringValue(ScheduleAt.Value, "O"); + } + writer.WriteEndObject(); + } + + internal static ScheduleAndSuspendMode DeserializeScheduleAndSuspendMode(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional scheduleAt = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("scheduleAt"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + scheduleAt = property.Value.GetDateTimeOffset("O"); + continue; + } + } + return new ScheduleAndSuspendMode(Optional.ToNullable(scheduleAt)); + } + } +} diff --git a/sdk/template/Azure.Template/src/Models/ScheduleAndSuspendMode.cs b/sdk/template/Azure.Template/src/Models/ScheduleAndSuspendMode.cs new file mode 100644 index 000000000000..97dc65711125 --- /dev/null +++ b/sdk/template/Azure.Template/src/Models/ScheduleAndSuspendMode.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Azure.Communication.JobRouter.Models +{ + /// The ScheduleAndSuspendMode. + public partial class ScheduleAndSuspendMode + { + /// Initializes a new instance of ScheduleAndSuspendMode. + public ScheduleAndSuspendMode() + { + } + + /// Initializes a new instance of ScheduleAndSuspendMode. + /// + internal ScheduleAndSuspendMode(DateTimeOffset? scheduleAt) + { + ScheduleAt = scheduleAt; + } + + /// Gets or sets the schedule at. + public DateTimeOffset? ScheduleAt { get; set; } + } +} diff --git a/sdk/template/Azure.Template/src/Models/SecretBundle.Serialization.cs b/sdk/template/Azure.Template/src/Models/SecretBundle.Serialization.cs deleted file mode 100644 index 0c1f66b97101..000000000000 --- a/sdk/template/Azure.Template/src/Models/SecretBundle.Serialization.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.Template.Models -{ - public partial class SecretBundle - { - internal static SecretBundle DeserializeSecretBundle(JsonElement element) - { - Optional value = default; - Optional id = default; - Optional contentType = default; - Optional> tags = default; - Optional kid = default; - Optional managed = default; - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("value")) - { - value = property.Value.GetString(); - continue; - } - if (property.NameEquals("id")) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("contentType")) - { - contentType = property.Value.GetString(); - continue; - } - if (property.NameEquals("tags")) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) - { - dictionary.Add(property0.Name, property0.Value.GetString()); - } - tags = dictionary; - continue; - } - if (property.NameEquals("kid")) - { - kid = property.Value.GetString(); - continue; - } - if (property.NameEquals("managed")) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - property.ThrowNonNullablePropertyIsNull(); - continue; - } - managed = property.Value.GetBoolean(); - continue; - } - } - return new SecretBundle(value.Value, id.Value, contentType.Value, Optional.ToDictionary(tags), kid.Value, Optional.ToNullable(managed)); - } - - internal static SecretBundle FromResponse(Response response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeSecretBundle(document.RootElement); - } - } -} diff --git a/sdk/template/Azure.Template/src/Models/SecretBundle.cs b/sdk/template/Azure.Template/src/Models/SecretBundle.cs deleted file mode 100644 index fb3693244513..000000000000 --- a/sdk/template/Azure.Template/src/Models/SecretBundle.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System.Collections.Generic; -using Azure.Core; - -namespace Azure.Template.Models -{ - /// A secret consisting of a value, id and its attributes. - public partial class SecretBundle - { - /// Initializes a new instance of SecretBundle. - internal SecretBundle() - { - Tags = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of SecretBundle. - /// The secret value. - /// The secret id. - /// The content type of the secret. - /// Application specific metadata in the form of key-value pairs. - /// If this is a secret backing a KV certificate, then this field specifies the corresponding key backing the KV certificate. - /// True if the secret's lifetime is managed by key vault. If this is a secret backing a certificate, then managed will be true. - internal SecretBundle(string value, string id, string contentType, IReadOnlyDictionary tags, string kid, bool? managed) - { - Value = value; - Id = id; - ContentType = contentType; - Tags = tags; - Kid = kid; - Managed = managed; - } - - /// The secret value. - public string Value { get; } - /// The secret id. - public string Id { get; } - /// The content type of the secret. - public string ContentType { get; } - /// Application specific metadata in the form of key-value pairs. - public IReadOnlyDictionary Tags { get; } - /// If this is a secret backing a KV certificate, then this field specifies the corresponding key backing the KV certificate. - public string Kid { get; } - /// True if the secret's lifetime is managed by key vault. If this is a secret backing a certificate, then managed will be true. - public bool? Managed { get; } - } -} diff --git a/sdk/template/Azure.Template/src/TemplateClient.cs b/sdk/template/Azure.Template/src/TemplateClient.cs deleted file mode 100644 index 0053351597f3..000000000000 --- a/sdk/template/Azure.Template/src/TemplateClient.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#nullable disable - -using System; -using System.Threading; -using System.Threading.Tasks; -using Azure.Core.Pipeline; -using Azure.Template.Models; - -namespace Azure.Template -{ - /// The Template service client. - public partial class TemplateClient - { - /// The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get permission. - /// The name of the secret. - /// The cancellation token to use. - public virtual async Task> GetSecretValueAsync(string secretName, CancellationToken cancellationToken = default) - { - using DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(TemplateClient)}.{nameof(GetSecretValue)}"); - scope.Start(); - - try - { - RequestContext context = new RequestContext() - { - CancellationToken = cancellationToken, - }; - Response response = await GetSecretAsync(secretName, context).ConfigureAwait(false); - SecretBundle value = SecretBundle.FromResponse(response); - return Response.FromValue(value, response); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get permission. - /// The name of the secret. - /// The cancellation token to use. - public virtual Response GetSecretValue(string secretName, CancellationToken cancellationToken = default) - { - using DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(TemplateClient)}.{nameof(GetSecretValue)}"); - scope.Start(); - - try - { - RequestContext context = new RequestContext() - { - CancellationToken = cancellationToken, - }; - Response response = GetSecret(secretName, context); - SecretBundle value = SecretBundle.FromResponse(response); - return Response.FromValue(value, response); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - } -} diff --git a/sdk/template/Azure.Template/src/autorest.md b/sdk/template/Azure.Template/src/autorest.md index fb916b5a8ee2..a363bd387b2b 100644 --- a/sdk/template/Azure.Template/src/autorest.md +++ b/sdk/template/Azure.Template/src/autorest.md @@ -1,14 +1,9 @@ # Azure SDK Code Generation for Data Plane -Run `dotnet build /t:GenerateCode` to generate code. - -### AutoRest Configuration -> see https://aka.ms/autorest - ``` yaml -input-file: -- $(this-folder)/swagger/mini-secrets.json -namespace: Azure.Template +require: +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/29159d148372f5f61cb04b76fc87252b13c62515/specification/communication/data-plane/JobRouter/readme.md +namespace: Azure.Communication.JobRouter security: AADToken -security-scopes: https://vault.azure.net/.default +security-scopes: https://example.azure.net/.default ``` diff --git a/sdk/template/Azure.Template/src/swagger/mini-secrets.json b/sdk/template/Azure.Template/src/swagger/mini-secrets.json deleted file mode 100644 index 0c4853a0c78a..000000000000 --- a/sdk/template/Azure.Template/src/swagger/mini-secrets.json +++ /dev/null @@ -1,110 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "title": "TemplateClient", - "description": "The key vault client performs cryptographic key operations and vault operations against the Key Vault service.", - "version": "7.0" - }, - "x-ms-parameterized-host": { - "hostTemplate": "{vaultBaseUrl}", - "useSchemePrefix": false, - "positionInOperation": "first", - "parameters": [ - { - "name": "vaultBaseUrl", - "description": "The vault name, for example https://myvault.vault.azure.net.", - "required": true, - "type": "string", - "in": "path", - "x-ms-skip-url-encoding": true, - "x-ms-parameter-location": "client" - } - ] - }, - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "paths": { - "/secrets/{secret-name}": { - "get": { - "tags": [ - "Secrets" - ], - "operationId": "GetSecret", - "summary": "Get a specified secret from a given key vault.", - "description": "The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get permission.", - "parameters": [ - { - "name": "secret-name", - "in": "path", - "required": true, - "type": "string", - "description": "The name of the secret." - }, - { - "$ref": "#/parameters/ApiVersionParameter" - } - ], - "responses": { - "200": { - "description": "The retrieved secret.", - "schema": { - "$ref": "#/definitions/SecretBundle" - } - }, - "default": { - "description": "Key Vault error response describing why the operation failed." - } - } - } - } - }, - "definitions": { - "SecretBundle": { - "properties": { - "value": { - "type": "string", - "description": "The secret value." - }, - "id": { - "type": "string", - "description": "The secret id." - }, - "contentType": { - "type": "string", - "description": "The content type of the secret." - }, - "tags": { - "type": "object", - "additionalProperties": { - "type": "string" - }, - "description": "Application specific metadata in the form of key-value pairs." - }, - "kid": { - "type": "string", - "readOnly": true, - "description": "If this is a secret backing a KV certificate, then this field specifies the corresponding key backing the KV certificate." - }, - "managed": { - "type": "boolean", - "readOnly": true, - "description": "True if the secret's lifetime is managed by key vault. If this is a secret backing a certificate, then managed will be true." - } - }, - "description": "A secret consisting of a value, id and its attributes." - } - }, - "parameters": { - "ApiVersionParameter": { - "name": "api-version", - "in": "query", - "required": true, - "type": "string", - "description": "Client API version." - } - } -} diff --git a/sdk/template/Azure.Template/tests/Azure.Template.Tests.csproj b/sdk/template/Azure.Template/tests/Azure.Communication.JobRouter.Tests.csproj similarity index 82% rename from sdk/template/Azure.Template/tests/Azure.Template.Tests.csproj rename to sdk/template/Azure.Template/tests/Azure.Communication.JobRouter.Tests.csproj index 743b77ec082c..00b18cf8552d 100644 --- a/sdk/template/Azure.Template/tests/Azure.Template.Tests.csproj +++ b/sdk/template/Azure.Template/tests/Azure.Communication.JobRouter.Tests.csproj @@ -9,7 +9,7 @@ - + @@ -21,5 +21,6 @@ + \ No newline at end of file diff --git a/sdk/template/Azure.Template/tests/Generated/Samples/Samples_JobRouterAdministrationClient.cs b/sdk/template/Azure.Template/tests/Generated/Samples/Samples_JobRouterAdministrationClient.cs new file mode 100644 index 000000000000..4ecf653a286e --- /dev/null +++ b/sdk/template/Azure.Template/tests/Generated/Samples/Samples_JobRouterAdministrationClient.cs @@ -0,0 +1,1178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Azure.Communication.JobRouter.Samples +{ + public class Samples_JobRouterAdministrationClient + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_UpsertClassificationPolicy() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new { }; + + Response response = client.UpsertClassificationPolicy("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_UpsertClassificationPolicy_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new + { + name = "", + fallbackQueueId = "", + queueSelectors = new[] { + new { + condition = new { + kind = "direct-map-rule", + }, + queueSelectors = new[] { + new { + key = "", + labelOperator = "equal", + value = new {}, + } + }, + kind = "conditional", + } + }, + prioritizationRule = new + { + kind = "direct-map-rule", + }, + workerSelectors = new[] { + new { + condition = new { + kind = "direct-map-rule", + }, + workerSelectors = new[] { + new { + key = "", + labelOperator = "equal", + value = new {}, + expiresAfterSeconds = 123.45d, + expedite = true, + } + }, + kind = "conditional", + } + }, + }; + + Response response = client.UpsertClassificationPolicy("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("fallbackQueueId").ToString()); + Console.WriteLine(result.GetProperty("queueSelectors")[0].GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("prioritizationRule").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("workerSelectors")[0].GetProperty("kind").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_UpsertClassificationPolicy_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new { }; + + Response response = await client.UpsertClassificationPolicyAsync("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_UpsertClassificationPolicy_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new + { + name = "", + fallbackQueueId = "", + queueSelectors = new[] { + new { + condition = new { + kind = "direct-map-rule", + }, + queueSelectors = new[] { + new { + key = "", + labelOperator = "equal", + value = new {}, + } + }, + kind = "conditional", + } + }, + prioritizationRule = new + { + kind = "direct-map-rule", + }, + workerSelectors = new[] { + new { + condition = new { + kind = "direct-map-rule", + }, + workerSelectors = new[] { + new { + key = "", + labelOperator = "equal", + value = new {}, + expiresAfterSeconds = 123.45d, + expedite = true, + } + }, + kind = "conditional", + } + }, + }; + + Response response = await client.UpsertClassificationPolicyAsync("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("fallbackQueueId").ToString()); + Console.WriteLine(result.GetProperty("queueSelectors")[0].GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("prioritizationRule").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("workerSelectors")[0].GetProperty("kind").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetClassificationPolicy() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.GetClassificationPolicy("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetClassificationPolicy_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.GetClassificationPolicy("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("fallbackQueueId").ToString()); + Console.WriteLine(result.GetProperty("queueSelectors")[0].GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("prioritizationRule").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("workerSelectors")[0].GetProperty("kind").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetClassificationPolicy_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.GetClassificationPolicyAsync("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetClassificationPolicy_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.GetClassificationPolicyAsync("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("fallbackQueueId").ToString()); + Console.WriteLine(result.GetProperty("queueSelectors")[0].GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("prioritizationRule").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("workerSelectors")[0].GetProperty("kind").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_DeleteClassificationPolicy() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.DeleteClassificationPolicy(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_DeleteClassificationPolicy_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.DeleteClassificationPolicy(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_DeleteClassificationPolicy_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.DeleteClassificationPolicyAsync(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_DeleteClassificationPolicy_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.DeleteClassificationPolicyAsync(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_UpsertDistributionPolicy() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new { }; + + Response response = client.UpsertDistributionPolicy("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_UpsertDistributionPolicy_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new + { + name = "", + offerExpiresAfterSeconds = 123.45d, + mode = new + { + scoringRule = new + { + kind = "direct-map-rule", + }, + scoringRuleOptions = new + { + batchSize = 1234, + scoringParameters = new[] { + "jobLabels" + }, + allowScoringBatchOfWorkers = true, + descendingOrder = true, + }, + kind = "best-worker", + minConcurrentOffers = 1234, + maxConcurrentOffers = 1234, + bypassSelectors = true, + }, + }; + + Response response = client.UpsertDistributionPolicy("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("offerExpiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("minConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("maxConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("bypassSelectors").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_UpsertDistributionPolicy_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new { }; + + Response response = await client.UpsertDistributionPolicyAsync("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_UpsertDistributionPolicy_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new + { + name = "", + offerExpiresAfterSeconds = 123.45d, + mode = new + { + scoringRule = new + { + kind = "direct-map-rule", + }, + scoringRuleOptions = new + { + batchSize = 1234, + scoringParameters = new[] { + "jobLabels" + }, + allowScoringBatchOfWorkers = true, + descendingOrder = true, + }, + kind = "best-worker", + minConcurrentOffers = 1234, + maxConcurrentOffers = 1234, + bypassSelectors = true, + }, + }; + + Response response = await client.UpsertDistributionPolicyAsync("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("offerExpiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("minConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("maxConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("bypassSelectors").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetDistributionPolicy() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.GetDistributionPolicy("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetDistributionPolicy_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.GetDistributionPolicy("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("offerExpiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("minConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("maxConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("bypassSelectors").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetDistributionPolicy_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.GetDistributionPolicyAsync("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetDistributionPolicy_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.GetDistributionPolicyAsync("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("offerExpiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("minConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("maxConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("mode").GetProperty("bypassSelectors").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_DeleteDistributionPolicy() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.DeleteDistributionPolicy(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_DeleteDistributionPolicy_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.DeleteDistributionPolicy(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_DeleteDistributionPolicy_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.DeleteDistributionPolicyAsync(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_DeleteDistributionPolicy_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.DeleteDistributionPolicyAsync(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_UpsertExceptionPolicy() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new { }; + + Response response = client.UpsertExceptionPolicy("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_UpsertExceptionPolicy_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new + { + name = "", + exceptionRules = new + { + key = new + { + trigger = new + { + threshold = 1234, + kind = "queue-length", + }, + actions = new + { + key = new + { + note = "", + dispositionCode = "", + kind = "cancel", + }, + }, + }, + }, + }; + + Response response = client.UpsertExceptionPolicy("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("trigger").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("actions").GetProperty("").GetProperty("kind").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_UpsertExceptionPolicy_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new { }; + + Response response = await client.UpsertExceptionPolicyAsync("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_UpsertExceptionPolicy_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new + { + name = "", + exceptionRules = new + { + key = new + { + trigger = new + { + threshold = 1234, + kind = "queue-length", + }, + actions = new + { + key = new + { + note = "", + dispositionCode = "", + kind = "cancel", + }, + }, + }, + }, + }; + + Response response = await client.UpsertExceptionPolicyAsync("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("trigger").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("actions").GetProperty("").GetProperty("kind").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetExceptionPolicy() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.GetExceptionPolicy("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetExceptionPolicy_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.GetExceptionPolicy("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("trigger").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("actions").GetProperty("").GetProperty("kind").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetExceptionPolicy_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.GetExceptionPolicyAsync("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetExceptionPolicy_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.GetExceptionPolicyAsync("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("trigger").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("exceptionRules").GetProperty("").GetProperty("actions").GetProperty("").GetProperty("kind").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_DeleteExceptionPolicy() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.DeleteExceptionPolicy(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_DeleteExceptionPolicy_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.DeleteExceptionPolicy(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_DeleteExceptionPolicy_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.DeleteExceptionPolicyAsync(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_DeleteExceptionPolicy_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.DeleteExceptionPolicyAsync(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_UpsertQueue() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new { }; + + Response response = client.UpsertQueue("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_UpsertQueue_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new + { + name = "", + distributionPolicyId = "", + labels = new + { + key = new { }, + }, + exceptionPolicyId = "", + }; + + Response response = client.UpsertQueue("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicyId").ToString()); + Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicyId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_UpsertQueue_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new { }; + + Response response = await client.UpsertQueueAsync("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_UpsertQueue_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + var data = new + { + name = "", + distributionPolicyId = "", + labels = new + { + key = new { }, + }, + exceptionPolicyId = "", + }; + + Response response = await client.UpsertQueueAsync("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicyId").ToString()); + Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicyId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetQueue() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.GetQueue("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetQueue_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.GetQueue("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicyId").ToString()); + Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicyId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetQueue_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.GetQueueAsync("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetQueue_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.GetQueueAsync("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicyId").ToString()); + Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicyId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_DeleteQueue() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.DeleteQueue(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_DeleteQueue_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = client.DeleteQueue(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_DeleteQueue_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.DeleteQueueAsync(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_DeleteQueue_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + Response response = await client.DeleteQueueAsync(""); + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetClassificationPolicies() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + foreach (var item in client.GetClassificationPolicies(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetClassificationPolicies_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + foreach (var item in client.GetClassificationPolicies(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("fallbackQueueId").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("queueSelectors")[0].GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("prioritizationRule").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("workerSelectors")[0].GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetClassificationPolicies_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + await foreach (var item in client.GetClassificationPoliciesAsync(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetClassificationPolicies_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + await foreach (var item in client.GetClassificationPoliciesAsync(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("fallbackQueueId").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("queueSelectors")[0].GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("prioritizationRule").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicy").GetProperty("workerSelectors")[0].GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetDistributionPolicies() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + foreach (var item in client.GetDistributionPolicies(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetDistributionPolicies_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + foreach (var item in client.GetDistributionPolicies(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("offerExpiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("minConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("maxConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("bypassSelectors").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetDistributionPolicies_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + await foreach (var item in client.GetDistributionPoliciesAsync(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetDistributionPolicies_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + await foreach (var item in client.GetDistributionPoliciesAsync(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("offerExpiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("minConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("maxConcurrentOffers").ToString()); + Console.WriteLine(result.GetProperty("distributionPolicy").GetProperty("mode").GetProperty("bypassSelectors").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetExceptionPolicies() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + foreach (var item in client.GetExceptionPolicies(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetExceptionPolicies_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + foreach (var item in client.GetExceptionPolicies(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("exceptionRules").GetProperty("").GetProperty("trigger").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("exceptionRules").GetProperty("").GetProperty("actions").GetProperty("").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetExceptionPolicies_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + await foreach (var item in client.GetExceptionPoliciesAsync(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetExceptionPolicies_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + await foreach (var item in client.GetExceptionPoliciesAsync(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("exceptionRules").GetProperty("").GetProperty("trigger").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("exceptionPolicy").GetProperty("exceptionRules").GetProperty("").GetProperty("actions").GetProperty("").GetProperty("kind").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetQueues() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + foreach (var item in client.GetQueues(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetQueues_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + foreach (var item in client.GetQueues(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("queue").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("distributionPolicyId").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("exceptionPolicyId").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetQueues_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + await foreach (var item in client.GetQueuesAsync(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetQueues_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterAdministrationClient("", credential); + + await foreach (var item in client.GetQueuesAsync(1234, new RequestContext())) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("queue").GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("distributionPolicyId").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("queue").GetProperty("exceptionPolicyId").ToString()); + Console.WriteLine(result.GetProperty("etag").ToString()); + } + } + } +} diff --git a/sdk/template/Azure.Template/tests/Generated/Samples/Samples_JobRouterClient.cs b/sdk/template/Azure.Template/tests/Generated/Samples/Samples_JobRouterClient.cs new file mode 100644 index 000000000000..a309c8917995 --- /dev/null +++ b/sdk/template/Azure.Template/tests/Generated/Samples/Samples_JobRouterClient.cs @@ -0,0 +1,352 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Azure.Communication.JobRouter.Samples +{ + public class Samples_JobRouterClient + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_UpsertJob() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + var data = new { }; + + Response response = client.UpsertJob("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_UpsertJob_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + var data = new + { + channelReference = "", + channelId = "", + classificationPolicyId = "", + queueId = "", + priority = 1234, + dispositionCode = "", + requestedWorkerSelectors = new[] { + new { + key = "", + labelOperator = "equal", + value = new {}, + expiresAfterSeconds = 123.45d, + expedite = true, + } + }, + labels = new + { + key = new { }, + }, + tags = new + { + key = new { }, + }, + notes = new + { + key = "", + }, + matchingMode = new + { + modeType = "queueAndMatchMode", + queueAndMatchMode = new { }, + scheduleAndSuspendMode = new + { + scheduleAt = "2022-05-10T18:57:31.2311892Z", + }, + suspendMode = new { }, + }, + }; + + Response response = client.UpsertJob("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("channelReference").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("enqueuedAt").ToString()); + Console.WriteLine(result.GetProperty("channelId").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicyId").ToString()); + Console.WriteLine(result.GetProperty("queueId").ToString()); + Console.WriteLine(result.GetProperty("priority").ToString()); + Console.WriteLine(result.GetProperty("dispositionCode").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("key").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expedite").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("key").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expedite").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignmentId").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("workerId").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignedAt").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("completedAt").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("closedAt").ToString()); + Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("notes").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("scheduledAt").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("modeType").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("queueAndMatchMode").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("scheduleAndSuspendMode").GetProperty("scheduleAt").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("suspendMode").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_UpsertJob_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + var data = new { }; + + Response response = await client.UpsertJobAsync("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_UpsertJob_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + var data = new + { + channelReference = "", + channelId = "", + classificationPolicyId = "", + queueId = "", + priority = 1234, + dispositionCode = "", + requestedWorkerSelectors = new[] { + new { + key = "", + labelOperator = "equal", + value = new {}, + expiresAfterSeconds = 123.45d, + expedite = true, + } + }, + labels = new + { + key = new { }, + }, + tags = new + { + key = new { }, + }, + notes = new + { + key = "", + }, + matchingMode = new + { + modeType = "queueAndMatchMode", + queueAndMatchMode = new { }, + scheduleAndSuspendMode = new + { + scheduleAt = "2022-05-10T18:57:31.2311892Z", + }, + suspendMode = new { }, + }, + }; + + Response response = await client.UpsertJobAsync("", RequestContent.Create(data)); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("channelReference").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("enqueuedAt").ToString()); + Console.WriteLine(result.GetProperty("channelId").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicyId").ToString()); + Console.WriteLine(result.GetProperty("queueId").ToString()); + Console.WriteLine(result.GetProperty("priority").ToString()); + Console.WriteLine(result.GetProperty("dispositionCode").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("key").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expedite").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("key").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expedite").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignmentId").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("workerId").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignedAt").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("completedAt").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("closedAt").ToString()); + Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("notes").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("scheduledAt").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("modeType").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("queueAndMatchMode").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("scheduleAndSuspendMode").GetProperty("scheduleAt").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("suspendMode").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetJob() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + Response response = client.GetJob("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_GetJob_AllParameters() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + Response response = client.GetJob("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("channelReference").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("enqueuedAt").ToString()); + Console.WriteLine(result.GetProperty("channelId").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicyId").ToString()); + Console.WriteLine(result.GetProperty("queueId").ToString()); + Console.WriteLine(result.GetProperty("priority").ToString()); + Console.WriteLine(result.GetProperty("dispositionCode").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("key").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expedite").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("key").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expedite").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignmentId").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("workerId").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignedAt").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("completedAt").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("closedAt").ToString()); + Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("notes").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("scheduledAt").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("modeType").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("queueAndMatchMode").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("scheduleAndSuspendMode").GetProperty("scheduleAt").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("suspendMode").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetJob_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + Response response = await client.GetJobAsync("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_GetJob_AllParameters_Async() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + Response response = await client.GetJobAsync("", new RequestContext()); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("channelReference").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("enqueuedAt").ToString()); + Console.WriteLine(result.GetProperty("channelId").ToString()); + Console.WriteLine(result.GetProperty("classificationPolicyId").ToString()); + Console.WriteLine(result.GetProperty("queueId").ToString()); + Console.WriteLine(result.GetProperty("priority").ToString()); + Console.WriteLine(result.GetProperty("dispositionCode").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("key").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expedite").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("requestedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("key").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("labelOperator").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("value").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAfterSeconds").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expedite").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("attachedWorkerSelectors")[0].GetProperty("expiresAt").ToString()); + Console.WriteLine(result.GetProperty("labels").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignmentId").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("workerId").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("assignedAt").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("completedAt").ToString()); + Console.WriteLine(result.GetProperty("assignments").GetProperty("").GetProperty("closedAt").ToString()); + Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("notes").GetProperty("").ToString()); + Console.WriteLine(result.GetProperty("scheduledAt").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("modeType").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("queueAndMatchMode").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("scheduleAndSuspendMode").GetProperty("scheduleAt").ToString()); + Console.WriteLine(result.GetProperty("matchingMode").GetProperty("suspendMode").ToString()); + } + } +} diff --git a/sdk/template/Azure.Template/tests/Generated/Samples/Samples_TemplateClient.cs b/sdk/template/Azure.Template/tests/Generated/Samples/Samples_TemplateClient.cs deleted file mode 100644 index 6131f8c3ac56..000000000000 --- a/sdk/template/Azure.Template/tests/Generated/Samples/Samples_TemplateClient.cs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text.Json; -using System.Threading.Tasks; -using Azure; -using Azure.Core; -using Azure.Identity; -using NUnit.Framework; - -namespace Azure.Template.Samples -{ - public class Samples_TemplateClient - { - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_GetSecret() - { - var credential = new DefaultAzureCredential(); - var client = new TemplateClient("", credential); - - Response response = client.GetSecret("", new RequestContext()); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result.ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_GetSecret_AllParameters() - { - var credential = new DefaultAzureCredential(); - var client = new TemplateClient("", credential); - - Response response = client.GetSecret("", new RequestContext()); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result.GetProperty("value").ToString()); - Console.WriteLine(result.GetProperty("id").ToString()); - Console.WriteLine(result.GetProperty("contentType").ToString()); - Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); - Console.WriteLine(result.GetProperty("kid").ToString()); - Console.WriteLine(result.GetProperty("managed").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_GetSecret_Async() - { - var credential = new DefaultAzureCredential(); - var client = new TemplateClient("", credential); - - Response response = await client.GetSecretAsync("", new RequestContext()); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result.ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_GetSecret_AllParameters_Async() - { - var credential = new DefaultAzureCredential(); - var client = new TemplateClient("", credential); - - Response response = await client.GetSecretAsync("", new RequestContext()); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result.GetProperty("value").ToString()); - Console.WriteLine(result.GetProperty("id").ToString()); - Console.WriteLine(result.GetProperty("contentType").ToString()); - Console.WriteLine(result.GetProperty("tags").GetProperty("").ToString()); - Console.WriteLine(result.GetProperty("kid").ToString()); - Console.WriteLine(result.GetProperty("managed").ToString()); - } - } -} diff --git a/sdk/template/Azure.Template/tests/TemplateClientTestEnvironment.cs b/sdk/template/Azure.Template/tests/JobRouterClientTestEnvironment.cs similarity index 91% rename from sdk/template/Azure.Template/tests/TemplateClientTestEnvironment.cs rename to sdk/template/Azure.Template/tests/JobRouterClientTestEnvironment.cs index 2fb75b1d747a..57812afd50d2 100644 --- a/sdk/template/Azure.Template/tests/TemplateClientTestEnvironment.cs +++ b/sdk/template/Azure.Template/tests/JobRouterClientTestEnvironment.cs @@ -5,7 +5,7 @@ namespace Azure.Template.Tests { - public class TemplateClientTestEnvironment : TestEnvironment + public class JobRouterClientTestEnvironment : TestEnvironment { public string KeyVaultUri => GetRecordedVariable("KEYVAULT_URL"); diff --git a/sdk/template/Azure.Template/tests/Samples/RouterJobModelSamples.cs b/sdk/template/Azure.Template/tests/Samples/RouterJobModelSamples.cs new file mode 100644 index 000000000000..252613fad76d --- /dev/null +++ b/sdk/template/Azure.Template/tests/Samples/RouterJobModelSamples.cs @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Communication.JobRouter.Models; +using Azure.Core; +using Azure.Core.Serialization; +using Azure.Identity; +using NUnit.Framework; + +namespace Azure.Communication.JobRouter.Samples +{ + public class RouterJobModelSamples + { + [Test] + public void RoundTripRouterJobSample_ProtocolMethods() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + Response response = client.GetJob("", new RequestContext()); + + dynamic routerJob = response.Content.ToDynamicFromJson(JsonPropertyNames.CamelCase); + Console.WriteLine($"Job ID: '{routerJob.Id}'."); + Console.WriteLine($"Channel ID: '{routerJob.ChannelId}'."); + + var patch = new + { + labels = new { + Some_Skill = 10 + } + }; + + // Sends JSON """{{"labels": {"Some_Skill": 10}}}""" + client.UpsertJob(routerJob.Id, RequestContent.Create(patch)); + } + + [Test] + public void RoundTripRouterJobSample_ProtocolMethods_DeleteLabel() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + Response response = client.GetJob("", new RequestContext()); + + dynamic routerJob = response.Content.ToDynamicFromJson(JsonPropertyNames.CamelCase); + Console.WriteLine($"Job ID: '{routerJob.Id}'."); + Console.WriteLine($"Channel ID: '{routerJob.ChannelId}'."); + + var patch = new + { + labels = new + { + Some_Skill = (object)null + } + }; + + // Sends JSON """{{"labels": {"Some_Skill": null}}}""" + client.UpsertJob(routerJob.Id, RequestContent.Create(patch)); + } + + [Test] + public void RoundTripRouterJobSample_ProtocolMethods_DeleteLabel_DynamicData() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + Response response = client.GetJob("", new RequestContext()); + + dynamic routerJob = response.Content.ToDynamicFromJson(JsonPropertyNames.CamelCase); + Console.WriteLine($"Job ID: '{routerJob.Id}'."); + Console.WriteLine($"Channel ID: '{routerJob.ChannelId}'."); + + routerJob.Labels["Some_Skill"] = null; + + // Sends JSON """{{"labels": {"Some_Skill": null}}}""" + client.UpsertJob(routerJob.Id, RequestContent.Create(routerJob, new ModelSerializerOptions("P"))); + } + + [Test] + public void RoundTripRouterJobSample_ConvenienceMethods() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + RouterJob routerJob = client.GetJob(""); + + Console.WriteLine($"Job ID: '{routerJob.Id}'."); + Console.WriteLine($"Channel ID: '{routerJob.ChannelId}'."); + + // Sends JSON """{{"labels": {"Some_Skill": 10}}}""" + routerJob.Labels["Some_Skill"] = 10; + + client.UpsertJob(routerJob); + } + + [Test] + public void RoundTripRouterJobSample_ConvenienceMethods_DeleteLabel() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + RouterJob routerJob = client.GetJob(""); + + Console.WriteLine($"Job ID: '{routerJob.Id}'."); + Console.WriteLine($"Channel ID: '{routerJob.ChannelId}'."); + + routerJob.Labels.Remove("Some_Skill"); + + // Sends JSON """{{"labels": {"Some_Skill": null}}}""" + client.UpsertJob(routerJob); + } + [Test] + public void PatchWithoutGetRouterJobSample_ProtocolMethods() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + var patch = new + { + labels = new + { + Some_Skill = 10 + } + }; + + // Sends JSON """{{"labels": {"Some_Skill": 10}}}""" + client.UpsertJob("", RequestContent.Create(patch)); + } + + [Test] + public void PatchWithoutGetRouterJobSample_ProtocolMethods_DeleteLabel() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + var patch = new + { + labels = new + { + Some_Skill = (object)null + } + }; + + // Sends JSON """{{"labels": {"Some_Skill": null}}}""" + client.UpsertJob("", RequestContent.Create(patch)); + } + + [Test] + public void PatchWithoutGetRouterJobSample_ConvenienceMethods() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + RouterJob routerJob = new RouterJob(""); + + // Sends JSON """{{"labels": {"Some_Skill": 10}}}""" + routerJob.Labels["Some_Skill"] = 10; + + client.UpsertJob(routerJob); + } + + [Test] + public void PatchWithoutGetRouterJobSample_ConvenienceMethods_DeleteLabel() + { + var credential = new DefaultAzureCredential(); + var client = new JobRouterClient("", credential); + + RouterJob routerJob = new RouterJob(""); + + routerJob.Labels.Remove("Some_Skill"); + + // Sends JSON """{{"labels": {"Some_Skill": null}}}""" + client.UpsertJob(routerJob); + } + } +} diff --git a/sdk/template/Azure.Template/tests/Samples/Sample1_HelloWorld.cs b/sdk/template/Azure.Template/tests/Samples/Sample1_HelloWorld.cs deleted file mode 100644 index 67be8a4caf7b..000000000000 --- a/sdk/template/Azure.Template/tests/Samples/Sample1_HelloWorld.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using Azure.Core; -using Azure.Core.TestFramework; -#region Snippet:Azure_Template -using Azure.Identity; -using Azure.Template.Models; -#endregion -using NUnit.Framework; - -namespace Azure.Template.Tests.Samples -{ - public partial class TemplateSamples: SamplesBase - { - [Test] - [SyncOnly] - public void GettingASecret() - { - #region Snippet:Azure_Template_GetSecret -#if SNIPPET - string endpoint = "https://myvault.vault.azure.net"; - var credential = new DefaultAzureCredential(); -#else - string endpoint = TestEnvironment.KeyVaultUri; - var credential = TestEnvironment.Credential; -#endif - var client = new TemplateClient(endpoint, credential); - - SecretBundle secret = client.GetSecretValue("TestSecret"); - - Console.WriteLine(secret.Value); - #endregion - - Assert.NotNull(secret.Value); - } - } -} diff --git a/sdk/template/Azure.Template/tests/Samples/Sample1_HelloWorldAsync.cs b/sdk/template/Azure.Template/tests/Samples/Sample1_HelloWorldAsync.cs deleted file mode 100644 index 3fb502e5e38f..000000000000 --- a/sdk/template/Azure.Template/tests/Samples/Sample1_HelloWorldAsync.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Threading.Tasks; -using Azure.Core; -using Azure.Core.TestFramework; -using Azure.Template.Models; -using NUnit.Framework; - -namespace Azure.Template.Tests.Samples -{ - public partial class TemplateSamples: SamplesBase - { - [Test] - [AsyncOnly] - public async Task GettingASecretAsync() - { - #region Snippet:Azure_Template_GetSecretAsync -#if SNIPPET - string endpoint = "https://myvault.vault.azure.net"; - var credential = new DefaultAzureCredential(); -#else - string endpoint = TestEnvironment.KeyVaultUri; - var credential = TestEnvironment.Credential; -#endif - var client = new TemplateClient(endpoint, credential); - - SecretBundle secret = await client.GetSecretValueAsync("TestSecret"); - - Console.WriteLine(secret.Value); - #endregion - - Assert.NotNull(secret.Value); - } - } -} diff --git a/sdk/template/Azure.Template/tests/SessionRecords/TemplateClientLiveTests/CanGetSecret.json b/sdk/template/Azure.Template/tests/SessionRecords/TemplateClientLiveTests/CanGetSecret.json deleted file mode 100644 index 90846a3af8d8..000000000000 --- a/sdk/template/Azure.Template/tests/SessionRecords/TemplateClientLiveTests/CanGetSecret.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://td6ee755a427d4cbd.vault.azure.net/secrets/TestSecret?api-version=7.0", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Authorization": "Sanitized", - "User-Agent": [ - "azsdk-net-Template/1.0.2-dev.20200824.4", - "(.NET Core 4.6.27514.02; Microsoft Windows 10.0.17763 )" - ], - "x-ms-client-request-id": "2d69f86bb5cd658959d538084efd6435", - "x-ms-return-client-request-id": "true" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Cache-Control": "no-cache", - "Content-Length": "230", - "Content-Type": "application/json; charset=utf-8", - "Date": "Mon, 24 Aug 2020 17:28:34 GMT", - "Expires": "-1", - "Pragma": "no-cache", - "Strict-Transport-Security": "max-age=31536000;includeSubDomains", - "X-AspNet-Version": "4.0.30319", - "X-Content-Type-Options": "nosniff", - "x-ms-keyvault-network-info": "conn_type=Ipv4;addr=52.188.205.173;act_addr_fam=InterNetwork;", - "x-ms-keyvault-region": "westus2", - "x-ms-keyvault-service-version": "1.1.44.0", - "x-ms-request-id": "336162b9-e626-49f9-9ff3-44ace416e108", - "X-Powered-By": "ASP.NET" - }, - "ResponseBody": { - "value": "Very secret value", - "id": "https://td6ee755a427d4cbd.vault.azure.net/secrets/TestSecret/a63ea68be4ec4148b0de05599a163b86", - "attributes": { - "enabled": true, - "created": 1598290014, - "updated": 1598290014, - "recoveryLevel": "Purgeable" - } - } - } - ], - "Variables": { - "KEYVAULT_URL": "https://td6ee755a427d4cbd.vault.azure.net", - "RandomSeed": "1523443367" - } -} \ No newline at end of file diff --git a/sdk/template/Azure.Template/tests/SessionRecords/TemplateClientLiveTests/CanGetSecretAsync.json b/sdk/template/Azure.Template/tests/SessionRecords/TemplateClientLiveTests/CanGetSecretAsync.json deleted file mode 100644 index c0048bce6853..000000000000 --- a/sdk/template/Azure.Template/tests/SessionRecords/TemplateClientLiveTests/CanGetSecretAsync.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://td6ee755a427d4cbd.vault.azure.net/secrets/TestSecret?api-version=7.0", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Authorization": "Sanitized", - "User-Agent": [ - "azsdk-net-Template/1.0.2-dev.20200824.4", - "(.NET Core 4.6.27514.02; Microsoft Windows 10.0.17763 )" - ], - "x-ms-client-request-id": "b41531fddad5df6f8a3bc26c53829105", - "x-ms-return-client-request-id": "true" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Cache-Control": "no-cache", - "Content-Length": "230", - "Content-Type": "application/json; charset=utf-8", - "Date": "Mon, 24 Aug 2020 17:28:34 GMT", - "Expires": "-1", - "Pragma": "no-cache", - "Strict-Transport-Security": "max-age=31536000;includeSubDomains", - "X-AspNet-Version": "4.0.30319", - "X-Content-Type-Options": "nosniff", - "x-ms-keyvault-network-info": "conn_type=Ipv4;addr=52.188.205.173;act_addr_fam=InterNetwork;", - "x-ms-keyvault-region": "westus2", - "x-ms-keyvault-service-version": "1.1.44.0", - "x-ms-request-id": "f4fdd9a6-9ddf-4ef5-8f2e-3c59cba16c2d", - "X-Powered-By": "ASP.NET" - }, - "ResponseBody": { - "value": "Very secret value", - "id": "https://td6ee755a427d4cbd.vault.azure.net/secrets/TestSecret/a63ea68be4ec4148b0de05599a163b86", - "attributes": { - "enabled": true, - "created": 1598290014, - "updated": 1598290014, - "recoveryLevel": "Purgeable" - } - } - } - ], - "Variables": { - "KEYVAULT_URL": "https://td6ee755a427d4cbd.vault.azure.net", - "RandomSeed": "2070406030" - } -} \ No newline at end of file diff --git a/sdk/template/Azure.Template/tests/TemplateClientLiveTests.cs b/sdk/template/Azure.Template/tests/TemplateClientLiveTests.cs deleted file mode 100644 index c3b9c332ba60..000000000000 --- a/sdk/template/Azure.Template/tests/TemplateClientLiveTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Threading.Tasks; -using Azure.Core.TestFramework; -using NUnit.Framework; -using Azure.Template.Models; - -namespace Azure.Template.Tests -{ - // When necessary, use the [ClientTestFixture] to test multiple versions. - // See https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/core/Azure.Core.TestFramework#support-multi-service-version-testing. - public class TemplateClientLiveTests: RecordedTestBase - { - public TemplateClientLiveTests(bool isAsync) - // Delete null and the opening comment to re-record, or change to debug live tests. - // You can also change eng/nunit.runsettings to set the TestMode parameter. - // See https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/core/Azure.Core.TestFramework#test-settings. - : base(isAsync, null /* RecordedTestMode.Record /* to re-record */) - { - } - - private TemplateClient CreateClient() - { - return InstrumentClient(new TemplateClient( - TestEnvironment.KeyVaultUri, - TestEnvironment.Credential, - InstrumentClientOptions(new TemplateClientOptions()) - )); - } - - [RecordedTest] - public async Task CanGetSecret() - { - TemplateClient client = CreateClient(); - - Response secret = await client.GetSecretValueAsync("TestSecret"); - - Assert.AreEqual("Very secret value", secret.Value.Value); - } - } -}