diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/Azure.ResourceManager.Contoso.sln b/sdk/contoso/Azure.ResourceManager.Contoso/Azure.ResourceManager.Contoso.sln new file mode 100644 index 000000000000..cb820959e5b2 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/Azure.ResourceManager.Contoso.sln @@ -0,0 +1,56 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.ResourceManager.Contoso.Samples", "samples\Azure.ResourceManager.Contoso.Samples.csproj", "{7A2DFF15-5746-49F4-BD0F-C6C35337088A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.ResourceManager.Contoso", "src\Azure.ResourceManager.Contoso.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.ResourceManager.Contoso.Tests", "tests\Azure.ResourceManager.Contoso.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + 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 + {7A2DFF15-5746-49F4-BD0F-C6C35337088A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7A2DFF15-5746-49F4-BD0F-C6C35337088A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7A2DFF15-5746-49F4-BD0F-C6C35337088A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7A2DFF15-5746-49F4-BD0F-C6C35337088A}.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 + {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 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A97F4B90-2591-4689-B1F8-5F21FE6D6CAE} + EndGlobalSection +EndGlobal diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/CHANGELOG.md b/sdk/contoso/Azure.ResourceManager.Contoso/CHANGELOG.md new file mode 100644 index 000000000000..8b33f0fedccc --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/CHANGELOG.md @@ -0,0 +1,11 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes \ No newline at end of file diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/Directory.Build.props b/sdk/contoso/Azure.ResourceManager.Contoso/Directory.Build.props new file mode 100644 index 000000000000..63bd836ad44b --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/Directory.Build.props @@ -0,0 +1,6 @@ + + + + diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/README.md b/sdk/contoso/Azure.ResourceManager.Contoso/README.md new file mode 100644 index 000000000000..78ea67f6bbf0 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/README.md @@ -0,0 +1,80 @@ +# Microsoft Azure Contoso management client library for .NET + +**[Describe the service briefly first.]** + +This library follows the [new Azure SDK guidelines](https://azure.github.io/azure-sdk/general_introduction.html), and provides many core capabilities: + + - Support MSAL.NET, Azure.Identity is out of box for supporting MSAL.NET. + - Support [OpenTelemetry](https://opentelemetry.io/) for distributed tracing. + - HTTP pipeline with custom policies. + - Better error-handling. + - Support uniform telemetry across all languages. + +## Getting started + +### Install the package + +Install the Microsoft Azure Contoso management library for .NET with [NuGet](https://www.nuget.org/): + +```dotnetcli +dotnet add package Azure.ResourceManager.Contoso --prerelease +``` + +### Prerequisites + +* You must have an [Microsoft Azure subscription](https://azure.microsoft.com/free/dotnet/). + +### Authenticate the Client + +To create an authenticated client and start interacting with Microsoft Azure resources, see the [quickstart guide here](https://github.com/Azure/azure-sdk-for-net/blob/main/doc/dev/mgmt_quickstart.md). + +## Key concepts + +Key concepts of the Microsoft Azure SDK for .NET can be found [here](https://azure.github.io/azure-sdk/dotnet_introduction.html) + +## Documentation + +Documentation is available to help you learn how to use this package: + +- [Quickstart](https://github.com/Azure/azure-sdk-for-net/blob/main/doc/dev/mgmt_quickstart.md). +- [API References](https://learn.microsoft.com/dotnet/api/?view=azure-dotnet). +- [Authentication](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/README.md). + +## Examples + +Code samples for using the management library for .NET can be found in the following locations +- [.NET Management Library Code Samples](https://aka.ms/azuresdk-net-mgmt-samples) + +## Troubleshooting + +- File an issue via [GitHub Issues](https://github.com/Azure/azure-sdk-for-net/issues). +- Check [previous questions](https://stackoverflow.com/questions/tagged/azure+.net) or ask new ones on Stack Overflow using Azure and .NET tags. + +## Next steps + +For more information about Microsoft Azure SDK, see [this website](https://azure.github.io/azure-sdk/). + +## Contributing + +For details on contributing to this repository, see the [contributing +guide][cg]. + +This project welcomes contributions and suggestions. Most contributions +require you to agree to a Contributor License Agreement (CLA) declaring +that you have the right to, and actually do, grant us the rights to use +your contribution. For details, visit . + +When you submit a pull request, a CLA-bot will automatically determine +whether you need to provide a CLA and decorate the PR appropriately +(for example, label, comment). Follow the instructions provided by the +bot. You'll only need to do this action once across all repositories +using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For +more information, see the [Code of Conduct FAQ][coc_faq] or contact + with any other questions or comments. + + +[cg]: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/resourcemanager/Azure.ResourceManager/docs/CONTRIBUTING.md +[coc]: https://opensource.microsoft.com/codeofconduct/ +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ \ No newline at end of file diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/api/Azure.ResourceManager.Contoso.net8.0.cs b/sdk/contoso/Azure.ResourceManager.Contoso/api/Azure.ResourceManager.Contoso.net8.0.cs new file mode 100644 index 000000000000..e066d059b9ab --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/api/Azure.ResourceManager.Contoso.net8.0.cs @@ -0,0 +1,131 @@ +namespace Azure.ResourceManager.Contoso +{ + public static partial class ContosoExtensions + { + public static Azure.Response GetEmployee(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource, string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public static System.Threading.Tasks.Task> GetEmployeeAsync(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource, string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public static Azure.ResourceManager.Contoso.EmployeeResource GetEmployeeResource(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } + public static Azure.ResourceManager.Contoso.EmployeeCollection GetEmployees(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource) { throw null; } + public static Azure.Pageable GetEmployees(this Azure.ResourceManager.Resources.SubscriptionResource subscriptionResource, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public static Azure.AsyncPageable GetEmployeesAsync(this Azure.ResourceManager.Resources.SubscriptionResource subscriptionResource, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + } + public partial class EmployeeCollection : Azure.ResourceManager.ArmCollection, System.Collections.Generic.IAsyncEnumerable, System.Collections.Generic.IEnumerable, System.Collections.IEnumerable + { + protected EmployeeCollection() { } + public virtual Azure.ResourceManager.ArmOperation CreateOrUpdate(Azure.WaitUntil waitUntil, string employeeName, Azure.ResourceManager.Contoso.EmployeeData data, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> CreateOrUpdateAsync(Azure.WaitUntil waitUntil, string employeeName, Azure.ResourceManager.Contoso.EmployeeData data, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Exists(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> ExistsAsync(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Get(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Pageable GetAll(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.AsyncPageable GetAllAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> GetAsync(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.NullableResponse GetIfExists(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> GetIfExistsAsync(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + System.Collections.Generic.IAsyncEnumerator System.Collections.Generic.IAsyncEnumerable.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } + System.Collections.Generic.IEnumerator System.Collections.Generic.IEnumerable.GetEnumerator() { throw null; } + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } + } + public partial class EmployeeData : Azure.ResourceManager.Models.TrackedResourceData, System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public EmployeeData(Azure.Core.AzureLocation location) { } + public Azure.ResourceManager.Contoso.Models.EmployeeProperties Properties { get { throw null; } set { } } + protected override void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Contoso.EmployeeData System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Contoso.EmployeeData System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class EmployeeResource : Azure.ResourceManager.ArmResource, System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public static readonly Azure.Core.ResourceType ResourceType; + protected EmployeeResource() { } + public virtual Azure.ResourceManager.Contoso.EmployeeData Data { get { throw null; } } + public virtual bool HasData { get { throw null; } } + public virtual Azure.Response AddTag(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> AddTagAsync(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string employeeName) { throw null; } + public virtual Azure.ResourceManager.ArmOperation Delete(Azure.WaitUntil waitUntil, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task DeleteAsync(Azure.WaitUntil waitUntil, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response RemoveTag(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> RemoveTagAsync(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response SetTags(System.Collections.Generic.IDictionary tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> SetTagsAsync(System.Collections.Generic.IDictionary tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + Azure.ResourceManager.Contoso.EmployeeData System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Contoso.EmployeeData System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + public virtual Azure.Response Update(Azure.ResourceManager.Contoso.EmployeeData data, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> UpdateAsync(Azure.ResourceManager.Contoso.EmployeeData data, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + } +} +namespace Azure.ResourceManager.Contoso.Mocking +{ + public partial class MockableContosoArmClient : Azure.ResourceManager.ArmResource + { + protected MockableContosoArmClient() { } + public virtual Azure.ResourceManager.Contoso.EmployeeResource GetEmployeeResource(Azure.Core.ResourceIdentifier id) { throw null; } + } + public partial class MockableContosoResourceGroupResource : Azure.ResourceManager.ArmResource + { + protected MockableContosoResourceGroupResource() { } + public virtual Azure.Response GetEmployee(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> GetEmployeeAsync(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.ResourceManager.Contoso.EmployeeCollection GetEmployees() { throw null; } + } + public partial class MockableContosoSubscriptionResource : Azure.ResourceManager.ArmResource + { + protected MockableContosoSubscriptionResource() { } + public virtual Azure.Pageable GetEmployees(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.AsyncPageable GetEmployeesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + } +} +namespace Azure.ResourceManager.Contoso.Models +{ + public static partial class ArmContosoModelFactory + { + public static Azure.ResourceManager.Contoso.EmployeeData EmployeeData(Azure.Core.ResourceIdentifier id = null, string name = null, Azure.Core.ResourceType resourceType = default(Azure.Core.ResourceType), Azure.ResourceManager.Models.SystemData systemData = null, System.Collections.Generic.IDictionary tags = null, Azure.Core.AzureLocation location = default(Azure.Core.AzureLocation), Azure.ResourceManager.Contoso.Models.EmployeeProperties properties = null) { throw null; } + public static Azure.ResourceManager.Contoso.Models.EmployeeProperties EmployeeProperties(int? age = default(int?), string city = null, byte[] profile = null, Azure.ResourceManager.Contoso.Models.ProvisioningState? provisioningState = default(Azure.ResourceManager.Contoso.Models.ProvisioningState?)) { throw null; } + } + public partial class EmployeeProperties : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public EmployeeProperties() { } + public int? Age { get { throw null; } set { } } + public string City { get { throw null; } set { } } + public byte[] Profile { get { throw null; } set { } } + public Azure.ResourceManager.Contoso.Models.ProvisioningState? ProvisioningState { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Contoso.Models.EmployeeProperties System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Contoso.Models.EmployeeProperties System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct ProvisioningState : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public ProvisioningState(string value) { throw null; } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Accepted { get { throw null; } } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Canceled { get { throw null; } } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Deleting { get { throw null; } } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Failed { get { throw null; } } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Provisioning { get { throw null; } } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Succeeded { get { throw null; } } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Updating { get { throw null; } } + public bool Equals(Azure.ResourceManager.Contoso.Models.ProvisioningState 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.ResourceManager.Contoso.Models.ProvisioningState left, Azure.ResourceManager.Contoso.Models.ProvisioningState right) { throw null; } + public static implicit operator Azure.ResourceManager.Contoso.Models.ProvisioningState (string value) { throw null; } + public static bool operator !=(Azure.ResourceManager.Contoso.Models.ProvisioningState left, Azure.ResourceManager.Contoso.Models.ProvisioningState right) { throw null; } + public override string ToString() { throw null; } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/api/Azure.ResourceManager.Contoso.netstandard2.0.cs b/sdk/contoso/Azure.ResourceManager.Contoso/api/Azure.ResourceManager.Contoso.netstandard2.0.cs new file mode 100644 index 000000000000..e066d059b9ab --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/api/Azure.ResourceManager.Contoso.netstandard2.0.cs @@ -0,0 +1,131 @@ +namespace Azure.ResourceManager.Contoso +{ + public static partial class ContosoExtensions + { + public static Azure.Response GetEmployee(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource, string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public static System.Threading.Tasks.Task> GetEmployeeAsync(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource, string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public static Azure.ResourceManager.Contoso.EmployeeResource GetEmployeeResource(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } + public static Azure.ResourceManager.Contoso.EmployeeCollection GetEmployees(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource) { throw null; } + public static Azure.Pageable GetEmployees(this Azure.ResourceManager.Resources.SubscriptionResource subscriptionResource, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public static Azure.AsyncPageable GetEmployeesAsync(this Azure.ResourceManager.Resources.SubscriptionResource subscriptionResource, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + } + public partial class EmployeeCollection : Azure.ResourceManager.ArmCollection, System.Collections.Generic.IAsyncEnumerable, System.Collections.Generic.IEnumerable, System.Collections.IEnumerable + { + protected EmployeeCollection() { } + public virtual Azure.ResourceManager.ArmOperation CreateOrUpdate(Azure.WaitUntil waitUntil, string employeeName, Azure.ResourceManager.Contoso.EmployeeData data, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> CreateOrUpdateAsync(Azure.WaitUntil waitUntil, string employeeName, Azure.ResourceManager.Contoso.EmployeeData data, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Exists(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> ExistsAsync(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Get(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Pageable GetAll(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.AsyncPageable GetAllAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> GetAsync(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.NullableResponse GetIfExists(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> GetIfExistsAsync(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + System.Collections.Generic.IAsyncEnumerator System.Collections.Generic.IAsyncEnumerable.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } + System.Collections.Generic.IEnumerator System.Collections.Generic.IEnumerable.GetEnumerator() { throw null; } + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } + } + public partial class EmployeeData : Azure.ResourceManager.Models.TrackedResourceData, System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public EmployeeData(Azure.Core.AzureLocation location) { } + public Azure.ResourceManager.Contoso.Models.EmployeeProperties Properties { get { throw null; } set { } } + protected override void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Contoso.EmployeeData System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Contoso.EmployeeData System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class EmployeeResource : Azure.ResourceManager.ArmResource, System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public static readonly Azure.Core.ResourceType ResourceType; + protected EmployeeResource() { } + public virtual Azure.ResourceManager.Contoso.EmployeeData Data { get { throw null; } } + public virtual bool HasData { get { throw null; } } + public virtual Azure.Response AddTag(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> AddTagAsync(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string employeeName) { throw null; } + public virtual Azure.ResourceManager.ArmOperation Delete(Azure.WaitUntil waitUntil, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task DeleteAsync(Azure.WaitUntil waitUntil, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response RemoveTag(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> RemoveTagAsync(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response SetTags(System.Collections.Generic.IDictionary tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> SetTagsAsync(System.Collections.Generic.IDictionary tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + Azure.ResourceManager.Contoso.EmployeeData System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Contoso.EmployeeData System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + public virtual Azure.Response Update(Azure.ResourceManager.Contoso.EmployeeData data, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> UpdateAsync(Azure.ResourceManager.Contoso.EmployeeData data, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + } +} +namespace Azure.ResourceManager.Contoso.Mocking +{ + public partial class MockableContosoArmClient : Azure.ResourceManager.ArmResource + { + protected MockableContosoArmClient() { } + public virtual Azure.ResourceManager.Contoso.EmployeeResource GetEmployeeResource(Azure.Core.ResourceIdentifier id) { throw null; } + } + public partial class MockableContosoResourceGroupResource : Azure.ResourceManager.ArmResource + { + protected MockableContosoResourceGroupResource() { } + public virtual Azure.Response GetEmployee(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> GetEmployeeAsync(string employeeName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.ResourceManager.Contoso.EmployeeCollection GetEmployees() { throw null; } + } + public partial class MockableContosoSubscriptionResource : Azure.ResourceManager.ArmResource + { + protected MockableContosoSubscriptionResource() { } + public virtual Azure.Pageable GetEmployees(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.AsyncPageable GetEmployeesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + } +} +namespace Azure.ResourceManager.Contoso.Models +{ + public static partial class ArmContosoModelFactory + { + public static Azure.ResourceManager.Contoso.EmployeeData EmployeeData(Azure.Core.ResourceIdentifier id = null, string name = null, Azure.Core.ResourceType resourceType = default(Azure.Core.ResourceType), Azure.ResourceManager.Models.SystemData systemData = null, System.Collections.Generic.IDictionary tags = null, Azure.Core.AzureLocation location = default(Azure.Core.AzureLocation), Azure.ResourceManager.Contoso.Models.EmployeeProperties properties = null) { throw null; } + public static Azure.ResourceManager.Contoso.Models.EmployeeProperties EmployeeProperties(int? age = default(int?), string city = null, byte[] profile = null, Azure.ResourceManager.Contoso.Models.ProvisioningState? provisioningState = default(Azure.ResourceManager.Contoso.Models.ProvisioningState?)) { throw null; } + } + public partial class EmployeeProperties : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public EmployeeProperties() { } + public int? Age { get { throw null; } set { } } + public string City { get { throw null; } set { } } + public byte[] Profile { get { throw null; } set { } } + public Azure.ResourceManager.Contoso.Models.ProvisioningState? ProvisioningState { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Contoso.Models.EmployeeProperties System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.ResourceManager.Contoso.Models.EmployeeProperties System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct ProvisioningState : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public ProvisioningState(string value) { throw null; } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Accepted { get { throw null; } } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Canceled { get { throw null; } } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Deleting { get { throw null; } } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Failed { get { throw null; } } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Provisioning { get { throw null; } } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Succeeded { get { throw null; } } + public static Azure.ResourceManager.Contoso.Models.ProvisioningState Updating { get { throw null; } } + public bool Equals(Azure.ResourceManager.Contoso.Models.ProvisioningState 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.ResourceManager.Contoso.Models.ProvisioningState left, Azure.ResourceManager.Contoso.Models.ProvisioningState right) { throw null; } + public static implicit operator Azure.ResourceManager.Contoso.Models.ProvisioningState (string value) { throw null; } + public static bool operator !=(Azure.ResourceManager.Contoso.Models.ProvisioningState left, Azure.ResourceManager.Contoso.Models.ProvisioningState right) { throw null; } + public override string ToString() { throw null; } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/assets.json b/sdk/contoso/Azure.ResourceManager.Contoso/assets.json new file mode 100644 index 000000000000..ed7bbd7af63d --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/assets.json @@ -0,0 +1,7 @@ + +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "net", + "TagPrefix": "net/contoso/Azure.ResourceManager.Contoso", + "Tag": "" +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/samples/Azure.ResourceManager.Contoso.Samples.csproj b/sdk/contoso/Azure.ResourceManager.Contoso/samples/Azure.ResourceManager.Contoso.Samples.csproj new file mode 100644 index 000000000000..e1423e416b0f --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/samples/Azure.ResourceManager.Contoso.Samples.csproj @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/samples/Generated/Samples/Sample_EmployeeCollection.cs b/sdk/contoso/Azure.ResourceManager.Contoso/samples/Generated/Samples/Sample_EmployeeCollection.cs new file mode 100644 index 000000000000..5d6930e24057 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/samples/Generated/Samples/Sample_EmployeeCollection.cs @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using Azure.ResourceManager.Contoso.Models; +using Azure.ResourceManager.Resources; +using NUnit.Framework; + +namespace Azure.ResourceManager.Contoso.Samples +{ + public partial class Sample_EmployeeCollection + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task CreateOrUpdate_EmployeesCreateOrUpdate() + { + // Generated from example definition: 2021-11-01/Employees_CreateOrUpdate.json + // this example is just showing the usage of "Employee_CreateOrUpdate" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this ResourceGroupResource created on azure + // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource + string subscriptionId = "11809CA1-E126-4017-945E-AA795CD5C5A9"; + string resourceGroupName = "rgopenapi"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this EmployeeResource + EmployeeCollection collection = resourceGroupResource.GetEmployees(); + + // invoke the operation + string employeeName = "9KF-f-8b"; + EmployeeData data = new EmployeeData(new AzureLocation("itajgxyqozseoygnl")) + { + Properties = new EmployeeProperties + { + Age = 30, + City = "gydhnntudughbmxlkyzrskcdkotrxn", + Profile = Encoding.UTF8.GetBytes("ms"), + }, + Tags = +{ +["key2913"] = "urperxmkkhhkp" +}, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, employeeName, data); + EmployeeResource result = lro.Value; + + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + EmployeeData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Get_EmployeesGet() + { + // Generated from example definition: 2021-11-01/Employees_Get.json + // this example is just showing the usage of "Employee_Get" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this ResourceGroupResource created on azure + // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource + string subscriptionId = "11809CA1-E126-4017-945E-AA795CD5C5A9"; + string resourceGroupName = "rgopenapi"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this EmployeeResource + EmployeeCollection collection = resourceGroupResource.GetEmployees(); + + // invoke the operation + string employeeName = "le-8MU--J3W6q8D386p3-iT3"; + EmployeeResource result = await collection.GetAsync(employeeName); + + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + EmployeeData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetAll_EmployeesListByResourceGroup() + { + // Generated from example definition: 2021-11-01/Employees_ListByResourceGroup.json + // this example is just showing the usage of "Employee_ListByResourceGroup" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this ResourceGroupResource created on azure + // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource + string subscriptionId = "11809CA1-E126-4017-945E-AA795CD5C5A9"; + string resourceGroupName = "rgopenapi"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this EmployeeResource + EmployeeCollection collection = resourceGroupResource.GetEmployees(); + + // invoke the operation and iterate over the result + await foreach (EmployeeResource item in collection.GetAllAsync()) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + EmployeeData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + + Console.WriteLine("Succeeded"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Exists_EmployeesGet() + { + // Generated from example definition: 2021-11-01/Employees_Get.json + // this example is just showing the usage of "Employee_Get" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this ResourceGroupResource created on azure + // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource + string subscriptionId = "11809CA1-E126-4017-945E-AA795CD5C5A9"; + string resourceGroupName = "rgopenapi"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this EmployeeResource + EmployeeCollection collection = resourceGroupResource.GetEmployees(); + + // invoke the operation + string employeeName = "le-8MU--J3W6q8D386p3-iT3"; + bool result = await collection.ExistsAsync(employeeName); + + Console.WriteLine($"Succeeded: {result}"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetIfExists_EmployeesGet() + { + // Generated from example definition: 2021-11-01/Employees_Get.json + // this example is just showing the usage of "Employee_Get" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this ResourceGroupResource created on azure + // for more information of creating ResourceGroupResource, please refer to the document of ResourceGroupResource + string subscriptionId = "11809CA1-E126-4017-945E-AA795CD5C5A9"; + string resourceGroupName = "rgopenapi"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this EmployeeResource + EmployeeCollection collection = resourceGroupResource.GetEmployees(); + + // invoke the operation + string employeeName = "le-8MU--J3W6q8D386p3-iT3"; + NullableResponse response = await collection.GetIfExistsAsync(employeeName); + EmployeeResource result = response.HasValue ? response.Value : null; + + if (result == null) + { + Console.WriteLine("Succeeded with null as result"); + } + else + { + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + EmployeeData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/samples/Generated/Samples/Sample_EmployeeResource.cs b/sdk/contoso/Azure.ResourceManager.Contoso/samples/Generated/Samples/Sample_EmployeeResource.cs new file mode 100644 index 000000000000..da147009f1d0 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/samples/Generated/Samples/Sample_EmployeeResource.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using Azure.ResourceManager.Contoso.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.Contoso.Samples +{ + public partial class Sample_EmployeeResource + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Get_EmployeesGet() + { + // Generated from example definition: 2021-11-01/Employees_Get.json + // this example is just showing the usage of "Employee_Get" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this EmployeeResource created on azure + // for more information of creating EmployeeResource, please refer to the document of EmployeeResource + string subscriptionId = "11809CA1-E126-4017-945E-AA795CD5C5A9"; + string resourceGroupName = "rgopenapi"; + string employeeName = "le-8MU--J3W6q8D386p3-iT3"; + ResourceIdentifier employeeResourceId = EmployeeResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, employeeName); + EmployeeResource employee = client.GetEmployeeResource(employeeResourceId); + + // invoke the operation + EmployeeResource result = await employee.GetAsync(); + + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + EmployeeData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Delete_EmployeesDelete() + { + // Generated from example definition: 2021-11-01/Employees_Delete.json + // this example is just showing the usage of "Employee_Delete" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this EmployeeResource created on azure + // for more information of creating EmployeeResource, please refer to the document of EmployeeResource + string subscriptionId = "11809CA1-E126-4017-945E-AA795CD5C5A9"; + string resourceGroupName = "rgopenapi"; + string employeeName = "5vX--BxSu3ux48rI4O9OQ569"; + ResourceIdentifier employeeResourceId = EmployeeResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, employeeName); + EmployeeResource employee = client.GetEmployeeResource(employeeResourceId); + + // invoke the operation + await employee.DeleteAsync(WaitUntil.Completed); + + Console.WriteLine("Succeeded"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Update_EmployeesUpdate() + { + // Generated from example definition: 2021-11-01/Employees_Update.json + // this example is just showing the usage of "Employee_Update" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this EmployeeResource created on azure + // for more information of creating EmployeeResource, please refer to the document of EmployeeResource + string subscriptionId = "11809CA1-E126-4017-945E-AA795CD5C5A9"; + string resourceGroupName = "rgopenapi"; + string employeeName = "-XhyNJ--"; + ResourceIdentifier employeeResourceId = EmployeeResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, employeeName); + EmployeeResource employee = client.GetEmployeeResource(employeeResourceId); + + // invoke the operation + EmployeeData data = new EmployeeData(default) + { + Properties = new EmployeeProperties + { + Age = 24, + City = "uyfg", + Profile = Encoding.UTF8.GetBytes("oapgijcswfkruiuuzbwco"), + }, + Tags = +{ +["key7952"] = "no" +}, + }; + EmployeeResource result = await employee.UpdateAsync(data); + + // the variable result is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + EmployeeData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/samples/Generated/Samples/Sample_SubscriptionResourceExtensions.cs b/sdk/contoso/Azure.ResourceManager.Contoso/samples/Generated/Samples/Sample_SubscriptionResourceExtensions.cs new file mode 100644 index 000000000000..62db2b6f5e75 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/samples/Generated/Samples/Sample_SubscriptionResourceExtensions.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using Azure.ResourceManager.Resources; +using NUnit.Framework; + +namespace Azure.ResourceManager.Contoso.Samples +{ + public partial class Sample_SubscriptionResourceExtensions + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetEmployees_EmployeesListBySubscription() + { + // Generated from example definition: 2021-11-01/Employees_ListBySubscription.json + // this example is just showing the usage of "Employee_ListBySubscription" operation, for the dependent resources, they will have to be created separately. + + // get your azure access token, for more details of how Azure SDK get your access token, please refer to https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication?tabs=command-line + TokenCredential cred = new DefaultAzureCredential(); + // authenticate your client + ArmClient client = new ArmClient(cred); + + // this example assumes you already have this SubscriptionResource created on azure + // for more information of creating SubscriptionResource, please refer to the document of SubscriptionResource + string subscriptionId = "11809CA1-E126-4017-945E-AA795CD5C5A9"; + ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); + SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); + + // invoke the operation and iterate over the result + await foreach (EmployeeResource item in subscriptionResource.GetEmployeesAsync()) + { + // the variable item is a resource, you could call other operations on this instance as well + // but just for demo, we get its data from this resource instance + EmployeeData resourceData = item.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + + Console.WriteLine("Succeeded"); + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Azure.ResourceManager.Contoso.csproj b/sdk/contoso/Azure.ResourceManager.Contoso/src/Azure.ResourceManager.Contoso.csproj new file mode 100644 index 000000000000..2755628805d0 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Azure.ResourceManager.Contoso.csproj @@ -0,0 +1,8 @@ + + + Azure Resource Manager client SDK for Azure resource provider Contoso. + 1.0.0-beta.1 + azure;management;arm;resource manager;contoso + Azure.ResourceManager.Contoso + + diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/ArmContosoModelFactory.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/ArmContosoModelFactory.cs new file mode 100644 index 000000000000..836b121b3967 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/ArmContosoModelFactory.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure.Core; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.Contoso.Models +{ + /// Model factory for models. + public static partial class ArmContosoModelFactory + { + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// The tags. + /// The location. + /// The resource-specific properties for this resource. + /// A new instance for mocking. + public static EmployeeData EmployeeData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, IDictionary tags = null, AzureLocation location = default, EmployeeProperties properties = null) + { + tags ??= new Dictionary(); + + return new EmployeeData( + id, + name, + resourceType, + systemData, + tags, + location, + properties, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Age of employee. + /// City of employee. + /// Profile of employee. + /// The status of the last operation. + /// A new instance for mocking. + public static EmployeeProperties EmployeeProperties(int? age = null, string city = null, byte[] profile = null, ProvisioningState? provisioningState = null) + { + return new EmployeeProperties(age, city, profile, provisioningState, serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeCollection.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeCollection.cs new file mode 100644 index 000000000000..6fead5174202 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeCollection.cs @@ -0,0 +1,494 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Autorest.CSharp.Core; +using Azure.Core; +using Azure.Core.Pipeline; +using Azure.ResourceManager.Resources; + +namespace Azure.ResourceManager.Contoso +{ + /// + /// A class representing a collection of and their operations. + /// Each in the collection will belong to the same instance of . + /// To get an instance call the GetEmployees method from an instance of . + /// + public partial class EmployeeCollection : ArmCollection, IEnumerable, IAsyncEnumerable + { + private readonly ClientDiagnostics _employeeClientDiagnostics; + private readonly EmployeesRestOperations _employeeRestClient; + + /// Initializes a new instance of the class for mocking. + protected EmployeeCollection() + { + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The identifier of the parent resource that is the target of operations. + internal EmployeeCollection(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _employeeClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Contoso", EmployeeResource.ResourceType.Namespace, Diagnostics); + TryGetApiVersion(EmployeeResource.ResourceType, out string employeeApiVersion); + _employeeRestClient = new EmployeesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, employeeApiVersion); +#if DEBUG + ValidateResourceId(Id); +#endif + } + + internal static void ValidateResourceId(ResourceIdentifier id) + { + if (id.ResourceType != ResourceGroupResource.ResourceType) + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceGroupResource.ResourceType), nameof(id)); + } + + /// + /// Create a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The name of the Employee. + /// Resource create parameters. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// or is null. + public virtual async Task> CreateOrUpdateAsync(WaitUntil waitUntil, string employeeName, EmployeeData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = await _employeeRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, employeeName, data, cancellationToken).ConfigureAwait(false); + var operation = new ContosoArmOperation(new EmployeeOperationSource(Client), _employeeClientDiagnostics, Pipeline, _employeeRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, employeeName, data).Request, response, OperationFinalStateVia.AzureAsyncOperation); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The name of the Employee. + /// Resource create parameters. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// or is null. + public virtual ArmOperation CreateOrUpdate(WaitUntil waitUntil, string employeeName, EmployeeData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = _employeeRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, employeeName, data, cancellationToken); + var operation = new ContosoArmOperation(new EmployeeOperationSource(Client), _employeeClientDiagnostics, Pipeline, _employeeRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, employeeName, data).Request, response, OperationFinalStateVia.AzureAsyncOperation); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The name of the Employee. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetAsync(string employeeName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeCollection.Get"); + scope.Start(); + try + { + var response = await _employeeRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, employeeName, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new EmployeeResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The name of the Employee. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Get(string employeeName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeCollection.Get"); + scope.Start(); + try + { + var response = _employeeRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, employeeName, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new EmployeeResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// List Employee resources by resource group + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees + /// + /// + /// Operation Id + /// Employee_ListByResourceGroup + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + /// An async collection of that may take multiple service requests to iterate over. + public virtual AsyncPageable GetAllAsync(CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => _employeeRestClient.CreateListByResourceGroupRequest(Id.SubscriptionId, Id.ResourceGroupName); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _employeeRestClient.CreateListByResourceGroupNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new EmployeeResource(Client, EmployeeData.DeserializeEmployeeData(e)), _employeeClientDiagnostics, Pipeline, "EmployeeCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// List Employee resources by resource group + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees + /// + /// + /// Operation Id + /// Employee_ListByResourceGroup + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + /// A collection of that may take multiple service requests to iterate over. + public virtual Pageable GetAll(CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => _employeeRestClient.CreateListByResourceGroupRequest(Id.SubscriptionId, Id.ResourceGroupName); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _employeeRestClient.CreateListByResourceGroupNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new EmployeeResource(Client, EmployeeData.DeserializeEmployeeData(e)), _employeeClientDiagnostics, Pipeline, "EmployeeCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// Checks to see if the resource exists in azure. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The name of the Employee. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> ExistsAsync(string employeeName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeCollection.Exists"); + scope.Start(); + try + { + var response = await _employeeRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, employeeName, cancellationToken: cancellationToken).ConfigureAwait(false); + return Response.FromValue(response.Value != null, response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Checks to see if the resource exists in azure. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The name of the Employee. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Exists(string employeeName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeCollection.Exists"); + scope.Start(); + try + { + var response = _employeeRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, employeeName, cancellationToken: cancellationToken); + return Response.FromValue(response.Value != null, response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Tries to get details for this resource from the service. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The name of the Employee. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetIfExistsAsync(string employeeName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeCollection.GetIfExists"); + scope.Start(); + try + { + var response = await _employeeRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, employeeName, cancellationToken: cancellationToken).ConfigureAwait(false); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new EmployeeResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Tries to get details for this resource from the service. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The name of the Employee. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual NullableResponse GetIfExists(string employeeName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeCollection.GetIfExists"); + scope.Start(); + try + { + var response = _employeeRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, employeeName, cancellationToken: cancellationToken); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new EmployeeResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetAll().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetAll().GetEnumerator(); + } + + IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) + { + return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeData.Serialization.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeData.Serialization.cs new file mode 100644 index 000000000000..6f63d6c28ea4 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeData.Serialization.cs @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; +using Azure.ResourceManager.Contoso.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.Contoso +{ + public partial class EmployeeData : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EmployeeData)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Properties)) + { + writer.WritePropertyName("properties"u8); + writer.WriteObjectValue(Properties, options); + } + } + + EmployeeData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EmployeeData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEmployeeData(document.RootElement, options); + } + + internal static EmployeeData DeserializeEmployeeData(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + EmployeeProperties properties = default; + IDictionary tags = default; + AzureLocation location = default; + ResourceIdentifier id = default; + string name = default; + ResourceType type = default; + SystemData systemData = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + properties = EmployeeProperties.DeserializeEmployeeProperties(property.Value, options); + continue; + } + if (property.NameEquals("tags"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()); + } + tags = dictionary; + continue; + } + if (property.NameEquals("location"u8)) + { + location = new AzureLocation(property.Value.GetString()); + continue; + } + if (property.NameEquals("id"u8)) + { + id = new ResourceIdentifier(property.Value.GetString()); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new ResourceType(property.Value.GetString()); + continue; + } + if (property.NameEquals("systemData"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + systemData = JsonSerializer.Deserialize(property.Value.GetRawText()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EmployeeData( + id, + name, + type, + systemData, + tags ?? new ChangeTrackingDictionary(), + location, + properties, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(EmployeeData)} does not support writing '{options.Format}' format."); + } + } + + EmployeeData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEmployeeData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EmployeeData)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeData.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeData.cs new file mode 100644 index 000000000000..081bdf1fe2c7 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeData.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure.Core; +using Azure.ResourceManager.Contoso.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.Contoso +{ + /// + /// A class representing the Employee data model. + /// Employee resource + /// + public partial class EmployeeData : TrackedResourceData + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The location. + public EmployeeData(AzureLocation location) : base(location) + { + } + + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// The tags. + /// The location. + /// The resource-specific properties for this resource. + /// Keeps track of any properties unknown to the library. + internal EmployeeData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary tags, AzureLocation location, EmployeeProperties properties, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData, tags, location) + { + Properties = properties; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal EmployeeData() + { + } + + /// The resource-specific properties for this resource. + public EmployeeProperties Properties { get; set; } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeResource.Serialization.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeResource.Serialization.cs new file mode 100644 index 000000000000..9ba6d75f170e --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeResource.Serialization.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; + +namespace Azure.ResourceManager.Contoso +{ + public partial class EmployeeResource : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); + + EmployeeData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)Data).Create(ref reader, options); + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options); + + EmployeeData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options); + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)Data).GetFormatFromOptions(options); + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeResource.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeResource.cs new file mode 100644 index 000000000000..d09c19428c4c --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/EmployeeResource.cs @@ -0,0 +1,698 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; +using Azure.ResourceManager.Resources; + +namespace Azure.ResourceManager.Contoso +{ + /// + /// A Class representing an Employee along with the instance operations that can be performed on it. + /// If you have a you can construct an + /// from an instance of using the GetEmployeeResource method. + /// Otherwise you can get one from its parent resource using the GetEmployee method. + /// + public partial class EmployeeResource : ArmResource + { + /// Generate the resource identifier of a instance. + /// The subscriptionId. + /// The resourceGroupName. + /// The employeeName. + public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string employeeName) + { + var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName}"; + return new ResourceIdentifier(resourceId); + } + + private readonly ClientDiagnostics _employeeClientDiagnostics; + private readonly EmployeesRestOperations _employeeRestClient; + private readonly EmployeeData _data; + + /// Gets the resource type for the operations. + public static readonly ResourceType ResourceType = "Microsoft.Contoso/employees"; + + /// Initializes a new instance of the class for mocking. + protected EmployeeResource() + { + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The resource that is the target of operations. + internal EmployeeResource(ArmClient client, EmployeeData data) : this(client, data.Id) + { + HasData = true; + _data = data; + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + internal EmployeeResource(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _employeeClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Contoso", ResourceType.Namespace, Diagnostics); + TryGetApiVersion(ResourceType, out string employeeApiVersion); + _employeeRestClient = new EmployeesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, employeeApiVersion); +#if DEBUG + ValidateResourceId(Id); +#endif + } + + /// Gets whether or not the current instance has data. + public virtual bool HasData { get; } + + /// Gets the data representing this Feature. + /// Throws if there is no data loaded in the current instance. + public virtual EmployeeData Data + { + get + { + if (!HasData) + throw new InvalidOperationException("The current instance does not have data, you must call Get first."); + return _data; + } + } + + internal static void ValidateResourceId(ResourceIdentifier id) + { + if (id.ResourceType != ResourceType) + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); + } + + /// + /// Get a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual async Task> GetAsync(CancellationToken cancellationToken = default) + { + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeResource.Get"); + scope.Start(); + try + { + var response = await _employeeRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new EmployeeResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual Response Get(CancellationToken cancellationToken = default) + { + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeResource.Get"); + scope.Start(); + try + { + var response = _employeeRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new EmployeeResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Delete + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The cancellation token to use. + public virtual async Task DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) + { + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeResource.Delete"); + scope.Start(); + try + { + var response = await _employeeRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); + var operation = new ContosoArmOperation(_employeeClientDiagnostics, Pipeline, _employeeRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response, OperationFinalStateVia.Location); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Delete + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The cancellation token to use. + public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) + { + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeResource.Delete"); + scope.Start(); + try + { + var response = _employeeRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); + var operation = new ContosoArmOperation(_employeeClientDiagnostics, Pipeline, _employeeRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name).Request, response, OperationFinalStateVia.Location); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletionResponse(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Update a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Update + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The resource properties to be updated. + /// The cancellation token to use. + /// is null. + public virtual async Task> UpdateAsync(EmployeeData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeResource.Update"); + scope.Start(); + try + { + var response = await _employeeRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, data, cancellationToken).ConfigureAwait(false); + return Response.FromValue(new EmployeeResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Update a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Update + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The resource properties to be updated. + /// The cancellation token to use. + /// is null. + public virtual Response Update(EmployeeData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeResource.Update"); + scope.Start(); + try + { + var response = _employeeRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, data, cancellationToken); + return Response.FromValue(new EmployeeResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Add a tag to the current resource. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The key for the tag. + /// The value for the tag. + /// The cancellation token to use. + /// or is null. + public virtual async Task> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(key, nameof(key)); + Argument.AssertNotNull(value, nameof(value)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeResource.AddTag"); + scope.Start(); + try + { + if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) + { + var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); + originalTags.Value.Data.TagValues[key] = value; + await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); + var originalResponse = await _employeeRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); + return Response.FromValue(new EmployeeResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); + } + else + { + var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; + var patch = new EmployeeData(current.Location); + foreach (var tag in current.Tags) + { + patch.Tags.Add(tag); + } + patch.Tags[key] = value; + var result = await UpdateAsync(patch, cancellationToken: cancellationToken).ConfigureAwait(false); + return result; + } + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Add a tag to the current resource. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The key for the tag. + /// The value for the tag. + /// The cancellation token to use. + /// or is null. + public virtual Response AddTag(string key, string value, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(key, nameof(key)); + Argument.AssertNotNull(value, nameof(value)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeResource.AddTag"); + scope.Start(); + try + { + if (CanUseTagResource(cancellationToken: cancellationToken)) + { + var originalTags = GetTagResource().Get(cancellationToken); + originalTags.Value.Data.TagValues[key] = value; + GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); + var originalResponse = _employeeRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); + return Response.FromValue(new EmployeeResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); + } + else + { + var current = Get(cancellationToken: cancellationToken).Value.Data; + var patch = new EmployeeData(current.Location); + foreach (var tag in current.Tags) + { + patch.Tags.Add(tag); + } + patch.Tags[key] = value; + var result = Update(patch, cancellationToken: cancellationToken); + return result; + } + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Replace the tags on the resource with the given set. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The set of tags to use as replacement. + /// The cancellation token to use. + /// is null. + public virtual async Task> SetTagsAsync(IDictionary tags, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(tags, nameof(tags)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeResource.SetTags"); + scope.Start(); + try + { + if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) + { + await GetTagResource().DeleteAsync(WaitUntil.Completed, cancellationToken: cancellationToken).ConfigureAwait(false); + var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); + originalTags.Value.Data.TagValues.ReplaceWith(tags); + await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); + var originalResponse = await _employeeRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); + return Response.FromValue(new EmployeeResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); + } + else + { + var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; + var patch = new EmployeeData(current.Location); + patch.Tags.ReplaceWith(tags); + var result = await UpdateAsync(patch, cancellationToken: cancellationToken).ConfigureAwait(false); + return result; + } + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Replace the tags on the resource with the given set. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The set of tags to use as replacement. + /// The cancellation token to use. + /// is null. + public virtual Response SetTags(IDictionary tags, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(tags, nameof(tags)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeResource.SetTags"); + scope.Start(); + try + { + if (CanUseTagResource(cancellationToken: cancellationToken)) + { + GetTagResource().Delete(WaitUntil.Completed, cancellationToken: cancellationToken); + var originalTags = GetTagResource().Get(cancellationToken); + originalTags.Value.Data.TagValues.ReplaceWith(tags); + GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); + var originalResponse = _employeeRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); + return Response.FromValue(new EmployeeResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); + } + else + { + var current = Get(cancellationToken: cancellationToken).Value.Data; + var patch = new EmployeeData(current.Location); + patch.Tags.ReplaceWith(tags); + var result = Update(patch, cancellationToken: cancellationToken); + return result; + } + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Removes a tag by key from the resource. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The key for the tag. + /// The cancellation token to use. + /// is null. + public virtual async Task> RemoveTagAsync(string key, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(key, nameof(key)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeResource.RemoveTag"); + scope.Start(); + try + { + if (await CanUseTagResourceAsync(cancellationToken: cancellationToken).ConfigureAwait(false)) + { + var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); + originalTags.Value.Data.TagValues.Remove(key); + await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); + var originalResponse = await _employeeRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); + return Response.FromValue(new EmployeeResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); + } + else + { + var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; + var patch = new EmployeeData(current.Location); + foreach (var tag in current.Tags) + { + patch.Tags.Add(tag); + } + patch.Tags.Remove(key); + var result = await UpdateAsync(patch, cancellationToken: cancellationToken).ConfigureAwait(false); + return result; + } + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Removes a tag by key from the resource. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The key for the tag. + /// The cancellation token to use. + /// is null. + public virtual Response RemoveTag(string key, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(key, nameof(key)); + + using var scope = _employeeClientDiagnostics.CreateScope("EmployeeResource.RemoveTag"); + scope.Start(); + try + { + if (CanUseTagResource(cancellationToken: cancellationToken)) + { + var originalTags = GetTagResource().Get(cancellationToken); + originalTags.Value.Data.TagValues.Remove(key); + GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); + var originalResponse = _employeeRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); + return Response.FromValue(new EmployeeResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); + } + else + { + var current = Get(cancellationToken: cancellationToken).Value.Data; + var patch = new EmployeeData(current.Location); + foreach (var tag in current.Tags) + { + patch.Tags.Add(tag); + } + patch.Tags.Remove(key); + var result = Update(patch, cancellationToken: cancellationToken); + return result; + } + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Extensions/ContosoExtensions.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Extensions/ContosoExtensions.cs new file mode 100644 index 000000000000..3e8c2e0d8d70 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Extensions/ContosoExtensions.cs @@ -0,0 +1,219 @@ +// 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; +using Azure.ResourceManager.Contoso.Mocking; +using Azure.ResourceManager.Resources; + +namespace Azure.ResourceManager.Contoso +{ + /// A class to add extension methods to Azure.ResourceManager.Contoso. + public static partial class ContosoExtensions + { + private static MockableContosoArmClient GetMockableContosoArmClient(ArmClient client) + { + return client.GetCachedClient(client0 => new MockableContosoArmClient(client0)); + } + + private static MockableContosoResourceGroupResource GetMockableContosoResourceGroupResource(ArmResource resource) + { + return resource.GetCachedClient(client => new MockableContosoResourceGroupResource(client, resource.Id)); + } + + private static MockableContosoSubscriptionResource GetMockableContosoSubscriptionResource(ArmResource resource) + { + return resource.GetCachedClient(client => new MockableContosoSubscriptionResource(client, resource.Id)); + } + + /// + /// Gets an object representing an along with the instance operations that can be performed on it but with no data. + /// You can use to create an from its components. + /// + /// Mocking + /// To mock this method, please mock instead. + /// + /// + /// The instance the method will execute against. + /// The resource ID of the resource to get. + /// is null. + /// Returns a object. + public static EmployeeResource GetEmployeeResource(this ArmClient client, ResourceIdentifier id) + { + Argument.AssertNotNull(client, nameof(client)); + + return GetMockableContosoArmClient(client).GetEmployeeResource(id); + } + + /// + /// Gets a collection of EmployeeResources in the ResourceGroupResource. + /// + /// Mocking + /// To mock this method, please mock instead. + /// + /// + /// The instance the method will execute against. + /// is null. + /// An object representing collection of EmployeeResources and their operations over a EmployeeResource. + public static EmployeeCollection GetEmployees(this ResourceGroupResource resourceGroupResource) + { + Argument.AssertNotNull(resourceGroupResource, nameof(resourceGroupResource)); + + return GetMockableContosoResourceGroupResource(resourceGroupResource).GetEmployees(); + } + + /// + /// Get a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// Mocking + /// To mock this method, please mock instead. + /// + /// + /// The instance the method will execute against. + /// The name of the Employee. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public static async Task> GetEmployeeAsync(this ResourceGroupResource resourceGroupResource, string employeeName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(resourceGroupResource, nameof(resourceGroupResource)); + + return await GetMockableContosoResourceGroupResource(resourceGroupResource).GetEmployeeAsync(employeeName, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// Mocking + /// To mock this method, please mock instead. + /// + /// + /// The instance the method will execute against. + /// The name of the Employee. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public static Response GetEmployee(this ResourceGroupResource resourceGroupResource, string employeeName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(resourceGroupResource, nameof(resourceGroupResource)); + + return GetMockableContosoResourceGroupResource(resourceGroupResource).GetEmployee(employeeName, cancellationToken); + } + + /// + /// List Employee resources by subscription ID + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/providers/Microsoft.Contoso/employees + /// + /// + /// Operation Id + /// Employee_ListBySubscription + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// Mocking + /// To mock this method, please mock instead. + /// + /// + /// The instance the method will execute against. + /// The cancellation token to use. + /// is null. + /// An async collection of that may take multiple service requests to iterate over. + public static AsyncPageable GetEmployeesAsync(this SubscriptionResource subscriptionResource, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(subscriptionResource, nameof(subscriptionResource)); + + return GetMockableContosoSubscriptionResource(subscriptionResource).GetEmployeesAsync(cancellationToken); + } + + /// + /// List Employee resources by subscription ID + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/providers/Microsoft.Contoso/employees + /// + /// + /// Operation Id + /// Employee_ListBySubscription + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// Mocking + /// To mock this method, please mock instead. + /// + /// + /// The instance the method will execute against. + /// The cancellation token to use. + /// is null. + /// A collection of that may take multiple service requests to iterate over. + public static Pageable GetEmployees(this SubscriptionResource subscriptionResource, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(subscriptionResource, nameof(subscriptionResource)); + + return GetMockableContosoSubscriptionResource(subscriptionResource).GetEmployees(cancellationToken); + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Extensions/MockableContosoArmClient.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Extensions/MockableContosoArmClient.cs new file mode 100644 index 000000000000..9dd8be4758d4 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Extensions/MockableContosoArmClient.cs @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using Azure.Core; + +namespace Azure.ResourceManager.Contoso.Mocking +{ + /// A class to add extension methods to ArmClient. + public partial class MockableContosoArmClient : ArmResource + { + /// Initializes a new instance of the class for mocking. + protected MockableContosoArmClient() + { + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + internal MockableContosoArmClient(ArmClient client, ResourceIdentifier id) : base(client, id) + { + } + + internal MockableContosoArmClient(ArmClient client) : this(client, ResourceIdentifier.Root) + { + } + + private string GetApiVersionOrNull(ResourceType resourceType) + { + TryGetApiVersion(resourceType, out string apiVersion); + return apiVersion; + } + + /// + /// Gets an object representing an along with the instance operations that can be performed on it but with no data. + /// You can use to create an from its components. + /// + /// The resource ID of the resource to get. + /// Returns a object. + public virtual EmployeeResource GetEmployeeResource(ResourceIdentifier id) + { + EmployeeResource.ValidateResourceId(id); + return new EmployeeResource(Client, id); + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Extensions/MockableContosoResourceGroupResource.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Extensions/MockableContosoResourceGroupResource.cs new file mode 100644 index 000000000000..a4c47d382ed8 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Extensions/MockableContosoResourceGroupResource.cs @@ -0,0 +1,105 @@ +// 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; + +namespace Azure.ResourceManager.Contoso.Mocking +{ + /// A class to add extension methods to ResourceGroupResource. + public partial class MockableContosoResourceGroupResource : ArmResource + { + /// Initializes a new instance of the class for mocking. + protected MockableContosoResourceGroupResource() + { + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + internal MockableContosoResourceGroupResource(ArmClient client, ResourceIdentifier id) : base(client, id) + { + } + + private string GetApiVersionOrNull(ResourceType resourceType) + { + TryGetApiVersion(resourceType, out string apiVersion); + return apiVersion; + } + + /// Gets a collection of EmployeeResources in the ResourceGroupResource. + /// An object representing collection of EmployeeResources and their operations over a EmployeeResource. + public virtual EmployeeCollection GetEmployees() + { + return GetCachedClient(client => new EmployeeCollection(client, Id)); + } + + /// + /// Get a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The name of the Employee. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual async Task> GetEmployeeAsync(string employeeName, CancellationToken cancellationToken = default) + { + return await GetEmployees().GetAsync(employeeName, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a Employee + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Contoso/employees/{employeeName} + /// + /// + /// Operation Id + /// Employee_Get + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The name of the Employee. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual Response GetEmployee(string employeeName, CancellationToken cancellationToken = default) + { + return GetEmployees().Get(employeeName, cancellationToken); + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Extensions/MockableContosoSubscriptionResource.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Extensions/MockableContosoSubscriptionResource.cs new file mode 100644 index 000000000000..6a116f9716a3 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Extensions/MockableContosoSubscriptionResource.cs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Threading; +using Autorest.CSharp.Core; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.ResourceManager.Contoso.Mocking +{ + /// A class to add extension methods to SubscriptionResource. + public partial class MockableContosoSubscriptionResource : ArmResource + { + private ClientDiagnostics _employeeClientDiagnostics; + private EmployeesRestOperations _employeeRestClient; + + /// Initializes a new instance of the class for mocking. + protected MockableContosoSubscriptionResource() + { + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The identifier of the resource that is the target of operations. + internal MockableContosoSubscriptionResource(ArmClient client, ResourceIdentifier id) : base(client, id) + { + } + + private ClientDiagnostics EmployeeClientDiagnostics => _employeeClientDiagnostics ??= new ClientDiagnostics("Azure.ResourceManager.Contoso", EmployeeResource.ResourceType.Namespace, Diagnostics); + private EmployeesRestOperations EmployeeRestClient => _employeeRestClient ??= new EmployeesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, GetApiVersionOrNull(EmployeeResource.ResourceType)); + + private string GetApiVersionOrNull(ResourceType resourceType) + { + TryGetApiVersion(resourceType, out string apiVersion); + return apiVersion; + } + + /// + /// List Employee resources by subscription ID + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/providers/Microsoft.Contoso/employees + /// + /// + /// Operation Id + /// Employee_ListBySubscription + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + /// An async collection of that may take multiple service requests to iterate over. + public virtual AsyncPageable GetEmployeesAsync(CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => EmployeeRestClient.CreateListBySubscriptionRequest(Id.SubscriptionId); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => EmployeeRestClient.CreateListBySubscriptionNextPageRequest(nextLink, Id.SubscriptionId); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new EmployeeResource(Client, EmployeeData.DeserializeEmployeeData(e)), EmployeeClientDiagnostics, Pipeline, "MockableContosoSubscriptionResource.GetEmployees", "value", "nextLink", cancellationToken); + } + + /// + /// List Employee resources by subscription ID + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/providers/Microsoft.Contoso/employees + /// + /// + /// Operation Id + /// Employee_ListBySubscription + /// + /// + /// Default Api Version + /// 2021-11-01 + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + /// A collection of that may take multiple service requests to iterate over. + public virtual Pageable GetEmployees(CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => EmployeeRestClient.CreateListBySubscriptionRequest(Id.SubscriptionId); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => EmployeeRestClient.CreateListBySubscriptionNextPageRequest(nextLink, Id.SubscriptionId); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new EmployeeResource(Client, EmployeeData.DeserializeEmployeeData(e)), EmployeeClientDiagnostics, Pipeline, "MockableContosoSubscriptionResource.GetEmployees", "value", "nextLink", cancellationToken); + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/Argument.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/Argument.cs new file mode 100644 index 000000000000..b146fadb7828 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Contoso +{ + internal static class Argument + { + public static void AssertNotNull(T value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNull(T? value, string name) + where T : struct + { + if (!value.HasValue) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNullOrEmpty(IEnumerable value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value is ICollection collectionOfT && collectionOfT.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + if (value is ICollection collection && collection.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + using IEnumerator e = value.GetEnumerator(); + if (!e.MoveNext()) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + } + + public static void AssertNotNullOrEmpty(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value.Length == 0) + { + throw new ArgumentException("Value cannot be an empty string.", name); + } + } + + public static void AssertNotNullOrWhiteSpace(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name); + } + } + + public static void AssertNotDefault(ref T value, string name) + where T : struct, IEquatable + { + if (value.Equals(default)) + { + throw new ArgumentException("Value cannot be empty.", name); + } + } + + public static void AssertInRange(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (minimum.CompareTo(value) > 0) + { + throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); + } + if (maximum.CompareTo(value) < 0) + { + throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); + } + } + + public static void AssertEnumDefined(Type enumType, object value, string name) + { + if (!Enum.IsDefined(enumType, value)) + { + throw new ArgumentException($"Value not defined for {enumType.FullName}.", name); + } + } + + public static T CheckNotNull(T value, string name) + where T : class + { + AssertNotNull(value, name); + return value; + } + + public static string CheckNotNullOrEmpty(string value, string name) + { + AssertNotNullOrEmpty(value, name); + return value; + } + + public static void AssertNull(T value, string name, string message = null) + { + if (value != null) + { + throw new ArgumentException(message ?? "Value must be null.", name); + } + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 000000000000..c2b481265f05 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Contoso +{ + internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull + { + private IDictionary _innerDictionary; + + public ChangeTrackingDictionary() + { + } + + public ChangeTrackingDictionary(IDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(dictionary); + } + + public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(); + foreach (var pair in dictionary) + { + _innerDictionary.Add(pair); + } + } + + public bool IsUndefined => _innerDictionary == null; + + public int Count => IsUndefined ? 0 : EnsureDictionary().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; + + public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; + + public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; + + public TValue this[TKey key] + { + get + { + if (IsUndefined) + { + throw new KeyNotFoundException(nameof(key)); + } + return EnsureDictionary()[key]; + } + set + { + EnsureDictionary()[key] = value; + } + } + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + public IEnumerator> GetEnumerator() + { + if (IsUndefined) + { + IEnumerator> enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureDictionary().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + EnsureDictionary().Add(item); + } + + public void Clear() + { + EnsureDictionary().Clear(); + } + + public bool Contains(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int index) + { + if (IsUndefined) + { + return; + } + EnsureDictionary().CopyTo(array, index); + } + + public bool Remove(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(item); + } + + public void Add(TKey key, TValue value) + { + EnsureDictionary().Add(key, value); + } + + public bool ContainsKey(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().ContainsKey(key); + } + + public bool Remove(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(key); + } + + public bool TryGetValue(TKey key, out TValue value) + { + if (IsUndefined) + { + value = default; + return false; + } + return EnsureDictionary().TryGetValue(key, out value); + } + + public IDictionary EnsureDictionary() + { + return _innerDictionary ??= new Dictionary(); + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/ChangeTrackingList.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 000000000000..28e10b878f86 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/ChangeTrackingList.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.ResourceManager.Contoso +{ + internal class ChangeTrackingList : IList, IReadOnlyList + { + private IList _innerList; + + public ChangeTrackingList() + { + } + + public ChangeTrackingList(IList innerList) + { + if (innerList != null) + { + _innerList = innerList; + } + } + + public ChangeTrackingList(IReadOnlyList innerList) + { + if (innerList != null) + { + _innerList = innerList.ToList(); + } + } + + public bool IsUndefined => _innerList == null; + + public int Count => IsUndefined ? 0 : EnsureList().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; + + public T this[int index] + { + get + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + return EnsureList()[index]; + } + set + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList()[index] = value; + } + } + + public void Reset() + { + _innerList = null; + } + + public IEnumerator GetEnumerator() + { + if (IsUndefined) + { + IEnumerator enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureList().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(T item) + { + EnsureList().Add(item); + } + + public void Clear() + { + EnsureList().Clear(); + } + + public bool Contains(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Contains(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + if (IsUndefined) + { + return; + } + EnsureList().CopyTo(array, arrayIndex); + } + + public bool Remove(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Remove(item); + } + + public int IndexOf(T item) + { + if (IsUndefined) + { + return -1; + } + return EnsureList().IndexOf(item); + } + + public void Insert(int index, T item) + { + EnsureList().Insert(index, item); + } + + public void RemoveAt(int index) + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList().RemoveAt(index); + } + + public IList EnsureList() + { + return _innerList ??= new List(); + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 000000000000..5b13d8c23e13 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,399 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Xml; +using Azure.Core; + +namespace Azure.ResourceManager.Contoso +{ + internal static class ModelSerializationExtensions + { + internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions { MaxDepth = 256 }; + internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); + + public static object GetObject(this JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.String: + return element.GetString(); + case JsonValueKind.Number: + if (element.TryGetInt32(out int intValue)) + { + return intValue; + } + if (element.TryGetInt64(out long longValue)) + { + return longValue; + } + return element.GetDouble(); + case JsonValueKind.True: + return true; + case JsonValueKind.False: + return false; + case JsonValueKind.Undefined: + case JsonValueKind.Null: + return null; + case JsonValueKind.Object: + var dictionary = new Dictionary(); + foreach (var jsonProperty in element.EnumerateObject()) + { + dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); + } + return dictionary; + case JsonValueKind.Array: + var list = new List(); + foreach (var item in element.EnumerateArray()) + { + list.Add(item.GetObject()); + } + return list.ToArray(); + default: + throw new NotSupportedException($"Not supported value kind {element.ValueKind}"); + } + } + + public static byte[] GetBytesFromBase64(this JsonElement element, string format) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + + return format switch + { + "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()), + "D" => element.GetBytesFromBase64(), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + } + + public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch + { + "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()), + _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format) + }; + + public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format); + + public static char GetChar(this JsonElement element) + { + if (element.ValueKind == JsonValueKind.String) + { + var text = element.GetString(); + if (text == null || text.Length != 1) + { + throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); + } + return text[0]; + } + else + { + throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char"); + } + } + + [Conditional("DEBUG")] + public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) + { + throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); + } + + public static string GetRequiredString(this JsonElement element) + { + var value = element.GetString(); + if (value == null) + { + throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); + } + return value; + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, char value) + { + writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + + public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + switch (format) + { + case "U": + writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value)); + break; + case "D": + writer.WriteBase64StringValue(value); + break; + default: + throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)); + } + } + + public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + if (format != "U") + { + throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number."); + } + writer.WriteNumberValue(value.ToUnixTimeSeconds()); + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) + { + switch (value) + { + case null: + writer.WriteNullValue(); + break; + case IJsonModel jsonModel: + jsonModel.Write(writer, options ?? WireOptions); + break; + case IUtf8JsonSerializable serializable: + serializable.Write(writer); + break; + case byte[] bytes: + writer.WriteBase64StringValue(bytes); + break; + case BinaryData bytes0: + writer.WriteBase64StringValue(bytes0); + break; + case JsonElement json: + json.WriteTo(writer); + break; + case int i: + writer.WriteNumberValue(i); + break; + case decimal d: + writer.WriteNumberValue(d); + break; + case double d0: + if (double.IsNaN(d0)) + { + writer.WriteStringValue("NaN"); + } + else + { + writer.WriteNumberValue(d0); + } + break; + case float f: + writer.WriteNumberValue(f); + break; + case long l: + writer.WriteNumberValue(l); + break; + case string s: + writer.WriteStringValue(s); + break; + case bool b: + writer.WriteBooleanValue(b); + break; + case Guid g: + writer.WriteStringValue(g); + break; + case DateTimeOffset dateTimeOffset: + writer.WriteStringValue(dateTimeOffset, "O"); + break; + case DateTime dateTime: + writer.WriteStringValue(dateTime, "O"); + break; + case IEnumerable> enumerable: + writer.WriteStartObject(); + foreach (var pair in enumerable) + { + writer.WritePropertyName(pair.Key); + writer.WriteObjectValue(pair.Value, options); + } + writer.WriteEndObject(); + break; + case IEnumerable objectEnumerable: + writer.WriteStartArray(); + foreach (var item in objectEnumerable) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + break; + case TimeSpan timeSpan: + writer.WriteStringValue(timeSpan, "P"); + break; + default: + throw new NotSupportedException($"Not supported type {value.GetType()}"); + } + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) + { + writer.WriteObjectValue(value, options); + } + + internal static class TypeFormatters + { + private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; + public const string DefaultNumberFormat = "G"; + + public static string ToString(bool value) => value ? "true" : "false"; + + public static string ToString(DateTime value, string format) => value.Kind switch + { + DateTimeKind.Utc => ToString((DateTimeOffset)value, format), + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") + }; + + public static string ToString(DateTimeOffset value, string format) => format switch + { + "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "R" => value.ToString("r", CultureInfo.InvariantCulture), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(TimeSpan value, string format) => format switch + { + "P" => XmlConvert.ToString(value), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(byte[] value, string format) => format switch + { + "U" => ToBase64UrlString(value), + "D" => Convert.ToBase64String(value), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + + public static string ToBase64UrlString(byte[] value) + { + int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; + int size = checked(numWholeOrPartialInputBlocks * 4); + char[] output = new char[size]; + + int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); + + int i = 0; + for (; i < numBase64Chars; i++) + { + char ch = output[i]; + if (ch == '+') + { + output[i] = '-'; + } + else + { + if (ch == '/') + { + output[i] = '_'; + } + else + { + if (ch == '=') + { + break; + } + } + } + } + + return new string(output, 0, i); + } + + public static byte[] FromBase64UrlString(string value) + { + int paddingCharsToAdd = (value.Length % 4) switch + { + 0 => 0, + 2 => 2, + 3 => 1, + _ => throw new InvalidOperationException("Malformed input") + }; + char[] output = new char[(value.Length + paddingCharsToAdd)]; + int i = 0; + for (; i < value.Length; i++) + { + char ch = value[i]; + if (ch == '-') + { + output[i] = '+'; + } + else + { + if (ch == '_') + { + output[i] = '/'; + } + else + { + output[i] = ch; + } + } + } + + for (; i < output.Length; i++) + { + output[i] = '='; + } + + return Convert.FromBase64CharArray(output, 0, output.Length); + } + + public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch + { + "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), + _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) + }; + + public static TimeSpan ParseTimeSpan(string value, string format) => format switch + { + "P" => XmlConvert.ToTimeSpan(value), + _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) + }; + + public static string ConvertToString(object value, string format = null) => value switch + { + null => "null", + string s => s, + bool b => ToString(b), + int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), + byte[] b0 when format != null => ToString(b0, format), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when format != null => ToString(dateTime, format), + TimeSpan timeSpan when format != null => ToString(timeSpan, format), + TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/Optional.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/Optional.cs new file mode 100644 index 000000000000..3d6bd293a801 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/Optional.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; + +namespace Azure.ResourceManager.Contoso +{ + internal static class Optional + { + public static bool IsCollectionDefined(IEnumerable collection) + { + return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined); + } + + public static bool IsCollectionDefined(IDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsCollectionDefined(IReadOnlyDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsDefined(T? value) + where T : struct + { + return value.HasValue; + } + + public static bool IsDefined(object value) + { + return value != null; + } + + public static bool IsDefined(JsonElement value) + { + return value.ValueKind != JsonValueKind.Undefined; + } + + public static bool IsDefined(string value) + { + return value != null; + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 000000000000..50d04f500cd4 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace Azure.ResourceManager.Contoso +{ + internal class Utf8JsonRequestContent : RequestContent + { + private readonly MemoryStream _stream; + private readonly RequestContent _content; + + public Utf8JsonRequestContent() + { + _stream = new MemoryStream(); + _content = Create(_stream); + JsonWriter = new Utf8JsonWriter(_stream); + } + + public Utf8JsonWriter JsonWriter { get; } + + public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) + { + await JsonWriter.FlushAsync().ConfigureAwait(false); + await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); + } + + public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) + { + JsonWriter.Flush(); + _content.WriteTo(stream, cancellationToken); + } + + public override bool TryComputeLength(out long length) + { + length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; + return true; + } + + public override void Dispose() + { + JsonWriter.Dispose(); + _content.Dispose(); + _stream.Dispose(); + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/LongRunningOperation/ContosoArmOperation.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/LongRunningOperation/ContosoArmOperation.cs new file mode 100644 index 000000000000..2badd30f1f7b --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/LongRunningOperation/ContosoArmOperation.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.ResourceManager.Contoso +{ +#pragma warning disable SA1649 // File name should match first type name + internal class ContosoArmOperation : ArmOperation +#pragma warning restore SA1649 // File name should match first type name + { + private readonly OperationInternal _operation; + private readonly RehydrationToken? _completeRehydrationToken; + private readonly NextLinkOperationImplementation _nextLinkOperation; + private readonly string _operationId; + + /// Initializes a new instance of ContosoArmOperation for mocking. + protected ContosoArmOperation() + { + } + + internal ContosoArmOperation(Response response, RehydrationToken? rehydrationToken = null) + { + _operation = OperationInternal.Succeeded(response); + _completeRehydrationToken = rehydrationToken; + _operationId = GetOperationId(rehydrationToken); + } + + internal ContosoArmOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, bool skipApiVersionOverride = false, string apiVersionOverrideValue = null) + { + var nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); + if (nextLinkOperation is NextLinkOperationImplementation nextLinkOperationValue) + { + _nextLinkOperation = nextLinkOperationValue; + _operationId = _nextLinkOperation.OperationId; + } + else + { + _completeRehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(request.Method, request.Uri.ToUri(), response, finalStateVia); + _operationId = GetOperationId(_completeRehydrationToken); + } + _operation = new OperationInternal(nextLinkOperation, clientDiagnostics, response, "ContosoArmOperation", fallbackStrategy: new SequentialDelayStrategy()); + } + + private string GetOperationId(RehydrationToken? rehydrationToken) + { + if (rehydrationToken is null) + { + return null; + } + var lroDetails = ModelReaderWriter.Write(rehydrationToken, ModelReaderWriterOptions.Json).ToObjectFromJson>(); + return lroDetails["id"]; + } + /// + public override string Id => _operationId ?? NextLinkOperationImplementation.NotSet; + + /// + public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken() ?? _completeRehydrationToken; + + /// + public override bool HasCompleted => _operation.HasCompleted; + + /// + public override Response GetRawResponse() => _operation.RawResponse; + + /// + public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); + + /// + public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); + + /// + public override Response WaitForCompletionResponse(CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponse(cancellationToken); + + /// + public override Response WaitForCompletionResponse(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponse(pollingInterval, cancellationToken); + + /// + public override ValueTask WaitForCompletionResponseAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponseAsync(cancellationToken); + + /// + public override ValueTask WaitForCompletionResponseAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionResponseAsync(pollingInterval, cancellationToken); + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/LongRunningOperation/ContosoArmOperationOfT.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/LongRunningOperation/ContosoArmOperationOfT.cs new file mode 100644 index 000000000000..4b59643530b2 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/LongRunningOperation/ContosoArmOperationOfT.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.ResourceManager.Contoso +{ +#pragma warning disable SA1649 // File name should match first type name + internal class ContosoArmOperation : ArmOperation +#pragma warning restore SA1649 // File name should match first type name + { + private readonly OperationInternal _operation; + private readonly RehydrationToken? _completeRehydrationToken; + private readonly NextLinkOperationImplementation _nextLinkOperation; + private readonly string _operationId; + + /// Initializes a new instance of ContosoArmOperation for mocking. + protected ContosoArmOperation() + { + } + + internal ContosoArmOperation(Response response, RehydrationToken? rehydrationToken = null) + { + _operation = OperationInternal.Succeeded(response.GetRawResponse(), response.Value); + _completeRehydrationToken = rehydrationToken; + _operationId = GetOperationId(rehydrationToken); + } + + internal ContosoArmOperation(IOperationSource source, ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response, OperationFinalStateVia finalStateVia, bool skipApiVersionOverride = false, string apiVersionOverrideValue = null) + { + var nextLinkOperation = NextLinkOperationImplementation.Create(pipeline, request.Method, request.Uri.ToUri(), response, finalStateVia, skipApiVersionOverride, apiVersionOverrideValue); + if (nextLinkOperation is NextLinkOperationImplementation nextLinkOperationValue) + { + _nextLinkOperation = nextLinkOperationValue; + _operationId = _nextLinkOperation.OperationId; + } + else + { + _completeRehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(request.Method, request.Uri.ToUri(), response, finalStateVia); + _operationId = GetOperationId(_completeRehydrationToken); + } + _operation = new OperationInternal(NextLinkOperationImplementation.Create(source, nextLinkOperation), clientDiagnostics, response, "ContosoArmOperation", fallbackStrategy: new SequentialDelayStrategy()); + } + + private string GetOperationId(RehydrationToken? rehydrationToken) + { + if (rehydrationToken is null) + { + return null; + } + var lroDetails = ModelReaderWriter.Write(rehydrationToken, ModelReaderWriterOptions.Json).ToObjectFromJson>(); + return lroDetails["id"]; + } + /// + public override string Id => _operationId ?? NextLinkOperationImplementation.NotSet; + + /// + public override RehydrationToken? GetRehydrationToken() => _nextLinkOperation?.GetRehydrationToken() ?? _completeRehydrationToken; + + /// + public override T Value => _operation.Value; + + /// + public override bool HasValue => _operation.HasValue; + + /// + public override bool HasCompleted => _operation.HasCompleted; + + /// + public override Response GetRawResponse() => _operation.RawResponse; + + /// + public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); + + /// + public override ValueTask UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); + + /// + public override Response WaitForCompletion(CancellationToken cancellationToken = default) => _operation.WaitForCompletion(cancellationToken); + + /// + public override Response WaitForCompletion(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletion(pollingInterval, cancellationToken); + + /// + public override ValueTask> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); + + /// + public override ValueTask> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/LongRunningOperation/EmployeeOperationSource.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/LongRunningOperation/EmployeeOperationSource.cs new file mode 100644 index 000000000000..40897fe08bcb --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/LongRunningOperation/EmployeeOperationSource.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.ClientModel.Primitives; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace Azure.ResourceManager.Contoso +{ + internal class EmployeeOperationSource : IOperationSource + { + private readonly ArmClient _client; + + internal EmployeeOperationSource(ArmClient client) + { + _client = client; + } + + EmployeeResource IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) + { + var data = ModelReaderWriter.Read(response.Content); + return new EmployeeResource(_client, data); + } + + async ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) + { + var data = ModelReaderWriter.Read(response.Content); + return await Task.FromResult(new EmployeeResource(_client, data)).ConfigureAwait(false); + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/EmployeeListResult.Serialization.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/EmployeeListResult.Serialization.cs new file mode 100644 index 000000000000..5a1ac3f3643f --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/EmployeeListResult.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Contoso.Models +{ + internal partial class EmployeeListResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EmployeeListResult)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("value"u8); + writer.WriteStartArray(); + foreach (var item in Value) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (Optional.IsDefined(NextLink)) + { + writer.WritePropertyName("nextLink"u8); + writer.WriteStringValue(NextLink.AbsoluteUri); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + EmployeeListResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EmployeeListResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEmployeeListResult(document.RootElement, options); + } + + internal static EmployeeListResult DeserializeEmployeeListResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList value = default; + Uri nextLink = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("value"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(EmployeeData.DeserializeEmployeeData(item, options)); + } + value = array; + continue; + } + if (property.NameEquals("nextLink"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + nextLink = new Uri(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EmployeeListResult(value, nextLink, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(EmployeeListResult)} does not support writing '{options.Format}' format."); + } + } + + EmployeeListResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEmployeeListResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EmployeeListResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/EmployeeListResult.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/EmployeeListResult.cs new file mode 100644 index 000000000000..f40f6693d057 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/EmployeeListResult.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.ResourceManager.Contoso.Models +{ + /// The response of a Employee list operation. + internal partial class EmployeeListResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The Employee items on this page. + /// is null. + internal EmployeeListResult(IEnumerable value) + { + Argument.AssertNotNull(value, nameof(value)); + + Value = value.ToList(); + } + + /// Initializes a new instance of . + /// The Employee items on this page. + /// The link to the next page of items. + /// Keeps track of any properties unknown to the library. + internal EmployeeListResult(IReadOnlyList value, Uri nextLink, IDictionary serializedAdditionalRawData) + { + Value = value; + NextLink = nextLink; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal EmployeeListResult() + { + } + + /// The Employee items on this page. + public IReadOnlyList Value { get; } + /// The link to the next page of items. + public Uri NextLink { get; } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/EmployeeProperties.Serialization.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/EmployeeProperties.Serialization.cs new file mode 100644 index 000000000000..5c469fe54d30 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/EmployeeProperties.Serialization.cs @@ -0,0 +1,174 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.Contoso.Models +{ + public partial class EmployeeProperties : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EmployeeProperties)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Age)) + { + writer.WritePropertyName("age"u8); + writer.WriteNumberValue(Age.Value); + } + if (Optional.IsDefined(City)) + { + writer.WritePropertyName("city"u8); + writer.WriteStringValue(City); + } + if (Optional.IsDefined(Profile)) + { + writer.WritePropertyName("profile"u8); + writer.WriteBase64StringValue(Profile, "U"); + } + if (options.Format != "W" && Optional.IsDefined(ProvisioningState)) + { + writer.WritePropertyName("provisioningState"u8); + writer.WriteStringValue(ProvisioningState.Value.ToString()); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + EmployeeProperties IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EmployeeProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEmployeeProperties(document.RootElement, options); + } + + internal static EmployeeProperties DeserializeEmployeeProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? age = default; + string city = default; + byte[] profile = default; + ProvisioningState? provisioningState = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("age"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + age = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("city"u8)) + { + city = property.Value.GetString(); + continue; + } + if (property.NameEquals("profile"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + profile = property.Value.GetBytesFromBase64("U"); + continue; + } + if (property.NameEquals("provisioningState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + provisioningState = new ProvisioningState(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EmployeeProperties(age, city, profile, provisioningState, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(EmployeeProperties)} does not support writing '{options.Format}' format."); + } + } + + EmployeeProperties IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEmployeeProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EmployeeProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/EmployeeProperties.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/EmployeeProperties.cs new file mode 100644 index 000000000000..f17e5ee5c7df --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/EmployeeProperties.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.Contoso.Models +{ + /// Employee properties. + public partial class EmployeeProperties + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public EmployeeProperties() + { + } + + /// Initializes a new instance of . + /// Age of employee. + /// City of employee. + /// Profile of employee. + /// The status of the last operation. + /// Keeps track of any properties unknown to the library. + internal EmployeeProperties(int? age, string city, byte[] profile, ProvisioningState? provisioningState, IDictionary serializedAdditionalRawData) + { + Age = age; + City = city; + Profile = profile; + ProvisioningState = provisioningState; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Age of employee. + public int? Age { get; set; } + /// City of employee. + public string City { get; set; } + /// Profile of employee. + public byte[] Profile { get; set; } + /// The status of the last operation. + public ProvisioningState? ProvisioningState { get; } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/ProvisioningState.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/ProvisioningState.cs new file mode 100644 index 000000000000..3b650fd30ca1 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/Models/ProvisioningState.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.Contoso.Models +{ + /// The resource provisioning state. + public readonly partial struct ProvisioningState : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ProvisioningState(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SucceededValue = "Succeeded"; + private const string FailedValue = "Failed"; + private const string CanceledValue = "Canceled"; + private const string ProvisioningValue = "Provisioning"; + private const string UpdatingValue = "Updating"; + private const string DeletingValue = "Deleting"; + private const string AcceptedValue = "Accepted"; + + /// Resource has been created. + public static ProvisioningState Succeeded { get; } = new ProvisioningState(SucceededValue); + /// Resource creation failed. + public static ProvisioningState Failed { get; } = new ProvisioningState(FailedValue); + /// Resource creation was canceled. + public static ProvisioningState Canceled { get; } = new ProvisioningState(CanceledValue); + /// The resource is being provisioned. + public static ProvisioningState Provisioning { get; } = new ProvisioningState(ProvisioningValue); + /// The resource is updating. + public static ProvisioningState Updating { get; } = new ProvisioningState(UpdatingValue); + /// The resource is being deleted. + public static ProvisioningState Deleting { get; } = new ProvisioningState(DeletingValue); + /// The resource create request has been accepted. + public static ProvisioningState Accepted { get; } = new ProvisioningState(AcceptedValue); + /// Determines if two values are the same. + public static bool operator ==(ProvisioningState left, ProvisioningState right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ProvisioningState left, ProvisioningState right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ProvisioningState(string value) => new ProvisioningState(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ProvisioningState other && Equals(other); + /// + public bool Equals(ProvisioningState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/ProviderConstants.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/ProviderConstants.cs new file mode 100644 index 000000000000..58224a637312 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/ProviderConstants.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using Azure.Core.Pipeline; + +namespace Azure.ResourceManager.Contoso +{ + internal static class ProviderConstants + { + public static string DefaultProviderNamespace { get; } = ClientDiagnostics.GetResourceProviderNamespace(typeof(ProviderConstants).Assembly); + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/RestOperations/EmployeesRestOperations.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/RestOperations/EmployeesRestOperations.cs new file mode 100644 index 000000000000..b13e791dc40f --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Generated/RestOperations/EmployeesRestOperations.cs @@ -0,0 +1,731 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; +using Azure.ResourceManager.Contoso.Models; + +namespace Azure.ResourceManager.Contoso +{ + internal partial class EmployeesRestOperations + { + private readonly TelemetryDetails _userAgent; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// Initializes a new instance of EmployeesRestOperations. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The application id to use for user agent. + /// Service host. + /// The API version to use for this operation. + /// or is null. + public EmployeesRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) + { + _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); + _endpoint = endpoint ?? new Uri("https://management.azure.com"); + _apiVersion = apiVersion ?? "2021-11-01"; + _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); + } + + internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceGroupName, string employeeName) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/resourceGroups/", false); + uri.AppendPath(resourceGroupName, true); + uri.AppendPath("/providers/Microsoft.Contoso/employees/", false); + uri.AppendPath(employeeName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string employeeName) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/resourceGroups/", false); + uri.AppendPath(resourceGroupName, true); + uri.AppendPath("/providers/Microsoft.Contoso/employees/", false); + uri.AppendPath(employeeName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Get a Employee. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Employee. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task> GetAsync(string subscriptionId, string resourceGroupName, string employeeName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, employeeName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + EmployeeData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = EmployeeData.DeserializeEmployeeData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((EmployeeData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + /// Get a Employee. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Employee. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response Get(string subscriptionId, string resourceGroupName, string employeeName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, employeeName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + EmployeeData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = EmployeeData.DeserializeEmployeeData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((EmployeeData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string resourceGroupName, string employeeName, EmployeeData data) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/resourceGroups/", false); + uri.AppendPath(resourceGroupName, true); + uri.AppendPath("/providers/Microsoft.Contoso/employees/", false); + uri.AppendPath(employeeName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string employeeName, EmployeeData data) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/resourceGroups/", false); + uri.AppendPath(resourceGroupName, true); + uri.AppendPath("/providers/Microsoft.Contoso/employees/", false); + uri.AppendPath(employeeName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); + request.Content = content; + _userAgent.Apply(message); + return message; + } + + /// Create a Employee. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Employee. + /// Resource create parameters. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string employeeName, EmployeeData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, employeeName, data); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + case 201: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + /// Create a Employee. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Employee. + /// Resource create parameters. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, string employeeName, EmployeeData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, employeeName, data); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + case 201: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateUpdateRequestUri(string subscriptionId, string resourceGroupName, string employeeName, EmployeeData data) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/resourceGroups/", false); + uri.AppendPath(resourceGroupName, true); + uri.AppendPath("/providers/Microsoft.Contoso/employees/", false); + uri.AppendPath(employeeName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string employeeName, EmployeeData data) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Patch; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/resourceGroups/", false); + uri.AppendPath(resourceGroupName, true); + uri.AppendPath("/providers/Microsoft.Contoso/employees/", false); + uri.AppendPath(employeeName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(data, ModelSerializationExtensions.WireOptions); + request.Content = content; + _userAgent.Apply(message); + return message; + } + + /// Update a Employee. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Employee. + /// The resource properties to be updated. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task> UpdateAsync(string subscriptionId, string resourceGroupName, string employeeName, EmployeeData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, employeeName, data); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + EmployeeData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = EmployeeData.DeserializeEmployeeData(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// Update a Employee. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Employee. + /// The resource properties to be updated. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response Update(string subscriptionId, string resourceGroupName, string employeeName, EmployeeData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, employeeName, data); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + EmployeeData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = EmployeeData.DeserializeEmployeeData(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string resourceGroupName, string employeeName) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/resourceGroups/", false); + uri.AppendPath(resourceGroupName, true); + uri.AppendPath("/providers/Microsoft.Contoso/employees/", false); + uri.AppendPath(employeeName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string employeeName) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/resourceGroups/", false); + uri.AppendPath(resourceGroupName, true); + uri.AppendPath("/providers/Microsoft.Contoso/employees/", false); + uri.AppendPath(employeeName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Delete a Employee. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Employee. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task DeleteAsync(string subscriptionId, string resourceGroupName, string employeeName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, employeeName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 202: + case 204: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + /// Delete a Employee. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The name of the Employee. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response Delete(string subscriptionId, string resourceGroupName, string employeeName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(employeeName, nameof(employeeName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, employeeName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 202: + case 204: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListByResourceGroupRequestUri(string subscriptionId, string resourceGroupName) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/resourceGroups/", false); + uri.AppendPath(resourceGroupName, true); + uri.AppendPath("/providers/Microsoft.Contoso/employees", false); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateListByResourceGroupRequest(string subscriptionId, string resourceGroupName) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/resourceGroups/", false); + uri.AppendPath(resourceGroupName, true); + uri.AppendPath("/providers/Microsoft.Contoso/employees", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// List Employee resources by resource group. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public async Task> ListByResourceGroupAsync(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + + using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + EmployeeListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = EmployeeListResult.DeserializeEmployeeListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List Employee resources by resource group. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public Response ListByResourceGroup(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + + using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + EmployeeListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = EmployeeListResult.DeserializeEmployeeListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListBySubscriptionRequestUri(string subscriptionId) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/providers/Microsoft.Contoso/employees", false); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateListBySubscriptionRequest(string subscriptionId) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/subscriptions/", false); + uri.AppendPath(subscriptionId, true); + uri.AppendPath("/providers/Microsoft.Contoso/employees", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// List Employee resources by subscription ID. + /// The ID of the target subscription. The value must be an UUID. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public async Task> ListBySubscriptionAsync(string subscriptionId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + + using var message = CreateListBySubscriptionRequest(subscriptionId); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + EmployeeListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = EmployeeListResult.DeserializeEmployeeListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List Employee resources by subscription ID. + /// The ID of the target subscription. The value must be an UUID. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public Response ListBySubscription(string subscriptionId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + + using var message = CreateListBySubscriptionRequest(subscriptionId); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + EmployeeListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = EmployeeListResult.DeserializeEmployeeListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListByResourceGroupNextPageRequestUri(string nextLink, string subscriptionId, string resourceGroupName) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + return uri; + } + + internal HttpMessage CreateListByResourceGroupNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// List Employee resources by resource group. + /// The URL to the next page of results. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public async Task> ListByResourceGroupNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + + using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + EmployeeListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = EmployeeListResult.DeserializeEmployeeListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List Employee resources by resource group. + /// The URL to the next page of results. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public Response ListByResourceGroupNextPage(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + + using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + EmployeeListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = EmployeeListResult.DeserializeEmployeeListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListBySubscriptionNextPageRequestUri(string nextLink, string subscriptionId) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + return uri; + } + + internal HttpMessage CreateListBySubscriptionNextPageRequest(string nextLink, string subscriptionId) + { + var message = _pipeline.CreateMessage(); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// List Employee resources by subscription ID. + /// The URL to the next page of results. + /// The ID of the target subscription. The value must be an UUID. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public async Task> ListBySubscriptionNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + + using var message = CreateListBySubscriptionNextPageRequest(nextLink, subscriptionId); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + EmployeeListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = EmployeeListResult.DeserializeEmployeeListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List Employee resources by subscription ID. + /// The URL to the next page of results. + /// The ID of the target subscription. The value must be an UUID. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public Response ListBySubscriptionNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + + using var message = CreateListBySubscriptionNextPageRequest(nextLink, subscriptionId); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + EmployeeListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = EmployeeListResult.DeserializeEmployeeListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/src/Properties/AssemblyInfo.cs b/sdk/contoso/Azure.ResourceManager.Contoso/src/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..113b6ed3d98f --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/src/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Azure.ResourceManager.Contoso.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] + +// Replace Microsoft.Test with the correct resource provider namepace for your service and uncomment. +// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/azure-services-resource-providers +// for the list of possible values. +[assembly: Azure.Core.AzureResourceProviderNamespace("Contoso")] diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/tests/Azure.ResourceManager.Contoso.Tests.csproj b/sdk/contoso/Azure.ResourceManager.Contoso/tests/Azure.ResourceManager.Contoso.Tests.csproj new file mode 100644 index 000000000000..4b906ef77fda --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/tests/Azure.ResourceManager.Contoso.Tests.csproj @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/tests/ContosoManagementTestBase.cs b/sdk/contoso/Azure.ResourceManager.Contoso/tests/ContosoManagementTestBase.cs new file mode 100644 index 000000000000..77599a7902fe --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/tests/ContosoManagementTestBase.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure; +using Azure.Core; +using Azure.Core.TestFramework; +using Azure.ResourceManager; +using Azure.ResourceManager.Resources; +using Azure.ResourceManager.TestFramework; +using NUnit.Framework; +using System.Threading.Tasks; + +namespace Azure.ResourceManager.Contoso.Tests +{ + public class ContosoManagementTestBase : ManagementRecordedTestBase + { + protected ArmClient Client { get; private set; } + protected SubscriptionResource DefaultSubscription { get; private set; } + + protected ContosoManagementTestBase(bool isAsync, RecordedTestMode mode) + : base(isAsync, mode) + { + } + + protected ContosoManagementTestBase(bool isAsync) + : base(isAsync) + { + } + + [SetUp] + public async Task CreateCommonClient() + { + Client = GetArmClient(); + DefaultSubscription = await Client.GetDefaultSubscriptionAsync().ConfigureAwait(false); + } + + protected async Task CreateResourceGroup(SubscriptionResource subscription, string rgNamePrefix, AzureLocation location) + { + string rgName = Recording.GenerateAssetName(rgNamePrefix); + ResourceGroupData input = new ResourceGroupData(location); + var lro = await subscription.GetResourceGroups().CreateOrUpdateAsync(WaitUntil.Completed, rgName, input); + return lro.Value; + } + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/tests/ContosoManagementTestEnvironment.cs b/sdk/contoso/Azure.ResourceManager.Contoso/tests/ContosoManagementTestEnvironment.cs new file mode 100644 index 000000000000..b1c4c91e35b3 --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/tests/ContosoManagementTestEnvironment.cs @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core.TestFramework; + +namespace Azure.ResourceManager.Contoso.Tests +{ + public class ContosoManagementTestEnvironment : TestEnvironment + { + } +} diff --git a/sdk/contoso/Azure.ResourceManager.Contoso/tsp-location.yaml b/sdk/contoso/Azure.ResourceManager.Contoso/tsp-location.yaml new file mode 100644 index 000000000000..13d5a3f1a0cd --- /dev/null +++ b/sdk/contoso/Azure.ResourceManager.Contoso/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/contosowidgetmanager/Contoso.Management +commit: e86f9dade22bbb783fde4ee2879b0bf1cc3f9ec0 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/contoso/ci.mgmt.yml b/sdk/contoso/ci.mgmt.yml new file mode 100644 index 000000000000..3485a663b46d --- /dev/null +++ b/sdk/contoso/ci.mgmt.yml @@ -0,0 +1,26 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: none + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/contoso /ci.mgmt.yml + - sdk/contoso /Azure.ResourceManager.Contoso / + + +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: contoso + ArtifactName: packages + LimitForPullRequest: true + Artifacts: + - name: Azure.ResourceManager.Contoso + safeName: AzureResourceManagerContoso diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/Azure.Template.Contoso.sln b/sdk/contosowidgetmanager/Azure.Template.Contoso/Azure.Template.Contoso.sln new file mode 100644 index 000000000000..b8a126d8fc2a --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/Azure.Template.Contoso.sln @@ -0,0 +1,56 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +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.Contoso", "src\Azure.Template.Contoso.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Template.Contoso.Tests", "tests\Azure.Template.Contoso.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + 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 + {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 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A97F4B90-2591-4689-B1F8-5F21FE6D6CAE} + EndGlobalSection +EndGlobal diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/CHANGELOG.md b/sdk/contosowidgetmanager/Azure.Template.Contoso/CHANGELOG.md new file mode 100644 index 000000000000..8b33f0fedccc --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/CHANGELOG.md @@ -0,0 +1,11 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes \ No newline at end of file diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/Directory.Build.props b/sdk/contosowidgetmanager/Azure.Template.Contoso/Directory.Build.props new file mode 100644 index 000000000000..63bd836ad44b --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/Directory.Build.props @@ -0,0 +1,6 @@ + + + + diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/README.md b/sdk/contosowidgetmanager/Azure.Template.Contoso/README.md new file mode 100644 index 000000000000..e316c602298d --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/README.md @@ -0,0 +1,107 @@ +# Azure.Template.Contoso client library for .NET + +Azure.Template.Contoso is a managed service that helps developers get secret simply and securely. + +Use the client library for to: + +* [Get secret](https://docs.microsoft.com/azure) + +[Source code][source_root] | [Package (NuGet)][package] | [API reference documentation][reference_docs] | [Product documentation][azconfig_docs] | [Samples][source_samples] + + [Source code](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/contosowidgetmanager/Azure.Template.Contoso/src) | [Package (NuGet)](https://www.nuget.org/packages) | [API reference documentation](https://azure.github.io/azure-sdk-for-net) | [Product documentation](https://docs.microsoft.com/azure) + +## Getting started + +This section should include everything a developer needs to do to install and create their first client connection *very quickly*. + +### Install the package + +First, provide instruction for obtaining and installing the package or library. This section might include only a single line of code, like `dotnet add package package-name`, but should enable a developer to successfully install the package from NuGet, npm, or even cloning a GitHub repository. + +Install the client library for .NET with [NuGet](https://www.nuget.org/ ): + +```dotnetcli +dotnet add package Azure.Template.Contoso --prerelease +``` + +### Prerequisites + +Include a section after the install command that details any requirements that must be satisfied before a developer can [authenticate](#authenticate-the-client) and test all of the snippets in the [Examples](#examples) section. For example, for Cosmos DB: + +> You must have an [Azure subscription](https://azure.microsoft.com/free/dotnet/) and [Cosmos DB account](https://docs.microsoft.com/azure/cosmos-db/account-overview) (SQL API). In order to take advantage of the C# 8.0 syntax, it is recommended that you compile using the [.NET Core SDK](https://dotnet.microsoft.com/download) 3.0 or higher with a [language version](https://docs.microsoft.com/dotnet/csharp/language-reference/configure-language-version#override-a-default) of `latest`. It is also possible to compile with the .NET Core SDK 2.1.x using a language version of `preview`. + +### Authenticate the client + +If your library requires authentication for use, such as for Azure services, include instructions and example code needed for initializing and authenticating. + +For example, include details on obtaining an account key and endpoint URI, setting environment variables for each, and initializing the client object. + +### Service API versions + +The client library targets the latest service API version by default. A client instance accepts an optional service API version parameter from its options to specify which API version service to communicate. + +#### Select a service API version + +You have the flexibility to explicitly select a supported service API version when instantiating a client by configuring its associated options. This ensures that the client can communicate with services using the specified API version. + +For example, + +```C# Snippet:CreateClientForSpecificApiVersion +Uri endpoint = new Uri(""); +DefaultAzureCredential credential = new DefaultAzureCredential(); +ClientOptions options = new ClientOptions(ClientOptions.ServiceVersion.) +var client = new Client(endpoint, credential, options); +``` + +When selecting an API version, it's important to verify that there are no breaking changes compared to the latest API version. If there are significant differences, API calls may fail due to incompatibility. + +Always ensure that the chosen API version is fully supported and operational for your specific use case and that it aligns with the service's versioning policy. + +## Key concepts + +The *Key concepts* section should describe the functionality of the main classes. Point out the most important and useful classes in the package (with links to their reference pages) and explain how those classes work together. Feel free to use bulleted lists, tables, code blocks, or even diagrams for clarity. + +Include the *Thread safety* and *Additional concepts* sections below at the end of your *Key concepts* section. You may remove or add links depending on what your library makes use of: + +### Thread safety + +We guarantee that all client instance methods are thread-safe and independent of each other ([guideline](https://azure.github.io/azure-sdk/dotnet_introduction.html#dotnet-service-methods-thread-safety)). This ensures that the recommendation of reusing client instances is always safe, even across threads. + +### Additional concepts + +[Client options](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#configuring-service-clients-using-clientoptions) | +[Accessing the response](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#accessing-http-response-details-using-responset) | +[Long-running operations](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#consuming-long-running-operations-using-operationt) | +[Handling failures](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#reporting-errors-requestfailedexception) | +[Diagnostics](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Diagnostics.md) | +[Mocking](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#mocking) | +[Client lifetime](https://devblogs.microsoft.com/azure-sdk/lifetime-management-and-thread-safety-guarantees-of-azure-sdk-net-clients/) + + +## Examples + +You can familiarize yourself with different APIs using [Samples](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/contosowidgetmanager/Azure.Template.Contoso/samples). + +## Troubleshooting + +Describe common errors and exceptions, how to "unpack" them if necessary, and include guidance for graceful handling and recovery. + +Provide information to help developers avoid throttling or other service-enforced errors they might encounter. For example, provide guidance and examples for using retry or connection policies in the API. + +If the package or a related package supports it, include tips for logging or enabling instrumentation to help them debug their code. + +## Next steps + +* Provide a link to additional code examples, ideally to those sitting alongside the README in the package's `/samples` directory. +* If appropriate, point users to other packages that might be useful. +* If you think there's a good chance that developers might stumble across your package in error (because they're searching for specific functionality and mistakenly think the package provides that functionality), point them to the packages they might be looking for. + +## Contributing + +This is a template, but your SDK readme should include details on how to contribute code to the repo/package. + + +[style-guide-msft]: https://docs.microsoft.com/style-guide/capitalization +[style-guide-cloud]: https://aka.ms/azsdk/cloud-style-guide + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-net/sdk/contosowidgetmanager/Azure.Template.Contoso/README.png) \ No newline at end of file diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/api/Azure.Template.Contoso.net8.0.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/api/Azure.Template.Contoso.net8.0.cs new file mode 100644 index 000000000000..5f4aeb69c4f0 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/api/Azure.Template.Contoso.net8.0.cs @@ -0,0 +1,115 @@ +namespace Azure.Template.Contoso +{ + public partial class ContosoWidgets + { + protected ContosoWidgets() { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Operation CreateOrUpdateWidget(Azure.WaitUntil waitUntil, string widgetName, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> CreateOrUpdateWidgetAsync(Azure.WaitUntil waitUntil, string widgetName, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Operation DeleteWidget(Azure.WaitUntil waitUntil, string widgetName, Azure.RequestContext context) { throw null; } + public virtual Azure.Operation DeleteWidget(Azure.WaitUntil waitUntil, string widgetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> DeleteWidgetAsync(Azure.WaitUntil waitUntil, string widgetName, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task> DeleteWidgetAsync(Azure.WaitUntil waitUntil, string widgetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response GetWidget(string widgetName, Azure.RequestContext context) { throw null; } + public virtual Azure.Response GetWidget(string widgetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task GetWidgetAsync(string widgetName, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task> GetWidgetAsync(string widgetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response GetWidgetOperationStatus(string widgetName, string operationId, Azure.RequestContext context) { throw null; } + public virtual Azure.Response GetWidgetOperationStatus(string widgetName, string operationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task GetWidgetOperationStatusAsync(string widgetName, string operationId, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task> GetWidgetOperationStatusAsync(string widgetName, string operationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Pageable GetWidgets(Azure.RequestContext context) { throw null; } + public virtual Azure.Pageable GetWidgets(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.AsyncPageable GetWidgetsAsync(Azure.RequestContext context) { throw null; } + public virtual Azure.AsyncPageable GetWidgetsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + } + public partial class FakedSharedModel : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public FakedSharedModel(string tag, System.DateTimeOffset createdAt) { } + public System.DateTimeOffset CreatedAt { get { throw null; } set { } } + public string Tag { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Template.Contoso.FakedSharedModel System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Template.Contoso.FakedSharedModel System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct OperationState : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public OperationState(string value) { throw null; } + public static Azure.Template.Contoso.OperationState Canceled { get { throw null; } } + public static Azure.Template.Contoso.OperationState Failed { get { throw null; } } + public static Azure.Template.Contoso.OperationState NotStarted { get { throw null; } } + public static Azure.Template.Contoso.OperationState Running { get { throw null; } } + public static Azure.Template.Contoso.OperationState Succeeded { get { throw null; } } + public bool Equals(Azure.Template.Contoso.OperationState 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.Template.Contoso.OperationState left, Azure.Template.Contoso.OperationState right) { throw null; } + public static implicit operator Azure.Template.Contoso.OperationState (string value) { throw null; } + public static bool operator !=(Azure.Template.Contoso.OperationState left, Azure.Template.Contoso.OperationState right) { throw null; } + public override string ToString() { throw null; } + } + public partial class ResourceOperationStatusWidgetSuiteWidgetSuiteError : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal ResourceOperationStatusWidgetSuiteWidgetSuiteError() { } + public Azure.ResponseError Error { get { throw null; } } + public string Id { get { throw null; } } + public Azure.Template.Contoso.WidgetSuite Result { get { throw null; } } + public Azure.Template.Contoso.OperationState Status { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Template.Contoso.ResourceOperationStatusWidgetSuiteWidgetSuiteError System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Template.Contoso.ResourceOperationStatusWidgetSuiteWidgetSuiteError System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public static partial class TemplateContosoModelFactory + { + public static Azure.Template.Contoso.ResourceOperationStatusWidgetSuiteWidgetSuiteError ResourceOperationStatusWidgetSuiteWidgetSuiteError(string id = null, Azure.Template.Contoso.OperationState status = default(Azure.Template.Contoso.OperationState), Azure.ResponseError error = null, Azure.Template.Contoso.WidgetSuite result = null) { throw null; } + public static Azure.Template.Contoso.WidgetSuite WidgetSuite(string name = null, string manufacturerId = null, Azure.Template.Contoso.FakedSharedModel sharedModel = null) { throw null; } + } + public partial class WidgetManagerClient + { + protected WidgetManagerClient() { } + public WidgetManagerClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { } + public WidgetManagerClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Template.Contoso.WidgetManagerClientOptions options) { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Template.Contoso.ContosoWidgets GetContosoWidgetsClient(string apiVersion = "2022-12-01") { throw null; } + } + public partial class WidgetManagerClientOptions : Azure.Core.ClientOptions + { + public WidgetManagerClientOptions(Azure.Template.Contoso.WidgetManagerClientOptions.ServiceVersion version = Azure.Template.Contoso.WidgetManagerClientOptions.ServiceVersion.V2022_12_01) { } + public enum ServiceVersion + { + V2022_12_01 = 1, + } + } + public partial class WidgetSuite : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public WidgetSuite(string manufacturerId) { } + public string ManufacturerId { get { throw null; } set { } } + public string Name { get { throw null; } } + public Azure.Template.Contoso.FakedSharedModel SharedModel { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Template.Contoso.WidgetSuite System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Template.Contoso.WidgetSuite System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } +} +namespace Microsoft.Extensions.Azure +{ + public static partial class TemplateContosoClientBuilderExtensions + { + public static Azure.Core.Extensions.IAzureClientBuilder AddWidgetManagerClient(this TBuilder builder, System.Uri endpoint) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddWidgetManagerClient(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration { throw null; } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/api/Azure.Template.Contoso.netstandard2.0.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/api/Azure.Template.Contoso.netstandard2.0.cs new file mode 100644 index 000000000000..5f4aeb69c4f0 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/api/Azure.Template.Contoso.netstandard2.0.cs @@ -0,0 +1,115 @@ +namespace Azure.Template.Contoso +{ + public partial class ContosoWidgets + { + protected ContosoWidgets() { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Operation CreateOrUpdateWidget(Azure.WaitUntil waitUntil, string widgetName, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> CreateOrUpdateWidgetAsync(Azure.WaitUntil waitUntil, string widgetName, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Operation DeleteWidget(Azure.WaitUntil waitUntil, string widgetName, Azure.RequestContext context) { throw null; } + public virtual Azure.Operation DeleteWidget(Azure.WaitUntil waitUntil, string widgetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> DeleteWidgetAsync(Azure.WaitUntil waitUntil, string widgetName, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task> DeleteWidgetAsync(Azure.WaitUntil waitUntil, string widgetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response GetWidget(string widgetName, Azure.RequestContext context) { throw null; } + public virtual Azure.Response GetWidget(string widgetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task GetWidgetAsync(string widgetName, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task> GetWidgetAsync(string widgetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response GetWidgetOperationStatus(string widgetName, string operationId, Azure.RequestContext context) { throw null; } + public virtual Azure.Response GetWidgetOperationStatus(string widgetName, string operationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task GetWidgetOperationStatusAsync(string widgetName, string operationId, Azure.RequestContext context) { throw null; } + public virtual System.Threading.Tasks.Task> GetWidgetOperationStatusAsync(string widgetName, string operationId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Pageable GetWidgets(Azure.RequestContext context) { throw null; } + public virtual Azure.Pageable GetWidgets(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.AsyncPageable GetWidgetsAsync(Azure.RequestContext context) { throw null; } + public virtual Azure.AsyncPageable GetWidgetsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + } + public partial class FakedSharedModel : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public FakedSharedModel(string tag, System.DateTimeOffset createdAt) { } + public System.DateTimeOffset CreatedAt { get { throw null; } set { } } + public string Tag { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Template.Contoso.FakedSharedModel System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Template.Contoso.FakedSharedModel System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct OperationState : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public OperationState(string value) { throw null; } + public static Azure.Template.Contoso.OperationState Canceled { get { throw null; } } + public static Azure.Template.Contoso.OperationState Failed { get { throw null; } } + public static Azure.Template.Contoso.OperationState NotStarted { get { throw null; } } + public static Azure.Template.Contoso.OperationState Running { get { throw null; } } + public static Azure.Template.Contoso.OperationState Succeeded { get { throw null; } } + public bool Equals(Azure.Template.Contoso.OperationState 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.Template.Contoso.OperationState left, Azure.Template.Contoso.OperationState right) { throw null; } + public static implicit operator Azure.Template.Contoso.OperationState (string value) { throw null; } + public static bool operator !=(Azure.Template.Contoso.OperationState left, Azure.Template.Contoso.OperationState right) { throw null; } + public override string ToString() { throw null; } + } + public partial class ResourceOperationStatusWidgetSuiteWidgetSuiteError : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal ResourceOperationStatusWidgetSuiteWidgetSuiteError() { } + public Azure.ResponseError Error { get { throw null; } } + public string Id { get { throw null; } } + public Azure.Template.Contoso.WidgetSuite Result { get { throw null; } } + public Azure.Template.Contoso.OperationState Status { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Template.Contoso.ResourceOperationStatusWidgetSuiteWidgetSuiteError System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Template.Contoso.ResourceOperationStatusWidgetSuiteWidgetSuiteError System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public static partial class TemplateContosoModelFactory + { + public static Azure.Template.Contoso.ResourceOperationStatusWidgetSuiteWidgetSuiteError ResourceOperationStatusWidgetSuiteWidgetSuiteError(string id = null, Azure.Template.Contoso.OperationState status = default(Azure.Template.Contoso.OperationState), Azure.ResponseError error = null, Azure.Template.Contoso.WidgetSuite result = null) { throw null; } + public static Azure.Template.Contoso.WidgetSuite WidgetSuite(string name = null, string manufacturerId = null, Azure.Template.Contoso.FakedSharedModel sharedModel = null) { throw null; } + } + public partial class WidgetManagerClient + { + protected WidgetManagerClient() { } + public WidgetManagerClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { } + public WidgetManagerClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Template.Contoso.WidgetManagerClientOptions options) { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Template.Contoso.ContosoWidgets GetContosoWidgetsClient(string apiVersion = "2022-12-01") { throw null; } + } + public partial class WidgetManagerClientOptions : Azure.Core.ClientOptions + { + public WidgetManagerClientOptions(Azure.Template.Contoso.WidgetManagerClientOptions.ServiceVersion version = Azure.Template.Contoso.WidgetManagerClientOptions.ServiceVersion.V2022_12_01) { } + public enum ServiceVersion + { + V2022_12_01 = 1, + } + } + public partial class WidgetSuite : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public WidgetSuite(string manufacturerId) { } + public string ManufacturerId { get { throw null; } set { } } + public string Name { get { throw null; } } + public Azure.Template.Contoso.FakedSharedModel SharedModel { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Template.Contoso.WidgetSuite System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Template.Contoso.WidgetSuite System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } +} +namespace Microsoft.Extensions.Azure +{ + public static partial class TemplateContosoClientBuilderExtensions + { + public static Azure.Core.Extensions.IAzureClientBuilder AddWidgetManagerClient(this TBuilder builder, System.Uri endpoint) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddWidgetManagerClient(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration { throw null; } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Azure.Template.Contoso.csproj b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Azure.Template.Contoso.csproj new file mode 100644 index 000000000000..8e26ba2f2db8 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Azure.Template.Contoso.csproj @@ -0,0 +1,19 @@ + + + This is the Azure.Template.Contoso client library for developing .NET applications with rich experience. + Azure SDK Code Generation Azure.Template.Contoso for Azure Data Plane + 1.0.0-beta.1 + Azure.Template.Contoso + $(RequiredTargetFrameworks) + true + + + + + + + + + + + diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/ContosoWidgets.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/ContosoWidgets.cs new file mode 100644 index 000000000000..805332d7b840 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/ContosoWidgets.cs @@ -0,0 +1,661 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Autorest.CSharp.Core; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.Template.Contoso +{ + // Data plane generated sub-client. + /// The ContosoWidgets sub-client. + public partial class ContosoWidgets + { + private static readonly string[] AuthorizationScopes = new string[] { "https://contoso.azure.com/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _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 ContosoWidgets for mocking. + protected ContosoWidgets() + { + } + + /// Initializes a new instance of ContosoWidgets. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The token credential to copy. + /// Service host. + /// The API version to use for this operation. + internal ContosoWidgets(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Fetch a Widget by name. + /// The widget name. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> GetWidgetAsync(string widgetName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetWidgetAsync(widgetName, context).ConfigureAwait(false); + return Response.FromValue(WidgetSuite.FromResponse(response), response); + } + + /// Fetch a Widget by name. + /// The widget name. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response GetWidget(string widgetName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetWidget(widgetName, context); + return Response.FromValue(WidgetSuite.FromResponse(response), response); + } + + /// + /// [Protocol Method] Fetch a Widget by name. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The widget name. + /// 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 GetWidgetAsync(string widgetName, RequestContext context) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + + using var scope = ClientDiagnostics.CreateScope("ContosoWidgets.GetWidget"); + scope.Start(); + try + { + using HttpMessage message = CreateGetWidgetRequest(widgetName, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Fetch a Widget by name. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The widget name. + /// 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 GetWidget(string widgetName, RequestContext context) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + + using var scope = ClientDiagnostics.CreateScope("ContosoWidgets.GetWidget"); + scope.Start(); + try + { + using HttpMessage message = CreateGetWidgetRequest(widgetName, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets status of a Widget operation. + /// The widget name. + /// The unique ID of the operation. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// + public virtual async Task> GetWidgetOperationStatusAsync(string widgetName, string operationId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + Argument.AssertNotNullOrEmpty(operationId, nameof(operationId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetWidgetOperationStatusAsync(widgetName, operationId, context).ConfigureAwait(false); + return Response.FromValue(ResourceOperationStatusWidgetSuiteWidgetSuiteError.FromResponse(response), response); + } + + /// Gets status of a Widget operation. + /// The widget name. + /// The unique ID of the operation. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// + public virtual Response GetWidgetOperationStatus(string widgetName, string operationId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + Argument.AssertNotNullOrEmpty(operationId, nameof(operationId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetWidgetOperationStatus(widgetName, operationId, context); + return Response.FromValue(ResourceOperationStatusWidgetSuiteWidgetSuiteError.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets status of a Widget operation. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The widget name. + /// The unique ID of the operation. + /// 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 GetWidgetOperationStatusAsync(string widgetName, string operationId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + Argument.AssertNotNullOrEmpty(operationId, nameof(operationId)); + + using var scope = ClientDiagnostics.CreateScope("ContosoWidgets.GetWidgetOperationStatus"); + scope.Start(); + try + { + using HttpMessage message = CreateGetWidgetOperationStatusRequest(widgetName, operationId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets status of a Widget operation. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The widget name. + /// The unique ID of the operation. + /// 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 GetWidgetOperationStatus(string widgetName, string operationId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + Argument.AssertNotNullOrEmpty(operationId, nameof(operationId)); + + using var scope = ClientDiagnostics.CreateScope("ContosoWidgets.GetWidgetOperationStatus"); + scope.Start(); + try + { + using HttpMessage message = CreateGetWidgetOperationStatusRequest(widgetName, operationId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// List Widget resources. + /// The cancellation token to use. + /// + public virtual AsyncPageable GetWidgetsAsync(CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetWidgetsRequest(context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetWidgetsNextPageRequest(nextLink, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => WidgetSuite.DeserializeWidgetSuite(e), ClientDiagnostics, _pipeline, "ContosoWidgets.GetWidgets", "value", "nextLink", context); + } + + /// List Widget resources. + /// The cancellation token to use. + /// + public virtual Pageable GetWidgets(CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetWidgetsRequest(context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetWidgetsNextPageRequest(nextLink, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => WidgetSuite.DeserializeWidgetSuite(e), ClientDiagnostics, _pipeline, "ContosoWidgets.GetWidgets", "value", "nextLink", context); + } + + /// + /// [Protocol Method] List Widget resources + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// 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 GetWidgetsAsync(RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetWidgetsRequest(context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetWidgetsNextPageRequest(nextLink, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "ContosoWidgets.GetWidgets", "value", "nextLink", context); + } + + /// + /// [Protocol Method] List Widget resources + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// 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 GetWidgets(RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetWidgetsRequest(context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetWidgetsNextPageRequest(nextLink, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "ContosoWidgets.GetWidgets", "value", "nextLink", context); + } + + /// + /// [Protocol Method] Creates or updates a Widget asynchronously. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The widget name. + /// 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 representing an asynchronous operation on the service. + /// + public virtual async Task> CreateOrUpdateWidgetAsync(WaitUntil waitUntil, string widgetName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("ContosoWidgets.CreateOrUpdateWidget"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrUpdateWidgetRequest(widgetName, content, context); + return await ProtocolOperationHelpers.ProcessMessageAsync(_pipeline, message, ClientDiagnostics, "ContosoWidgets.CreateOrUpdateWidget", OperationFinalStateVia.OperationLocation, context, waitUntil).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates or updates a Widget asynchronously. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The widget name. + /// 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 representing an asynchronous operation on the service. + /// + public virtual Operation CreateOrUpdateWidget(WaitUntil waitUntil, string widgetName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("ContosoWidgets.CreateOrUpdateWidget"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrUpdateWidgetRequest(widgetName, content, context); + return ProtocolOperationHelpers.ProcessMessage(_pipeline, message, ClientDiagnostics, "ContosoWidgets.CreateOrUpdateWidget", OperationFinalStateVia.OperationLocation, context, waitUntil); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Delete a Widget asynchronously. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The widget name. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> DeleteWidgetAsync(WaitUntil waitUntil, string widgetName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = await DeleteWidgetAsync(waitUntil, widgetName, context).ConfigureAwait(false); + return ProtocolOperationHelpers.Convert(response, FetchWidgetSuiteFromResourceOperationStatusWidgetSuiteWidgetSuiteError, ClientDiagnostics, "ContosoWidgets.DeleteWidget"); + } + + /// Delete a Widget asynchronously. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The widget name. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Operation DeleteWidget(WaitUntil waitUntil, string widgetName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = DeleteWidget(waitUntil, widgetName, context); + return ProtocolOperationHelpers.Convert(response, FetchWidgetSuiteFromResourceOperationStatusWidgetSuiteWidgetSuiteError, ClientDiagnostics, "ContosoWidgets.DeleteWidget"); + } + + /// + /// [Protocol Method] Delete a Widget asynchronously. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The widget name. + /// 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 representing an asynchronous operation on the service. + /// + public virtual async Task> DeleteWidgetAsync(WaitUntil waitUntil, string widgetName, RequestContext context) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + + using var scope = ClientDiagnostics.CreateScope("ContosoWidgets.DeleteWidget"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteWidgetRequest(widgetName, context); + return await ProtocolOperationHelpers.ProcessMessageAsync(_pipeline, message, ClientDiagnostics, "ContosoWidgets.DeleteWidget", OperationFinalStateVia.OperationLocation, context, waitUntil).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Delete a Widget asynchronously. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The widget name. + /// 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 representing an asynchronous operation on the service. + /// + public virtual Operation DeleteWidget(WaitUntil waitUntil, string widgetName, RequestContext context) + { + Argument.AssertNotNullOrEmpty(widgetName, nameof(widgetName)); + + using var scope = ClientDiagnostics.CreateScope("ContosoWidgets.DeleteWidget"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteWidgetRequest(widgetName, context); + return ProtocolOperationHelpers.ProcessMessage(_pipeline, message, ClientDiagnostics, "ContosoWidgets.DeleteWidget", OperationFinalStateVia.OperationLocation, context, waitUntil); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateGetWidgetRequest(string widgetName, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/widgets/", false); + uri.AppendPath(widgetName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetWidgetOperationStatusRequest(string widgetName, string operationId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/widgets/", false); + uri.AppendPath(widgetName, true); + uri.AppendPath("/operations/", false); + uri.AppendPath(operationId, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateOrUpdateWidgetRequest(string widgetName, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Patch; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/widgets/", false); + uri.AppendPath(widgetName, 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 CreateDeleteWidgetRequest(string widgetName, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier202); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/widgets/", false); + uri.AppendPath(widgetName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetWidgetsRequest(RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/widgets", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetWidgetsNextPageRequest(string nextLink, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + private static ResponseClassifier _responseClassifier200201; + private static ResponseClassifier ResponseClassifier200201 => _responseClassifier200201 ??= new StatusCodeClassifier(stackalloc ushort[] { 200, 201 }); + private static ResponseClassifier _responseClassifier202; + private static ResponseClassifier ResponseClassifier202 => _responseClassifier202 ??= new StatusCodeClassifier(stackalloc ushort[] { 202 }); + + private WidgetSuite FetchWidgetSuiteFromResourceOperationStatusWidgetSuiteWidgetSuiteError(Response response) + { + var resultJsonElement = JsonDocument.Parse(response.Content).RootElement.GetProperty("result"); + return WidgetSuite.DeserializeWidgetSuite(resultJsonElement); + } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Docs/ContosoWidgets.xml b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Docs/ContosoWidgets.xml new file mode 100644 index 000000000000..f93a7fff74d1 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Docs/ContosoWidgets.xml @@ -0,0 +1,273 @@ + + + + + +This sample shows how to call GetWidgetAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +Response response = await client.GetWidgetAsync("searchbox"); +]]> + + + +This sample shows how to call GetWidget. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +Response response = client.GetWidget("searchbox"); +]]> + + + +This sample shows how to call GetWidgetAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +Response response = await client.GetWidgetAsync("searchbox", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("manufacturerId").ToString()); +]]> + + + +This sample shows how to call GetWidget and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +Response response = client.GetWidget("searchbox", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("manufacturerId").ToString()); +]]> + + + +This sample shows how to call GetWidgetOperationStatusAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +Response response = await client.GetWidgetOperationStatusAsync("name1", "opreation id1"); +]]> + + + +This sample shows how to call GetWidgetOperationStatus. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +Response response = client.GetWidgetOperationStatus("name1", "opreation id1"); +]]> + + + +This sample shows how to call GetWidgetOperationStatusAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +Response response = await client.GetWidgetOperationStatusAsync("name1", "opreation id1", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +]]> + + + +This sample shows how to call GetWidgetOperationStatus and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +Response response = client.GetWidgetOperationStatus("name1", "opreation id1", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +]]> + + + +This sample shows how to call GetWidgetsAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +await foreach (WidgetSuite item in client.GetWidgetsAsync()) +{ +} +]]> + + + +This sample shows how to call GetWidgets. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +foreach (WidgetSuite item in client.GetWidgets()) +{ +} +]]> + + + +This sample shows how to call GetWidgetsAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +await foreach (BinaryData item in client.GetWidgetsAsync(null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("manufacturerId").ToString()); +} +]]> + + + +This sample shows how to call GetWidgets and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +foreach (BinaryData item in client.GetWidgets(null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("manufacturerId").ToString()); +} +]]> + + + +This sample shows how to call CreateOrUpdateWidgetAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +using RequestContent content = RequestContent.Create(new +{ + manufacturerId = "manufacturer id1", + sharedModel = new + { + tag = "tag1", + createdAt = "2023-01-09T02:12:25.689Z", + }, +}); +Operation operation = await client.CreateOrUpdateWidgetAsync(WaitUntil.Completed, "name1", content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("manufacturerId").ToString()); +]]> + + + +This sample shows how to call CreateOrUpdateWidget and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +using RequestContent content = RequestContent.Create(new +{ + manufacturerId = "manufacturer id1", + sharedModel = new + { + tag = "tag1", + createdAt = "2023-01-09T02:12:25.689Z", + }, +}); +Operation operation = client.CreateOrUpdateWidget(WaitUntil.Completed, "name1", content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("manufacturerId").ToString()); +]]> + + + +This sample shows how to call DeleteWidgetAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +Operation operation = await client.DeleteWidgetAsync(WaitUntil.Completed, "searchbox"); +WidgetSuite responseData = operation.Value; +]]> + + + +This sample shows how to call DeleteWidget. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +Operation operation = client.DeleteWidget(WaitUntil.Completed, "searchbox"); +WidgetSuite responseData = operation.Value; +]]> + + + +This sample shows how to call DeleteWidgetAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +Operation operation = await client.DeleteWidgetAsync(WaitUntil.Completed, "searchbox", null); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("manufacturerId").ToString()); +]]> + + + +This sample shows how to call DeleteWidget and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + +Operation operation = client.DeleteWidget(WaitUntil.Completed, "searchbox", null); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("manufacturerId").ToString()); +]]> + + + \ No newline at end of file diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.Serialization.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/FakedSharedModel.Serialization.cs similarity index 55% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.Serialization.cs rename to sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/FakedSharedModel.Serialization.cs index 3a81222297b3..e852c0eb26bc 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.Serialization.cs +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/FakedSharedModel.Serialization.cs @@ -11,13 +11,13 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.Vision.Face +namespace Azure.Template.Contoso { - public partial class AuditRequestInfo : IUtf8JsonSerializable, IJsonModel + public partial class FakedSharedModel : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,28 +28,16 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(AuditRequestInfo)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(FakedSharedModel)} does not support writing '{format}' format."); } - writer.WritePropertyName("url"u8); - writer.WriteStringValue(Url); - writer.WritePropertyName("method"u8); - writer.WriteStringValue(Method); - if (Optional.IsDefined(ContentLength)) - { - writer.WritePropertyName("contentLength"u8); - writer.WriteNumberValue(ContentLength.Value); - } - writer.WritePropertyName("contentType"u8); - writer.WriteStringValue(ContentType); - if (Optional.IsDefined(UserAgent)) - { - writer.WritePropertyName("userAgent"u8); - writer.WriteStringValue(UserAgent); - } + writer.WritePropertyName("tag"u8); + writer.WriteStringValue(Tag); + writer.WritePropertyName("createdAt"u8); + writer.WriteStringValue(CreatedAt, "O"); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -67,19 +55,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - AuditRequestInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FakedSharedModel IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(AuditRequestInfo)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(FakedSharedModel)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAuditRequestInfo(document.RootElement, options); + return DeserializeFakedSharedModel(document.RootElement, options); } - internal static AuditRequestInfo DeserializeAuditRequestInfo(JsonElement element, ModelReaderWriterOptions options = null) + internal static FakedSharedModel DeserializeFakedSharedModel(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -87,42 +75,20 @@ internal static AuditRequestInfo DeserializeAuditRequestInfo(JsonElement element { return null; } - string url = default; - string method = default; - long? contentLength = default; - string contentType = default; - string userAgent = default; + string tag = default; + DateTimeOffset createdAt = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("url"u8)) - { - url = property.Value.GetString(); - continue; - } - if (property.NameEquals("method"u8)) - { - method = property.Value.GetString(); - continue; - } - if (property.NameEquals("contentLength"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - contentLength = property.Value.GetInt64(); - continue; - } - if (property.NameEquals("contentType"u8)) + if (property.NameEquals("tag"u8)) { - contentType = property.Value.GetString(); + tag = property.Value.GetString(); continue; } - if (property.NameEquals("userAgent"u8)) + if (property.NameEquals("createdAt"u8)) { - userAgent = property.Value.GetString(); + createdAt = property.Value.GetDateTimeOffset("O"); continue; } if (options.Format != "W") @@ -131,52 +97,46 @@ internal static AuditRequestInfo DeserializeAuditRequestInfo(JsonElement element } } serializedAdditionalRawData = rawDataDictionary; - return new AuditRequestInfo( - url, - method, - contentLength, - contentType, - userAgent, - serializedAdditionalRawData); + return new FakedSharedModel(tag, createdAt, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(AuditRequestInfo)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(FakedSharedModel)} does not support writing '{options.Format}' format."); } } - AuditRequestInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + FakedSharedModel IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAuditRequestInfo(document.RootElement, options); + return DeserializeFakedSharedModel(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(AuditRequestInfo)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(FakedSharedModel)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static AuditRequestInfo FromResponse(Response response) + internal static FakedSharedModel FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAuditRequestInfo(document.RootElement); + return DeserializeFakedSharedModel(document.RootElement); } /// Convert into a . diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/FakedSharedModel.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/FakedSharedModel.cs new file mode 100644 index 000000000000..0ebce4cf58ed --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/FakedSharedModel.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Template.Contoso +{ + /// Faked shared model. + public partial class FakedSharedModel + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The tag. + /// The created date. + /// is null. + public FakedSharedModel(string tag, DateTimeOffset createdAt) + { + Argument.AssertNotNull(tag, nameof(tag)); + + Tag = tag; + CreatedAt = createdAt; + } + + /// Initializes a new instance of . + /// The tag. + /// The created date. + /// Keeps track of any properties unknown to the library. + internal FakedSharedModel(string tag, DateTimeOffset createdAt, IDictionary serializedAdditionalRawData) + { + Tag = tag; + CreatedAt = createdAt; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FakedSharedModel() + { + } + + /// The tag. + public string Tag { get; set; } + /// The created date. + public DateTimeOffset CreatedAt { get; set; } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/Argument.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/Argument.cs new file mode 100644 index 000000000000..6d81344fe1d7 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Azure.Template.Contoso +{ + internal static class Argument + { + public static void AssertNotNull(T value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNull(T? value, string name) + where T : struct + { + if (!value.HasValue) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNullOrEmpty(IEnumerable value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value is ICollection collectionOfT && collectionOfT.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + if (value is ICollection collection && collection.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + using IEnumerator e = value.GetEnumerator(); + if (!e.MoveNext()) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + } + + public static void AssertNotNullOrEmpty(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value.Length == 0) + { + throw new ArgumentException("Value cannot be an empty string.", name); + } + } + + public static void AssertNotNullOrWhiteSpace(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name); + } + } + + public static void AssertNotDefault(ref T value, string name) + where T : struct, IEquatable + { + if (value.Equals(default)) + { + throw new ArgumentException("Value cannot be empty.", name); + } + } + + public static void AssertInRange(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (minimum.CompareTo(value) > 0) + { + throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); + } + if (maximum.CompareTo(value) < 0) + { + throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); + } + } + + public static void AssertEnumDefined(Type enumType, object value, string name) + { + if (!Enum.IsDefined(enumType, value)) + { + throw new ArgumentException($"Value not defined for {enumType.FullName}.", name); + } + } + + public static T CheckNotNull(T value, string name) + where T : class + { + AssertNotNull(value, name); + return value; + } + + public static string CheckNotNullOrEmpty(string value, string name) + { + AssertNotNullOrEmpty(value, name); + return value; + } + + public static void AssertNull(T value, string name, string message = null) + { + if (value != null) + { + throw new ArgumentException(message ?? "Value must be null.", name); + } + } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 000000000000..fba592e87808 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Azure.Template.Contoso +{ + internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull + { + private IDictionary _innerDictionary; + + public ChangeTrackingDictionary() + { + } + + public ChangeTrackingDictionary(IDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(dictionary); + } + + public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(); + foreach (var pair in dictionary) + { + _innerDictionary.Add(pair); + } + } + + public bool IsUndefined => _innerDictionary == null; + + public int Count => IsUndefined ? 0 : EnsureDictionary().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; + + public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; + + public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; + + public TValue this[TKey key] + { + get + { + if (IsUndefined) + { + throw new KeyNotFoundException(nameof(key)); + } + return EnsureDictionary()[key]; + } + set + { + EnsureDictionary()[key] = value; + } + } + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + public IEnumerator> GetEnumerator() + { + if (IsUndefined) + { + IEnumerator> enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureDictionary().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + EnsureDictionary().Add(item); + } + + public void Clear() + { + EnsureDictionary().Clear(); + } + + public bool Contains(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int index) + { + if (IsUndefined) + { + return; + } + EnsureDictionary().CopyTo(array, index); + } + + public bool Remove(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(item); + } + + public void Add(TKey key, TValue value) + { + EnsureDictionary().Add(key, value); + } + + public bool ContainsKey(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().ContainsKey(key); + } + + public bool Remove(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(key); + } + + public bool TryGetValue(TKey key, out TValue value) + { + if (IsUndefined) + { + value = default; + return false; + } + return EnsureDictionary().TryGetValue(key, out value); + } + + public IDictionary EnsureDictionary() + { + return _innerDictionary ??= new Dictionary(); + } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/ChangeTrackingList.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 000000000000..5d1cec4e0093 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/ChangeTrackingList.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.Template.Contoso +{ + internal class ChangeTrackingList : IList, IReadOnlyList + { + private IList _innerList; + + public ChangeTrackingList() + { + } + + public ChangeTrackingList(IList innerList) + { + if (innerList != null) + { + _innerList = innerList; + } + } + + public ChangeTrackingList(IReadOnlyList innerList) + { + if (innerList != null) + { + _innerList = innerList.ToList(); + } + } + + public bool IsUndefined => _innerList == null; + + public int Count => IsUndefined ? 0 : EnsureList().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; + + public T this[int index] + { + get + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + return EnsureList()[index]; + } + set + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList()[index] = value; + } + } + + public void Reset() + { + _innerList = null; + } + + public IEnumerator GetEnumerator() + { + if (IsUndefined) + { + IEnumerator enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureList().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(T item) + { + EnsureList().Add(item); + } + + public void Clear() + { + EnsureList().Clear(); + } + + public bool Contains(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Contains(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + if (IsUndefined) + { + return; + } + EnsureList().CopyTo(array, arrayIndex); + } + + public bool Remove(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Remove(item); + } + + public int IndexOf(T item) + { + if (IsUndefined) + { + return -1; + } + return EnsureList().IndexOf(item); + } + + public void Insert(int index, T item) + { + EnsureList().Insert(index, item); + } + + public void RemoveAt(int index) + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList().RemoveAt(index); + } + + public IList EnsureList() + { + return _innerList ??= new List(); + } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 000000000000..bfa9471431fb --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,399 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Xml; +using Azure.Core; + +namespace Azure.Template.Contoso +{ + internal static class ModelSerializationExtensions + { + internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions { MaxDepth = 256 }; + internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); + + public static object GetObject(this JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.String: + return element.GetString(); + case JsonValueKind.Number: + if (element.TryGetInt32(out int intValue)) + { + return intValue; + } + if (element.TryGetInt64(out long longValue)) + { + return longValue; + } + return element.GetDouble(); + case JsonValueKind.True: + return true; + case JsonValueKind.False: + return false; + case JsonValueKind.Undefined: + case JsonValueKind.Null: + return null; + case JsonValueKind.Object: + var dictionary = new Dictionary(); + foreach (var jsonProperty in element.EnumerateObject()) + { + dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); + } + return dictionary; + case JsonValueKind.Array: + var list = new List(); + foreach (var item in element.EnumerateArray()) + { + list.Add(item.GetObject()); + } + return list.ToArray(); + default: + throw new NotSupportedException($"Not supported value kind {element.ValueKind}"); + } + } + + public static byte[] GetBytesFromBase64(this JsonElement element, string format) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + + return format switch + { + "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()), + "D" => element.GetBytesFromBase64(), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + } + + public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch + { + "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()), + _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format) + }; + + public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format); + + public static char GetChar(this JsonElement element) + { + if (element.ValueKind == JsonValueKind.String) + { + var text = element.GetString(); + if (text == null || text.Length != 1) + { + throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); + } + return text[0]; + } + else + { + throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char"); + } + } + + [Conditional("DEBUG")] + public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) + { + throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); + } + + public static string GetRequiredString(this JsonElement element) + { + var value = element.GetString(); + if (value == null) + { + throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); + } + return value; + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, char value) + { + writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + + public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + switch (format) + { + case "U": + writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value)); + break; + case "D": + writer.WriteBase64StringValue(value); + break; + default: + throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)); + } + } + + public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + if (format != "U") + { + throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number."); + } + writer.WriteNumberValue(value.ToUnixTimeSeconds()); + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) + { + switch (value) + { + case null: + writer.WriteNullValue(); + break; + case IJsonModel jsonModel: + jsonModel.Write(writer, options ?? WireOptions); + break; + case IUtf8JsonSerializable serializable: + serializable.Write(writer); + break; + case byte[] bytes: + writer.WriteBase64StringValue(bytes); + break; + case BinaryData bytes0: + writer.WriteBase64StringValue(bytes0); + break; + case JsonElement json: + json.WriteTo(writer); + break; + case int i: + writer.WriteNumberValue(i); + break; + case decimal d: + writer.WriteNumberValue(d); + break; + case double d0: + if (double.IsNaN(d0)) + { + writer.WriteStringValue("NaN"); + } + else + { + writer.WriteNumberValue(d0); + } + break; + case float f: + writer.WriteNumberValue(f); + break; + case long l: + writer.WriteNumberValue(l); + break; + case string s: + writer.WriteStringValue(s); + break; + case bool b: + writer.WriteBooleanValue(b); + break; + case Guid g: + writer.WriteStringValue(g); + break; + case DateTimeOffset dateTimeOffset: + writer.WriteStringValue(dateTimeOffset, "O"); + break; + case DateTime dateTime: + writer.WriteStringValue(dateTime, "O"); + break; + case IEnumerable> enumerable: + writer.WriteStartObject(); + foreach (var pair in enumerable) + { + writer.WritePropertyName(pair.Key); + writer.WriteObjectValue(pair.Value, options); + } + writer.WriteEndObject(); + break; + case IEnumerable objectEnumerable: + writer.WriteStartArray(); + foreach (var item in objectEnumerable) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + break; + case TimeSpan timeSpan: + writer.WriteStringValue(timeSpan, "P"); + break; + default: + throw new NotSupportedException($"Not supported type {value.GetType()}"); + } + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) + { + writer.WriteObjectValue(value, options); + } + + internal static class TypeFormatters + { + private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; + public const string DefaultNumberFormat = "G"; + + public static string ToString(bool value) => value ? "true" : "false"; + + public static string ToString(DateTime value, string format) => value.Kind switch + { + DateTimeKind.Utc => ToString((DateTimeOffset)value, format), + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") + }; + + public static string ToString(DateTimeOffset value, string format) => format switch + { + "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "R" => value.ToString("r", CultureInfo.InvariantCulture), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(TimeSpan value, string format) => format switch + { + "P" => XmlConvert.ToString(value), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(byte[] value, string format) => format switch + { + "U" => ToBase64UrlString(value), + "D" => Convert.ToBase64String(value), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + + public static string ToBase64UrlString(byte[] value) + { + int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; + int size = checked(numWholeOrPartialInputBlocks * 4); + char[] output = new char[size]; + + int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); + + int i = 0; + for (; i < numBase64Chars; i++) + { + char ch = output[i]; + if (ch == '+') + { + output[i] = '-'; + } + else + { + if (ch == '/') + { + output[i] = '_'; + } + else + { + if (ch == '=') + { + break; + } + } + } + } + + return new string(output, 0, i); + } + + public static byte[] FromBase64UrlString(string value) + { + int paddingCharsToAdd = (value.Length % 4) switch + { + 0 => 0, + 2 => 2, + 3 => 1, + _ => throw new InvalidOperationException("Malformed input") + }; + char[] output = new char[(value.Length + paddingCharsToAdd)]; + int i = 0; + for (; i < value.Length; i++) + { + char ch = value[i]; + if (ch == '-') + { + output[i] = '+'; + } + else + { + if (ch == '_') + { + output[i] = '/'; + } + else + { + output[i] = ch; + } + } + } + + for (; i < output.Length; i++) + { + output[i] = '='; + } + + return Convert.FromBase64CharArray(output, 0, output.Length); + } + + public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch + { + "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), + _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) + }; + + public static TimeSpan ParseTimeSpan(string value, string format) => format switch + { + "P" => XmlConvert.ToTimeSpan(value), + _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) + }; + + public static string ConvertToString(object value, string format = null) => value switch + { + null => "null", + string s => s, + bool b => ToString(b), + int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), + byte[] b0 when format != null => ToString(b0, format), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when format != null => ToString(dateTime, format), + TimeSpan timeSpan when format != null => ToString(timeSpan, format), + TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; + } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/Optional.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/Optional.cs new file mode 100644 index 000000000000..072e7659b006 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/Optional.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; + +namespace Azure.Template.Contoso +{ + internal static class Optional + { + public static bool IsCollectionDefined(IEnumerable collection) + { + return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined); + } + + public static bool IsCollectionDefined(IDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsCollectionDefined(IReadOnlyDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsDefined(T? value) + where T : struct + { + return value.HasValue; + } + + public static bool IsDefined(object value) + { + return value != null; + } + + public static bool IsDefined(JsonElement value) + { + return value.ValueKind != JsonValueKind.Undefined; + } + + public static bool IsDefined(string value) + { + return value != null; + } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 000000000000..6dbde35752a2 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace Azure.Template.Contoso +{ + internal class Utf8JsonRequestContent : RequestContent + { + private readonly MemoryStream _stream; + private readonly RequestContent _content; + + public Utf8JsonRequestContent() + { + _stream = new MemoryStream(); + _content = Create(_stream); + JsonWriter = new Utf8JsonWriter(_stream); + } + + public Utf8JsonWriter JsonWriter { get; } + + public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) + { + await JsonWriter.FlushAsync().ConfigureAwait(false); + await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); + } + + public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) + { + JsonWriter.Flush(); + _content.WriteTo(stream, cancellationToken); + } + + public override bool TryComputeLength(out long length) + { + length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; + return true; + } + + public override void Dispose() + { + JsonWriter.Dispose(); + _content.Dispose(); + _stream.Dispose(); + } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/OperationState.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/OperationState.cs new file mode 100644 index 000000000000..de05771393ce --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/OperationState.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.Template.Contoso +{ + /// Enum describing allowed operation states. + public readonly partial struct OperationState : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OperationState(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string NotStartedValue = "NotStarted"; + private const string RunningValue = "Running"; + private const string SucceededValue = "Succeeded"; + private const string FailedValue = "Failed"; + private const string CanceledValue = "Canceled"; + + /// The operation has not started. + public static OperationState NotStarted { get; } = new OperationState(NotStartedValue); + /// The operation is in progress. + public static OperationState Running { get; } = new OperationState(RunningValue); + /// The operation has completed successfully. + public static OperationState Succeeded { get; } = new OperationState(SucceededValue); + /// The operation has failed. + public static OperationState Failed { get; } = new OperationState(FailedValue); + /// The operation has been canceled by the user. + public static OperationState Canceled { get; } = new OperationState(CanceledValue); + /// Determines if two values are the same. + public static bool operator ==(OperationState left, OperationState right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OperationState left, OperationState right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OperationState(string value) => new OperationState(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OperationState other && Equals(other); + /// + public bool Equals(OperationState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/ResourceOperationStatusWidgetSuiteWidgetSuiteError.Serialization.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/ResourceOperationStatusWidgetSuiteWidgetSuiteError.Serialization.cs new file mode 100644 index 000000000000..3df98b2b0909 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/ResourceOperationStatusWidgetSuiteWidgetSuiteError.Serialization.cs @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Template.Contoso +{ + public partial class ResourceOperationStatusWidgetSuiteWidgetSuiteError : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ResourceOperationStatusWidgetSuiteWidgetSuiteError)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + if (Optional.IsDefined(Error)) + { + writer.WritePropertyName("error"u8); + JsonSerializer.Serialize(writer, Error); + } + if (Optional.IsDefined(Result)) + { + writer.WritePropertyName("result"u8); + writer.WriteObjectValue(Result, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ResourceOperationStatusWidgetSuiteWidgetSuiteError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ResourceOperationStatusWidgetSuiteWidgetSuiteError)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeResourceOperationStatusWidgetSuiteWidgetSuiteError(document.RootElement, options); + } + + internal static ResourceOperationStatusWidgetSuiteWidgetSuiteError DeserializeResourceOperationStatusWidgetSuiteWidgetSuiteError(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + OperationState status = default; + ResponseError error = default; + WidgetSuite result = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("status"u8)) + { + status = new OperationState(property.Value.GetString()); + continue; + } + if (property.NameEquals("error"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + error = JsonSerializer.Deserialize(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("result"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + result = WidgetSuite.DeserializeWidgetSuite(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ResourceOperationStatusWidgetSuiteWidgetSuiteError(id, status, error, result, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ResourceOperationStatusWidgetSuiteWidgetSuiteError)} does not support writing '{options.Format}' format."); + } + } + + ResourceOperationStatusWidgetSuiteWidgetSuiteError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeResourceOperationStatusWidgetSuiteWidgetSuiteError(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ResourceOperationStatusWidgetSuiteWidgetSuiteError)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ResourceOperationStatusWidgetSuiteWidgetSuiteError FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeResourceOperationStatusWidgetSuiteWidgetSuiteError(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/ResourceOperationStatusWidgetSuiteWidgetSuiteError.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/ResourceOperationStatusWidgetSuiteWidgetSuiteError.cs new file mode 100644 index 000000000000..d2a07ed0b367 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/ResourceOperationStatusWidgetSuiteWidgetSuiteError.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Template.Contoso +{ + /// Provides status details for long running operations. + public partial class ResourceOperationStatusWidgetSuiteWidgetSuiteError + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The unique ID of the operation. + /// The status of the operation. + /// is null. + internal ResourceOperationStatusWidgetSuiteWidgetSuiteError(string id, OperationState status) + { + Argument.AssertNotNull(id, nameof(id)); + + Id = id; + Status = status; + } + + /// Initializes a new instance of . + /// The unique ID of the operation. + /// The status of the operation. + /// Error object that describes the error when status is "Failed". + /// The result of the operation. + /// Keeps track of any properties unknown to the library. + internal ResourceOperationStatusWidgetSuiteWidgetSuiteError(string id, OperationState status, ResponseError error, WidgetSuite result, IDictionary serializedAdditionalRawData) + { + Id = id; + Status = status; + Error = error; + Result = result; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ResourceOperationStatusWidgetSuiteWidgetSuiteError() + { + } + + /// The unique ID of the operation. + public string Id { get; } + /// The status of the operation. + public OperationState Status { get; } + /// Error object that describes the error when status is "Failed". + public ResponseError Error { get; } + /// The result of the operation. + public WidgetSuite Result { get; } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/TemplateContosoClientBuilderExtensions.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/TemplateContosoClientBuilderExtensions.cs new file mode 100644 index 000000000000..34e50338c431 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/TemplateContosoClientBuilderExtensions.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core.Extensions; +using Azure.Template.Contoso; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class TemplateContosoClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// Service host. + public static IAzureClientBuilder AddWidgetManagerClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new WidgetManagerClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddWidgetManagerClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/TemplateContosoModelFactory.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/TemplateContosoModelFactory.cs new file mode 100644 index 000000000000..1a64eda68bce --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/TemplateContosoModelFactory.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.Template.Contoso +{ + /// Model factory for models. + public static partial class TemplateContosoModelFactory + { + /// Initializes a new instance of . + /// The widget name. + /// The ID of the widget's manufacturer. + /// The faked shared model. + /// A new instance for mocking. + public static WidgetSuite WidgetSuite(string name = null, string manufacturerId = null, FakedSharedModel sharedModel = null) + { + return new WidgetSuite(name, manufacturerId, sharedModel, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The unique ID of the operation. + /// The status of the operation. + /// Error object that describes the error when status is "Failed". + /// The result of the operation. + /// A new instance for mocking. + public static ResourceOperationStatusWidgetSuiteWidgetSuiteError ResourceOperationStatusWidgetSuiteWidgetSuiteError(string id = null, OperationState status = default, ResponseError error = null, WidgetSuite result = null) + { + return new ResourceOperationStatusWidgetSuiteWidgetSuiteError(id, status, error, result, serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/WidgetManagerClient.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/WidgetManagerClient.cs new file mode 100644 index 000000000000..a4d30b4e1fb2 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/WidgetManagerClient.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.Template.Contoso +{ + // Data plane generated client. + /// The WidgetManager service client. + public partial class WidgetManagerClient + { + private static readonly string[] AuthorizationScopes = new string[] { "https://contoso.azure.com/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + + /// 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 WidgetManagerClient for mocking. + protected WidgetManagerClient() + { + } + + /// Initializes a new instance of WidgetManagerClient. + /// Service host. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public WidgetManagerClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new WidgetManagerClientOptions()) + { + } + + /// Initializes a new instance of WidgetManagerClient. + /// Service host. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public WidgetManagerClient(Uri endpoint, TokenCredential credential, WidgetManagerClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new WidgetManagerClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + } + + /// Initializes a new instance of ContosoWidgets. + /// The API version to use for this operation. + /// is null. + public virtual ContosoWidgets GetContosoWidgetsClient(string apiVersion = "2022-12-01") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new ContosoWidgets(ClientDiagnostics, _pipeline, _tokenCredential, _endpoint, apiVersion); + } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/WidgetManagerClientOptions.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/WidgetManagerClientOptions.cs new file mode 100644 index 000000000000..c451e0c67e97 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/WidgetManagerClientOptions.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.Template.Contoso +{ + /// Client options for WidgetManagerClient. + public partial class WidgetManagerClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2022_12_01; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2022-12-01". + V2022_12_01 = 1, + } + + internal string Version { get; } + + /// Initializes new instance of WidgetManagerClientOptions. + public WidgetManagerClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2022_12_01 => "2022-12-01", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.Serialization.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/WidgetSuite.Serialization.cs similarity index 55% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.Serialization.cs rename to sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/WidgetSuite.Serialization.cs index 4fb71cbac633..a1a04807038a 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.Serialization.cs +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/WidgetSuite.Serialization.cs @@ -11,13 +11,13 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.Vision.Face +namespace Azure.Template.Contoso { - public partial class CreateLivenessWithVerifySessionResult : IUtf8JsonSerializable, IJsonModel + public partial class WidgetSuite : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,20 +28,23 @@ void IJsonModel.Write(Utf8JsonWriter writ /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionResult)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(WidgetSuite)} does not support writing '{format}' format."); } - writer.WritePropertyName("sessionId"u8); - writer.WriteStringValue(SessionId); - writer.WritePropertyName("authToken"u8); - writer.WriteStringValue(AuthToken); - if (Optional.IsDefined(VerifyImage)) + if (options.Format != "W") { - writer.WritePropertyName("verifyImage"u8); - writer.WriteObjectValue(VerifyImage, options); + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + writer.WritePropertyName("manufacturerId"u8); + writer.WriteStringValue(ManufacturerId); + if (Optional.IsDefined(SharedModel)) + { + writer.WritePropertyName("sharedModel"u8); + writer.WriteObjectValue(SharedModel, options); } if (options.Format != "W" && _serializedAdditionalRawData != null) { @@ -60,19 +63,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - CreateLivenessWithVerifySessionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + WidgetSuite IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionResult)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(WidgetSuite)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCreateLivenessWithVerifySessionResult(document.RootElement, options); + return DeserializeWidgetSuite(document.RootElement, options); } - internal static CreateLivenessWithVerifySessionResult DeserializeCreateLivenessWithVerifySessionResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static WidgetSuite DeserializeWidgetSuite(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -80,30 +83,30 @@ internal static CreateLivenessWithVerifySessionResult DeserializeCreateLivenessW { return null; } - string sessionId = default; - string authToken = default; - LivenessWithVerifyImage verifyImage = default; + string name = default; + string manufacturerId = default; + FakedSharedModel sharedModel = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("sessionId"u8)) + if (property.NameEquals("name"u8)) { - sessionId = property.Value.GetString(); + name = property.Value.GetString(); continue; } - if (property.NameEquals("authToken"u8)) + if (property.NameEquals("manufacturerId"u8)) { - authToken = property.Value.GetString(); + manufacturerId = property.Value.GetString(); continue; } - if (property.NameEquals("verifyImage"u8)) + if (property.NameEquals("sharedModel"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - verifyImage = LivenessWithVerifyImage.DeserializeLivenessWithVerifyImage(property.Value, options); + sharedModel = FakedSharedModel.DeserializeFakedSharedModel(property.Value, options); continue; } if (options.Format != "W") @@ -112,46 +115,46 @@ internal static CreateLivenessWithVerifySessionResult DeserializeCreateLivenessW } } serializedAdditionalRawData = rawDataDictionary; - return new CreateLivenessWithVerifySessionResult(sessionId, authToken, verifyImage, serializedAdditionalRawData); + return new WidgetSuite(name, manufacturerId, sharedModel, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionResult)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(WidgetSuite)} does not support writing '{options.Format}' format."); } } - CreateLivenessWithVerifySessionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + WidgetSuite IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateLivenessWithVerifySessionResult(document.RootElement, options); + return DeserializeWidgetSuite(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionResult)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(WidgetSuite)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static CreateLivenessWithVerifySessionResult FromResponse(Response response) + internal static WidgetSuite FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateLivenessWithVerifySessionResult(document.RootElement); + return DeserializeWidgetSuite(document.RootElement); } /// Convert into a . diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/WidgetSuite.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/WidgetSuite.cs new file mode 100644 index 000000000000..9ba44c829aa3 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Generated/WidgetSuite.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Template.Contoso +{ + /// A widget. + public partial class WidgetSuite + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The ID of the widget's manufacturer. + /// is null. + public WidgetSuite(string manufacturerId) + { + Argument.AssertNotNull(manufacturerId, nameof(manufacturerId)); + + ManufacturerId = manufacturerId; + } + + /// Initializes a new instance of . + /// The widget name. + /// The ID of the widget's manufacturer. + /// The faked shared model. + /// Keeps track of any properties unknown to the library. + internal WidgetSuite(string name, string manufacturerId, FakedSharedModel sharedModel, IDictionary serializedAdditionalRawData) + { + Name = name; + ManufacturerId = manufacturerId; + SharedModel = sharedModel; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal WidgetSuite() + { + } + + /// The widget name. + public string Name { get; } + /// The ID of the widget's manufacturer. + public string ManufacturerId { get; set; } + /// The faked shared model. + public FakedSharedModel SharedModel { get; set; } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Properties/AssemblyInfo.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..aa9fd891b234 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/src/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Azure.Template.Contoso.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] + +// Replace Microsoft.Test with the correct resource provider namepace for your service and uncomment. +// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/azure-services-resource-providers +// for the list of possible values. +[assembly: Azure.Core.AzureResourceProviderNamespace("Microsoft.Template")] diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/tests/Azure.Template.Contoso.Tests.csproj b/sdk/contosowidgetmanager/Azure.Template.Contoso/tests/Azure.Template.Contoso.Tests.csproj new file mode 100644 index 000000000000..9b79d892421f --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/tests/Azure.Template.Contoso.Tests.csproj @@ -0,0 +1,20 @@ + + + $(RequiredTargetFrameworks) + + $(NoWarn);CS1591 + + + + + + + + + + + + + + + diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/tests/Generated/Samples/Samples_ContosoWidgets.cs b/sdk/contosowidgetmanager/Azure.Template.Contoso/tests/Generated/Samples/Samples_ContosoWidgets.cs new file mode 100644 index 000000000000..7b7e63a134ef --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/tests/Generated/Samples/Samples_ContosoWidgets.cs @@ -0,0 +1,287 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Azure.Template.Contoso.Samples +{ + public partial class Samples_ContosoWidgets + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_WidgetSuite_GetWidget_GetWidgetByWidgetName() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + Response response = client.GetWidget("searchbox", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("manufacturerId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_WidgetSuite_GetWidget_GetWidgetByWidgetName_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + Response response = await client.GetWidgetAsync("searchbox", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("manufacturerId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_WidgetSuite_GetWidget_GetWidgetByWidgetName_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + Response response = client.GetWidget("searchbox"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_WidgetSuite_GetWidget_GetWidgetByWidgetName_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + Response response = await client.GetWidgetAsync("searchbox"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ResourceOperationStatus_GetWidgetOperationStatus_WidgetsGetWidgetOperationStatus() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + Response response = client.GetWidgetOperationStatus("name1", "opreation id1", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ResourceOperationStatus_GetWidgetOperationStatus_WidgetsGetWidgetOperationStatus_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + Response response = await client.GetWidgetOperationStatusAsync("name1", "opreation id1", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_ResourceOperationStatus_GetWidgetOperationStatus_WidgetsGetWidgetOperationStatus_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + Response response = client.GetWidgetOperationStatus("name1", "opreation id1"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_ResourceOperationStatus_GetWidgetOperationStatus_WidgetsGetWidgetOperationStatus_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + Response response = await client.GetWidgetOperationStatusAsync("name1", "opreation id1"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_WidgetSuite_GetWidgets_WidgetsListWidgets() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + foreach (BinaryData item in client.GetWidgets(null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("manufacturerId").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_WidgetSuite_GetWidgets_WidgetsListWidgets_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + await foreach (BinaryData item in client.GetWidgetsAsync(null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("manufacturerId").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_WidgetSuite_GetWidgets_WidgetsListWidgets_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + foreach (WidgetSuite item in client.GetWidgets()) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_WidgetSuite_GetWidgets_WidgetsListWidgets_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + await foreach (WidgetSuite item in client.GetWidgetsAsync()) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_WidgetSuite_CreateOrUpdateWidget_WidgetsCreateOrUpdateWidget() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + using RequestContent content = RequestContent.Create(new + { + manufacturerId = "manufacturer id1", + sharedModel = new + { + tag = "tag1", + createdAt = "2023-01-09T02:12:25.689Z", + }, + }); + Operation operation = client.CreateOrUpdateWidget(WaitUntil.Completed, "name1", content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("manufacturerId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_WidgetSuite_CreateOrUpdateWidget_WidgetsCreateOrUpdateWidget_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + using RequestContent content = RequestContent.Create(new + { + manufacturerId = "manufacturer id1", + sharedModel = new + { + tag = "tag1", + createdAt = "2023-01-09T02:12:25.689Z", + }, + }); + Operation operation = await client.CreateOrUpdateWidgetAsync(WaitUntil.Completed, "name1", content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("manufacturerId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_WidgetSuite_DeleteWidget_DeleteWidgetByWidgetNameUsingLongRunningOperation() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + Operation operation = client.DeleteWidget(WaitUntil.Completed, "searchbox", null); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("manufacturerId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_WidgetSuite_DeleteWidget_DeleteWidgetByWidgetNameUsingLongRunningOperation_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + Operation operation = await client.DeleteWidgetAsync(WaitUntil.Completed, "searchbox", null); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("manufacturerId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_WidgetSuite_DeleteWidget_DeleteWidgetByWidgetNameUsingLongRunningOperation_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + Operation operation = client.DeleteWidget(WaitUntil.Completed, "searchbox"); + WidgetSuite responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_WidgetSuite_DeleteWidget_DeleteWidgetByWidgetNameUsingLongRunningOperation_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + ContosoWidgets client = new WidgetManagerClient(endpoint, credential).GetContosoWidgetsClient(apiVersion: "2022-12-01"); + + Operation operation = await client.DeleteWidgetAsync(WaitUntil.Completed, "searchbox"); + WidgetSuite responseData = operation.Value; + } + } +} diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/tsp-location.yaml b/sdk/contosowidgetmanager/Azure.Template.Contoso/tsp-location.yaml new file mode 100644 index 000000000000..b2e61cbeaaf0 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/tsp-location.yaml @@ -0,0 +1,5 @@ +directory: specification/contosowidgetmanager/Contoso.WidgetManager +commit: e86f9dade22bbb783fde4ee2879b0bf1cc3f9ec0 +repo: Azure/azure-rest-api-specs +additionalDirectories: +- specification/contosowidgetmanager/Contoso.WidgetManager.Shared diff --git a/sdk/pineconevectordb/ci.yml b/sdk/contosowidgetmanager/ci.yml similarity index 51% rename from sdk/pineconevectordb/ci.yml rename to sdk/contosowidgetmanager/ci.yml index 0b8325c8c903..7f76decbce9e 100644 --- a/sdk/pineconevectordb/ci.yml +++ b/sdk/contosowidgetmanager/ci.yml @@ -8,9 +8,9 @@ trigger: - release/* paths: include: - - sdk/pineconevectordb - - sdk/pineconevectordb/ci.yml - - sdk/pineconevectordb/Azure.ResourceManager.PineconeVectorDb + - sdk/contosowidgetmanager + - sdk/contosowidgetmanager/ci.yml + - sdk/contosowidgetmanager/Azure.Template.Contoso pr: branches: @@ -21,15 +21,15 @@ pr: - release/* paths: include: - - sdk/pineconevectordb - - sdk/pineconevectordb/ci.yml - - sdk/pineconevectordb/Azure.ResourceManager.PineconeVectorDb + - sdk/contosowidgetmanager + - sdk/contosowidgetmanager/ci.yml + - sdk/contosowidgetmanager/Azure.Template.Contoso extends: template: /eng/pipelines/templates/stages/archetype-sdk-client.yml parameters: - ServiceDirectory: pineconevectordb + ServiceDirectory: contosowidgetmanager ArtifactName: packages Artifacts: - - name: Azure.ResourceManager.PineconeVectorDb - safeName: AzureResourceManagerPineconeVectorDb + - name: Azure.Template.Contoso + safeName: AzureTemplateContoso diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/AIVisionFaceModelFactory.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/AIVisionFaceModelFactory.cs index 3c74552a2652..543f92175321 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/AIVisionFaceModelFactory.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/AIVisionFaceModelFactory.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; namespace Azure.AI.Vision.Face @@ -299,239 +300,206 @@ public static FaceIdentificationCandidate FaceIdentificationCandidate(Guid perso /// Initializes a new instance of . /// Type of liveness mode the client should follow. - /// Whether or not to allow a '200 - Success' response body to be sent to the client, which may be undesirable for security reasons. Default is false, clients will receive a '204 - NoContent' empty body response. Regardless of selection, calling Session GetResult will always contain a response body enabling business logic to be implemented. /// Whether or not to allow client to set their own 'deviceCorrelationId' via the Vision SDK. Default is false, and 'deviceCorrelationId' must be set in this request body. /// Whether or not store the session image. - /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. /// A new instance for mocking. - public static CreateLivenessSessionContent CreateLivenessSessionContent(LivenessOperationMode livenessOperationMode = default, bool? sendResultsToClient = null, bool? deviceCorrelationIdSetInClient = null, bool? enableSessionImage = null, LivenessModel? livenessSingleModalModel = null, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null) + public static CreateLivenessSessionContent CreateLivenessSessionContent(LivenessOperationMode livenessOperationMode = default, bool? deviceCorrelationIdSetInClient = null, bool? enableSessionImage = null, LivenessModel? livenessModelVersion = null, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null) { return new CreateLivenessSessionContent( livenessOperationMode, - sendResultsToClient, deviceCorrelationIdSetInClient, enableSessionImage, - livenessSingleModalModel, + livenessModelVersion, deviceCorrelationId, authTokenTimeToLiveInSeconds, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - /// A new instance for mocking. - public static CreateLivenessSessionResult CreateLivenessSessionResult(string sessionId = null, string authToken = null) - { - return new CreateLivenessSessionResult(sessionId, authToken, serializedAdditionalRawData: null); - } - /// Initializes a new instance of . - /// The unique ID to reference this session. - /// DateTime when this session was created. - /// DateTime when this session was started by the client. - /// Whether or not the session is expired. - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. + /// The unique ID to reference this session. + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. /// The current status of the session. - /// The latest session audit result only populated if status == 'ResultAvailable'. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The results of the liveness session. /// A new instance for mocking. - public static LivenessSession LivenessSession(string id = null, DateTimeOffset createdDateTime = default, DateTimeOffset? sessionStartDateTime = null, bool sessionExpired = default, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null, FaceSessionStatus status = default, LivenessSessionAuditEntry result = null) + public static LivenessSession LivenessSession(string sessionId = null, string authToken = null, OperationState status = default, LivenessModel? modelVersion = null, LivenessSessionResults results = null) { return new LivenessSession( - id, - createdDateTime, - sessionStartDateTime, - sessionExpired, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + sessionId, + authToken, status, - result, + modelVersion, + results, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The unique id to refer to this audit request. Use this id with the 'start' query parameter to continue on to the next page of audit results. - /// The unique sessionId of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding session DELETE operation. - /// The unique requestId that is returned by the service to the client in the 'apim-request-id' header. - /// The unique clientRequestId that is sent by the client in the 'client-request-id' header. - /// The UTC DateTime that the request was received. - /// The request of this entry. - /// The response of this entry. - /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. - /// The image ID of the session request. - /// The sha256 hash of the verify-image in the request. - /// A new instance for mocking. - public static LivenessSessionAuditEntry LivenessSessionAuditEntry(long id = default, string sessionId = null, string requestId = null, string clientRequestId = null, DateTimeOffset receivedDateTime = default, AuditRequestInfo request = null, AuditLivenessResponseInfo response = null, string digest = null, string sessionImageId = null, string verifyImageHash = null) + /// Initializes a new instance of . + /// The attempts data of underlying liveness call with the session. + /// A new instance for mocking. + public static LivenessSessionResults LivenessSessionResults(IEnumerable attempts = null) { - return new LivenessSessionAuditEntry( - id, - sessionId, - requestId, - clientRequestId, - receivedDateTime, - request, - response, - digest, - sessionImageId, - verifyImageHash, - serializedAdditionalRawData: null); - } + attempts ??= new List(); - /// Initializes a new instance of . - /// The relative URL and query of the liveness request. - /// The HTTP method of the request (i.e., GET, POST, DELETE). - /// The length of the request body in bytes. - /// The content type of the request. - /// The user agent used to submit the request. - /// A new instance for mocking. - public static AuditRequestInfo AuditRequestInfo(string url = null, string method = null, long? contentLength = null, string contentType = null, string userAgent = null) - { - return new AuditRequestInfo( - url, - method, - contentLength, - contentType, - userAgent, - serializedAdditionalRawData: null); + return new LivenessSessionResults(attempts?.ToList(), serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The response body. The schema of this field will depend on the request.url and request.method used by the client. - /// The HTTP status code returned to the client. - /// The server measured latency for this request in milliseconds. - /// A new instance for mocking. - public static AuditLivenessResponseInfo AuditLivenessResponseInfo(LivenessResponseBody body = null, int statusCode = default, long latencyInMilliseconds = default) + /// Initializes a new instance of . + /// The attempt ID, start from 1. + /// The status of the attempt. + /// The result of the liveness call, will be null if there is error. + /// The error of the liveness call, will be null if there is result. + /// A new instance for mocking. + public static LivenessSessionAttempt LivenessSessionAttempt(int attemptId = default, OperationState attemptStatus = default, LivenessResult result = null, LivenessError error = null) { - return new AuditLivenessResponseInfo(body, statusCode, latencyInMilliseconds, serializedAdditionalRawData: null); + return new LivenessSessionAttempt(attemptId, attemptStatus, result, error, serializedAdditionalRawData: null); } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The liveness classification for the target face. - /// Specific targets used for liveness classification. - /// The model version used for liveness classification. - /// The face verification output. Only available when the request is liveness with verify. - /// Additional Properties. - /// A new instance for mocking. - public static LivenessResponseBody LivenessResponseBody(FaceLivenessDecision? livenessDecision = null, LivenessOutputsTarget target = null, LivenessModel? modelVersionUsed = null, LivenessWithVerifyOutputs verifyResult = null, IReadOnlyDictionary additionalProperties = null) - { - additionalProperties ??= new Dictionary(); - - return new LivenessResponseBody(livenessDecision, target, modelVersionUsed, verifyResult, additionalProperties); - } - - /// Initializes a new instance of . - /// The face region where the liveness classification was made on. - /// The file name which contains the face rectangle where the liveness classification was made on. - /// The time offset within the file of the frame which contains the face rectangle where the liveness classification was made on. - /// The image type which contains the face rectangle where the liveness classification was made on. - /// A new instance for mocking. - public static LivenessOutputsTarget LivenessOutputsTarget(FaceRectangle faceRectangle = null, string fileName = null, int timeOffsetWithinFile = default, FaceImageType imageType = default) + /// Targets used for liveness classification. + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + /// The image ID of the session request. + /// A new instance for mocking. + public static LivenessResult LivenessResult(FaceLivenessDecision? livenessDecision = null, LivenessDecisionTargets targets = null, string digest = null, string sessionImageId = null) { - return new LivenessOutputsTarget(faceRectangle, fileName, timeOffsetWithinFile, imageType, serializedAdditionalRawData: null); + return new LivenessResult(livenessDecision, targets, digest, sessionImageId, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The detail of face for verification. - /// The target face liveness face and comparison image face verification confidence. - /// Whether the target liveness face and comparison image face match. - /// A new instance for mocking. - public static LivenessWithVerifyOutputs LivenessWithVerifyOutputs(LivenessWithVerifyImage verifyImage = null, float matchConfidence = default, bool isIdentical = default) + /// Initializes a new instance of . + /// The target from color image used for liveness classification. + /// A new instance for mocking. + public static LivenessDecisionTargets LivenessDecisionTargets(LivenessColorDecisionTarget color = null) { - return new LivenessWithVerifyOutputs(verifyImage, matchConfidence, isIdentical, serializedAdditionalRawData: null); + return new LivenessDecisionTargets(color, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The face region where the comparison image's classification was made. - /// Quality of face image for recognition. - /// A new instance for mocking. - public static LivenessWithVerifyImage LivenessWithVerifyImage(FaceRectangle faceRectangle = null, QualityForRecognition qualityForRecognition = default) + /// Initializes a new instance of . + /// The face region where the liveness classification was made on. + /// A new instance for mocking. + public static LivenessColorDecisionTarget LivenessColorDecisionTarget(FaceRectangle faceRectangle = null) { - return new LivenessWithVerifyImage(faceRectangle, qualityForRecognition, serializedAdditionalRawData: null); + return new LivenessColorDecisionTarget(faceRectangle, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The unique ID to reference this session. - /// DateTime when this session was created. - /// DateTime when this session was started by the client. - /// Whether or not the session is expired. - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - /// A new instance for mocking. - public static LivenessSessionItem LivenessSessionItem(string id = null, DateTimeOffset createdDateTime = default, DateTimeOffset? sessionStartDateTime = null, bool sessionExpired = default, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null) + /// Initializes a new instance of . + /// The error code. + /// The error message. + /// Targets used for liveness classification. + /// A new instance for mocking. + public static LivenessError LivenessError(string code = null, string message = null, LivenessDecisionTargets targets = null) { - return new LivenessSessionItem( - id, - createdDateTime, - sessionStartDateTime, - sessionExpired, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, - serializedAdditionalRawData: null); + return new LivenessError(code, message, targets, serializedAdditionalRawData: null); } /// Initializes a new instance of . /// Type of liveness mode the client should follow. - /// Whether or not to allow a '200 - Success' response body to be sent to the client, which may be undesirable for security reasons. Default is false, clients will receive a '204 - NoContent' empty body response. Regardless of selection, calling Session GetResult will always contain a response body enabling business logic to be implemented. /// Whether or not to allow client to set their own 'deviceCorrelationId' via the Vision SDK. Default is false, and 'deviceCorrelationId' must be set in this request body. /// Whether or not store the session image. - /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// Whether or not return the verify image hash. + /// Threshold for confidence of the face verification. Please refer to the documentation for more details. https://learn.microsoft.com/legal/cognitive-services/face/characteristics-and-limitations?context=%2Fazure%2Fai-services%2Fcomputer-vision%2Fcontext%2Fcontext#recognition-confidence-score. + /// The image stream for verify. Content-Disposition header field for this part must have filename. /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - /// Whether or not return the verify image hash. - /// Threshold for confidence of the face verification. /// A new instance for mocking. - public static CreateLivenessWithVerifySessionContent CreateLivenessWithVerifySessionContent(LivenessOperationMode livenessOperationMode = default, bool? sendResultsToClient = null, bool? deviceCorrelationIdSetInClient = null, bool? enableSessionImage = null, LivenessModel? livenessSingleModalModel = null, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null, bool? returnVerifyImageHash = null, float? verifyConfidenceThreshold = null) + public static CreateLivenessWithVerifySessionContent CreateLivenessWithVerifySessionContent(LivenessOperationMode livenessOperationMode = default, bool? deviceCorrelationIdSetInClient = null, bool? enableSessionImage = null, LivenessModel? livenessModelVersion = null, bool? returnVerifyImageHash = null, float? verifyConfidenceThreshold = null, Stream verifyImage = null, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null) { return new CreateLivenessWithVerifySessionContent( livenessOperationMode, - sendResultsToClient, deviceCorrelationIdSetInClient, enableSessionImage, - livenessSingleModalModel, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + livenessModelVersion, returnVerifyImageHash, verifyConfidenceThreshold, + verifyImage, + deviceCorrelationId, + authTokenTimeToLiveInSeconds, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - /// The detail of face for verification. - /// A new instance for mocking. - public static CreateLivenessWithVerifySessionResult CreateLivenessWithVerifySessionResult(string sessionId = null, string authToken = null, LivenessWithVerifyImage verifyImage = null) - { - return new CreateLivenessWithVerifySessionResult(sessionId, authToken, verifyImage, serializedAdditionalRawData: null); - } - /// Initializes a new instance of . - /// The unique ID to reference this session. - /// DateTime when this session was created. - /// DateTime when this session was started by the client. - /// Whether or not the session is expired. - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. + /// The unique ID to reference this session. + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. /// The current status of the session. - /// The latest session audit result only populated if status == 'ResultAvailable'. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The results of the liveness with verify session. /// A new instance for mocking. - public static LivenessWithVerifySession LivenessWithVerifySession(string id = null, DateTimeOffset createdDateTime = default, DateTimeOffset? sessionStartDateTime = null, bool sessionExpired = default, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null, FaceSessionStatus status = default, LivenessSessionAuditEntry result = null) + public static LivenessWithVerifySession LivenessWithVerifySession(string sessionId = null, string authToken = null, OperationState status = default, LivenessModel? modelVersion = null, LivenessWithVerifySessionResults results = null) { return new LivenessWithVerifySession( - id, - createdDateTime, - sessionStartDateTime, - sessionExpired, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + sessionId, + authToken, status, - result, + modelVersion, + results, serializedAdditionalRawData: null); } + /// Initializes a new instance of . + /// The references used for face verification. + /// The attempts data of underlying liveness with verify call with the session. + /// A new instance for mocking. + public static LivenessWithVerifySessionResults LivenessWithVerifySessionResults(IEnumerable verifyReferences = null, IEnumerable attempts = null) + { + verifyReferences ??= new List(); + attempts ??= new List(); + + return new LivenessWithVerifySessionResults(verifyReferences?.ToList(), attempts?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The image type which contains the face rectangle where the liveness classification was made on. + /// The face region where the comparison image's classification was made. + /// Quality of face image for recognition. + /// A new instance for mocking. + public static LivenessWithVerifyReference LivenessWithVerifyReference(FaceImageType referenceType = default, FaceRectangle faceRectangle = null, QualityForRecognition qualityForRecognition = default) + { + return new LivenessWithVerifyReference(referenceType, faceRectangle, qualityForRecognition, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The attempt ID, start from 1. + /// The status of the attempt. + /// The result of the liveness with verify call, will be null if there is error. + /// The error of the liveness with verify call, will be null if there is result. + /// A new instance for mocking. + public static LivenessWithVerifySessionAttempt LivenessWithVerifySessionAttempt(int attemptId = default, OperationState attemptStatus = default, LivenessWithVerifyResult result = null, LivenessError error = null) + { + return new LivenessWithVerifySessionAttempt(attemptId, attemptStatus, result, error, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The liveness classification for the target face. + /// Targets used for liveness classification. + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + /// The image ID of the session request. + /// The face verification output. Only available when the request is liveness with verify. + /// The sha256 hash of the verify-image in the request. + /// A new instance for mocking. + public static LivenessWithVerifyResult LivenessWithVerifyResult(FaceLivenessDecision? livenessDecision = null, LivenessDecisionTargets targets = null, string digest = null, string sessionImageId = null, LivenessWithVerifyOutputs verifyResult = null, string verifyImageHash = null) + { + return new LivenessWithVerifyResult( + livenessDecision, + targets, + digest, + sessionImageId, + verifyResult, + verifyImageHash, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The target face liveness face and comparison image face verification confidence. + /// Whether the target liveness face and comparison image face match. + /// A new instance for mocking. + public static LivenessWithVerifyOutputs LivenessWithVerifyOutputs(float matchConfidence = default, bool isIdentical = default) + { + return new LivenessWithVerifyOutputs(matchConfidence, isIdentical, serializedAdditionalRawData: null); + } + /// Initializes a new instance of . /// User defined name, maximum length is 128. /// Optional user defined data. Length should not exceed 16K. diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.cs deleted file mode 100644 index 3448b284f8e3..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// Audit entry for a response in the session. - public partial class AuditLivenessResponseInfo - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The response body. The schema of this field will depend on the request.url and request.method used by the client. - /// The HTTP status code returned to the client. - /// The server measured latency for this request in milliseconds. - /// is null. - internal AuditLivenessResponseInfo(LivenessResponseBody body, int statusCode, long latencyInMilliseconds) - { - Argument.AssertNotNull(body, nameof(body)); - - Body = body; - StatusCode = statusCode; - LatencyInMilliseconds = latencyInMilliseconds; - } - - /// Initializes a new instance of . - /// The response body. The schema of this field will depend on the request.url and request.method used by the client. - /// The HTTP status code returned to the client. - /// The server measured latency for this request in milliseconds. - /// Keeps track of any properties unknown to the library. - internal AuditLivenessResponseInfo(LivenessResponseBody body, int statusCode, long latencyInMilliseconds, IDictionary serializedAdditionalRawData) - { - Body = body; - StatusCode = statusCode; - LatencyInMilliseconds = latencyInMilliseconds; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal AuditLivenessResponseInfo() - { - } - - /// The response body. The schema of this field will depend on the request.url and request.method used by the client. - public LivenessResponseBody Body { get; } - /// The HTTP status code returned to the client. - public int StatusCode { get; } - /// The server measured latency for this request in milliseconds. - public long LatencyInMilliseconds { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.cs deleted file mode 100644 index 39356d1eb8f8..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// Audit entry for a request in the session. - public partial class AuditRequestInfo - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The relative URL and query of the liveness request. - /// The HTTP method of the request (i.e., GET, POST, DELETE). - /// The content type of the request. - /// , or is null. - internal AuditRequestInfo(string url, string method, string contentType) - { - Argument.AssertNotNull(url, nameof(url)); - Argument.AssertNotNull(method, nameof(method)); - Argument.AssertNotNull(contentType, nameof(contentType)); - - Url = url; - Method = method; - ContentType = contentType; - } - - /// Initializes a new instance of . - /// The relative URL and query of the liveness request. - /// The HTTP method of the request (i.e., GET, POST, DELETE). - /// The length of the request body in bytes. - /// The content type of the request. - /// The user agent used to submit the request. - /// Keeps track of any properties unknown to the library. - internal AuditRequestInfo(string url, string method, long? contentLength, string contentType, string userAgent, IDictionary serializedAdditionalRawData) - { - Url = url; - Method = method; - ContentLength = contentLength; - ContentType = contentType; - UserAgent = userAgent; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal AuditRequestInfo() - { - } - - /// The relative URL and query of the liveness request. - public string Url { get; } - /// The HTTP method of the request (i.e., GET, POST, DELETE). - public string Method { get; } - /// The length of the request body in bytes. - public long? ContentLength { get; } - /// The content type of the request. - public string ContentType { get; } - /// The user agent used to submit the request. - public string UserAgent { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/AzureAIVisionFaceClientOptions.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/AzureAIVisionFaceClientOptions.cs index a27f25f2a008..6790ac937886 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/AzureAIVisionFaceClientOptions.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/AzureAIVisionFaceClientOptions.cs @@ -13,7 +13,7 @@ namespace Azure.AI.Vision.Face /// Client options for Azure.AI.Vision.Face library clients. public partial class AzureAIVisionFaceClientOptions : ClientOptions { - private const ServiceVersion LatestVersion = ServiceVersion.V1_2_Preview_1; + private const ServiceVersion LatestVersion = ServiceVersion.V1_2; /// The version of the service to use. public enum ServiceVersion @@ -22,6 +22,8 @@ public enum ServiceVersion V1_1_Preview_1 = 1, /// Service version "v1.2-preview.1". V1_2_Preview_1 = 2, + /// Service version "v1.2". + V1_2 = 3, } internal string Version { get; } @@ -33,6 +35,7 @@ public AzureAIVisionFaceClientOptions(ServiceVersion version = LatestVersion) { ServiceVersion.V1_1_Preview_1 => "v1.1-preview.1", ServiceVersion.V1_2_Preview_1 => "v1.2-preview.1", + ServiceVersion.V1_2 => "v1.2", _ => throw new NotSupportedException() }; } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.Serialization.cs index 4c6879d0bbf9..a7d64fe5bb32 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.Serialization.cs @@ -36,11 +36,6 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("livenessOperationMode"u8); writer.WriteStringValue(LivenessOperationMode.ToString()); - if (Optional.IsDefined(SendResultsToClient)) - { - writer.WritePropertyName("sendResultsToClient"u8); - writer.WriteBooleanValue(SendResultsToClient.Value); - } if (Optional.IsDefined(DeviceCorrelationIdSetInClient)) { writer.WritePropertyName("deviceCorrelationIdSetInClient"u8); @@ -51,10 +46,10 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("enableSessionImage"u8); writer.WriteBooleanValue(EnableSessionImage.Value); } - if (Optional.IsDefined(LivenessSingleModalModel)) + if (Optional.IsDefined(LivenessModelVersion)) { - writer.WritePropertyName("livenessSingleModalModel"u8); - writer.WriteStringValue(LivenessSingleModalModel.Value.ToString()); + writer.WritePropertyName("livenessModelVersion"u8); + writer.WriteStringValue(LivenessModelVersion.Value.ToString()); } if (Optional.IsDefined(DeviceCorrelationId)) { @@ -104,10 +99,9 @@ internal static CreateLivenessSessionContent DeserializeCreateLivenessSessionCon return null; } LivenessOperationMode livenessOperationMode = default; - bool? sendResultsToClient = default; bool? deviceCorrelationIdSetInClient = default; bool? enableSessionImage = default; - LivenessModel? livenessSingleModalModel = default; + LivenessModel? livenessModelVersion = default; string deviceCorrelationId = default; int? authTokenTimeToLiveInSeconds = default; IDictionary serializedAdditionalRawData = default; @@ -119,15 +113,6 @@ internal static CreateLivenessSessionContent DeserializeCreateLivenessSessionCon livenessOperationMode = new LivenessOperationMode(property.Value.GetString()); continue; } - if (property.NameEquals("sendResultsToClient"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sendResultsToClient = property.Value.GetBoolean(); - continue; - } if (property.NameEquals("deviceCorrelationIdSetInClient"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -146,13 +131,13 @@ internal static CreateLivenessSessionContent DeserializeCreateLivenessSessionCon enableSessionImage = property.Value.GetBoolean(); continue; } - if (property.NameEquals("livenessSingleModalModel"u8)) + if (property.NameEquals("livenessModelVersion"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - livenessSingleModalModel = new LivenessModel(property.Value.GetString()); + livenessModelVersion = new LivenessModel(property.Value.GetString()); continue; } if (property.NameEquals("deviceCorrelationId"u8)) @@ -177,10 +162,9 @@ internal static CreateLivenessSessionContent DeserializeCreateLivenessSessionCon serializedAdditionalRawData = rawDataDictionary; return new CreateLivenessSessionContent( livenessOperationMode, - sendResultsToClient, deviceCorrelationIdSetInClient, enableSessionImage, - livenessSingleModalModel, + livenessModelVersion, deviceCorrelationId, authTokenTimeToLiveInSeconds, serializedAdditionalRawData); diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.cs index 9de38ee841c6..66e9ce0ec227 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.cs @@ -54,20 +54,18 @@ public CreateLivenessSessionContent(LivenessOperationMode livenessOperationMode) /// Initializes a new instance of . /// Type of liveness mode the client should follow. - /// Whether or not to allow a '200 - Success' response body to be sent to the client, which may be undesirable for security reasons. Default is false, clients will receive a '204 - NoContent' empty body response. Regardless of selection, calling Session GetResult will always contain a response body enabling business logic to be implemented. /// Whether or not to allow client to set their own 'deviceCorrelationId' via the Vision SDK. Default is false, and 'deviceCorrelationId' must be set in this request body. /// Whether or not store the session image. - /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. /// Keeps track of any properties unknown to the library. - internal CreateLivenessSessionContent(LivenessOperationMode livenessOperationMode, bool? sendResultsToClient, bool? deviceCorrelationIdSetInClient, bool? enableSessionImage, LivenessModel? livenessSingleModalModel, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, IDictionary serializedAdditionalRawData) + internal CreateLivenessSessionContent(LivenessOperationMode livenessOperationMode, bool? deviceCorrelationIdSetInClient, bool? enableSessionImage, LivenessModel? livenessModelVersion, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, IDictionary serializedAdditionalRawData) { LivenessOperationMode = livenessOperationMode; - SendResultsToClient = sendResultsToClient; DeviceCorrelationIdSetInClient = deviceCorrelationIdSetInClient; EnableSessionImage = enableSessionImage; - LivenessSingleModalModel = livenessSingleModalModel; + LivenessModelVersion = livenessModelVersion; DeviceCorrelationId = deviceCorrelationId; AuthTokenTimeToLiveInSeconds = authTokenTimeToLiveInSeconds; _serializedAdditionalRawData = serializedAdditionalRawData; @@ -80,14 +78,12 @@ internal CreateLivenessSessionContent() /// Type of liveness mode the client should follow. public LivenessOperationMode LivenessOperationMode { get; } - /// Whether or not to allow a '200 - Success' response body to be sent to the client, which may be undesirable for security reasons. Default is false, clients will receive a '204 - NoContent' empty body response. Regardless of selection, calling Session GetResult will always contain a response body enabling business logic to be implemented. - public bool? SendResultsToClient { get; set; } /// Whether or not to allow client to set their own 'deviceCorrelationId' via the Vision SDK. Default is false, and 'deviceCorrelationId' must be set in this request body. public bool? DeviceCorrelationIdSetInClient { get; set; } /// Whether or not store the session image. public bool? EnableSessionImage { get; set; } /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. - public LivenessModel? LivenessSingleModalModel { get; set; } + public LivenessModel? LivenessModelVersion { get; set; } /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. public string DeviceCorrelationId { get; set; } /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.cs deleted file mode 100644 index cf8e5b8e2c7f..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// Response of liveness session creation. - public partial class CreateLivenessSessionResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - /// or is null. - internal CreateLivenessSessionResult(string sessionId, string authToken) - { - Argument.AssertNotNull(sessionId, nameof(sessionId)); - Argument.AssertNotNull(authToken, nameof(authToken)); - - SessionId = sessionId; - AuthToken = authToken; - } - - /// Initializes a new instance of . - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - /// Keeps track of any properties unknown to the library. - internal CreateLivenessSessionResult(string sessionId, string authToken, IDictionary serializedAdditionalRawData) - { - SessionId = sessionId; - AuthToken = authToken; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal CreateLivenessSessionResult() - { - } - - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - public string SessionId { get; } - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - public string AuthToken { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.Serialization.cs index 27a9c425fb45..20c081c13629 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.Serialization.cs @@ -8,6 +8,7 @@ using System; using System.ClientModel.Primitives; using System.Collections.Generic; +using System.IO; using System.Text.Json; using Azure.Core; @@ -36,11 +37,6 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("livenessOperationMode"u8); writer.WriteStringValue(LivenessOperationMode.ToString()); - if (Optional.IsDefined(SendResultsToClient)) - { - writer.WritePropertyName("sendResultsToClient"u8); - writer.WriteBooleanValue(SendResultsToClient.Value); - } if (Optional.IsDefined(DeviceCorrelationIdSetInClient)) { writer.WritePropertyName("deviceCorrelationIdSetInClient"u8); @@ -51,20 +47,10 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("enableSessionImage"u8); writer.WriteBooleanValue(EnableSessionImage.Value); } - if (Optional.IsDefined(LivenessSingleModalModel)) + if (Optional.IsDefined(LivenessModelVersion)) { - writer.WritePropertyName("livenessSingleModalModel"u8); - writer.WriteStringValue(LivenessSingleModalModel.Value.ToString()); - } - if (Optional.IsDefined(DeviceCorrelationId)) - { - writer.WritePropertyName("deviceCorrelationId"u8); - writer.WriteStringValue(DeviceCorrelationId); - } - if (Optional.IsDefined(AuthTokenTimeToLiveInSeconds)) - { - writer.WritePropertyName("authTokenTimeToLiveInSeconds"u8); - writer.WriteNumberValue(AuthTokenTimeToLiveInSeconds.Value); + writer.WritePropertyName("livenessModelVersion"u8); + writer.WriteStringValue(LivenessModelVersion.Value.ToString()); } if (Optional.IsDefined(ReturnVerifyImageHash)) { @@ -76,6 +62,25 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("verifyConfidenceThreshold"u8); writer.WriteNumberValue(VerifyConfidenceThreshold.Value); } + writer.WritePropertyName("verifyImage"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(global::System.BinaryData.FromStream(VerifyImage)); +#else + using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(VerifyImage), ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (Optional.IsDefined(DeviceCorrelationId)) + { + writer.WritePropertyName("deviceCorrelationId"u8); + writer.WriteStringValue(DeviceCorrelationId); + } + if (Optional.IsDefined(AuthTokenTimeToLiveInSeconds)) + { + writer.WritePropertyName("authTokenTimeToLiveInSeconds"u8); + writer.WriteNumberValue(AuthTokenTimeToLiveInSeconds.Value); + } if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -114,14 +119,14 @@ internal static CreateLivenessWithVerifySessionContent DeserializeCreateLiveness return null; } LivenessOperationMode livenessOperationMode = default; - bool? sendResultsToClient = default; bool? deviceCorrelationIdSetInClient = default; bool? enableSessionImage = default; - LivenessModel? livenessSingleModalModel = default; - string deviceCorrelationId = default; - int? authTokenTimeToLiveInSeconds = default; + LivenessModel? livenessModelVersion = default; bool? returnVerifyImageHash = default; float? verifyConfidenceThreshold = default; + Stream verifyImage = default; + string deviceCorrelationId = default; + int? authTokenTimeToLiveInSeconds = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -131,15 +136,6 @@ internal static CreateLivenessWithVerifySessionContent DeserializeCreateLiveness livenessOperationMode = new LivenessOperationMode(property.Value.GetString()); continue; } - if (property.NameEquals("sendResultsToClient"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sendResultsToClient = property.Value.GetBoolean(); - continue; - } if (property.NameEquals("deviceCorrelationIdSetInClient"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -158,45 +154,50 @@ internal static CreateLivenessWithVerifySessionContent DeserializeCreateLiveness enableSessionImage = property.Value.GetBoolean(); continue; } - if (property.NameEquals("livenessSingleModalModel"u8)) + if (property.NameEquals("livenessModelVersion"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - livenessSingleModalModel = new LivenessModel(property.Value.GetString()); - continue; - } - if (property.NameEquals("deviceCorrelationId"u8)) - { - deviceCorrelationId = property.Value.GetString(); + livenessModelVersion = new LivenessModel(property.Value.GetString()); continue; } - if (property.NameEquals("authTokenTimeToLiveInSeconds"u8)) + if (property.NameEquals("returnVerifyImageHash"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - authTokenTimeToLiveInSeconds = property.Value.GetInt32(); + returnVerifyImageHash = property.Value.GetBoolean(); continue; } - if (property.NameEquals("returnVerifyImageHash"u8)) + if (property.NameEquals("verifyConfidenceThreshold"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - returnVerifyImageHash = property.Value.GetBoolean(); + verifyConfidenceThreshold = property.Value.GetSingle(); continue; } - if (property.NameEquals("verifyConfidenceThreshold"u8)) + if (property.NameEquals("verifyImage"u8)) + { + verifyImage = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + continue; + } + if (property.NameEquals("deviceCorrelationId"u8)) + { + deviceCorrelationId = property.Value.GetString(); + continue; + } + if (property.NameEquals("authTokenTimeToLiveInSeconds"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - verifyConfidenceThreshold = property.Value.GetSingle(); + authTokenTimeToLiveInSeconds = property.Value.GetInt32(); continue; } if (options.Format != "W") @@ -207,17 +208,68 @@ internal static CreateLivenessWithVerifySessionContent DeserializeCreateLiveness serializedAdditionalRawData = rawDataDictionary; return new CreateLivenessWithVerifySessionContent( livenessOperationMode, - sendResultsToClient, deviceCorrelationIdSetInClient, enableSessionImage, - livenessSingleModalModel, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + livenessModelVersion, returnVerifyImageHash, verifyConfidenceThreshold, + verifyImage, + deviceCorrelationId, + authTokenTimeToLiveInSeconds, serializedAdditionalRawData); } + private BinaryData SerializeMultipart(ModelReaderWriterOptions options) + { + using MultipartFormDataRequestContent content = ToMultipartRequestContent(); + using MemoryStream stream = new MemoryStream(); + content.WriteTo(stream); + if (stream.Position > int.MaxValue) + { + return BinaryData.FromStream(stream); + } + else + { + return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); + } + } + + internal virtual MultipartFormDataRequestContent ToMultipartRequestContent() + { + MultipartFormDataRequestContent content = new MultipartFormDataRequestContent(); + content.Add(LivenessOperationMode.ToString(), "livenessOperationMode"); + if (Optional.IsDefined(DeviceCorrelationIdSetInClient)) + { + content.Add(DeviceCorrelationIdSetInClient.Value, "deviceCorrelationIdSetInClient"); + } + if (Optional.IsDefined(EnableSessionImage)) + { + content.Add(EnableSessionImage.Value, "enableSessionImage"); + } + if (Optional.IsDefined(LivenessModelVersion)) + { + content.Add(LivenessModelVersion.Value.ToString(), "livenessModelVersion"); + } + if (Optional.IsDefined(ReturnVerifyImageHash)) + { + content.Add(ReturnVerifyImageHash.Value, "returnVerifyImageHash"); + } + if (Optional.IsDefined(VerifyConfidenceThreshold)) + { + content.Add(VerifyConfidenceThreshold.Value, "verifyConfidenceThreshold"); + } + content.Add(VerifyImage, "verifyImage", "verifyImage", "application/octet-stream"); + if (Optional.IsDefined(DeviceCorrelationId)) + { + content.Add(DeviceCorrelationId, "deviceCorrelationId"); + } + if (Optional.IsDefined(AuthTokenTimeToLiveInSeconds)) + { + content.Add(AuthTokenTimeToLiveInSeconds.Value, "authTokenTimeToLiveInSeconds"); + } + return content; + } + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; @@ -226,6 +278,8 @@ BinaryData IPersistableModel.Write(Model { case "J": return ModelReaderWriter.Write(this, options); + case "MFD": + return SerializeMultipart(options); default: throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionContent)} does not support writing '{options.Format}' format."); } @@ -247,7 +301,7 @@ CreateLivenessWithVerifySessionContent IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.cs index 99e890eaf7e3..b0ce40c829f3 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.cs @@ -7,10 +7,11 @@ using System; using System.Collections.Generic; +using System.IO; namespace Azure.AI.Vision.Face { - /// Request for creating liveness with verify session. + /// Request of liveness with verify session creation. public partial class CreateLivenessWithVerifySessionContent { /// @@ -47,33 +48,38 @@ public partial class CreateLivenessWithVerifySessionContent /// Initializes a new instance of . /// Type of liveness mode the client should follow. - public CreateLivenessWithVerifySessionContent(LivenessOperationMode livenessOperationMode) + /// The image stream for verify. Content-Disposition header field for this part must have filename. + /// is null. + public CreateLivenessWithVerifySessionContent(LivenessOperationMode livenessOperationMode, Stream verifyImage) { + Argument.AssertNotNull(verifyImage, nameof(verifyImage)); + LivenessOperationMode = livenessOperationMode; + VerifyImage = verifyImage; } /// Initializes a new instance of . /// Type of liveness mode the client should follow. - /// Whether or not to allow a '200 - Success' response body to be sent to the client, which may be undesirable for security reasons. Default is false, clients will receive a '204 - NoContent' empty body response. Regardless of selection, calling Session GetResult will always contain a response body enabling business logic to be implemented. /// Whether or not to allow client to set their own 'deviceCorrelationId' via the Vision SDK. Default is false, and 'deviceCorrelationId' must be set in this request body. /// Whether or not store the session image. - /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// Whether or not return the verify image hash. + /// Threshold for confidence of the face verification. Please refer to the documentation for more details. https://learn.microsoft.com/legal/cognitive-services/face/characteristics-and-limitations?context=%2Fazure%2Fai-services%2Fcomputer-vision%2Fcontext%2Fcontext#recognition-confidence-score. + /// The image stream for verify. Content-Disposition header field for this part must have filename. /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - /// Whether or not return the verify image hash. - /// Threshold for confidence of the face verification. /// Keeps track of any properties unknown to the library. - internal CreateLivenessWithVerifySessionContent(LivenessOperationMode livenessOperationMode, bool? sendResultsToClient, bool? deviceCorrelationIdSetInClient, bool? enableSessionImage, LivenessModel? livenessSingleModalModel, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, bool? returnVerifyImageHash, float? verifyConfidenceThreshold, IDictionary serializedAdditionalRawData) + internal CreateLivenessWithVerifySessionContent(LivenessOperationMode livenessOperationMode, bool? deviceCorrelationIdSetInClient, bool? enableSessionImage, LivenessModel? livenessModelVersion, bool? returnVerifyImageHash, float? verifyConfidenceThreshold, Stream verifyImage, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, IDictionary serializedAdditionalRawData) { LivenessOperationMode = livenessOperationMode; - SendResultsToClient = sendResultsToClient; DeviceCorrelationIdSetInClient = deviceCorrelationIdSetInClient; EnableSessionImage = enableSessionImage; - LivenessSingleModalModel = livenessSingleModalModel; - DeviceCorrelationId = deviceCorrelationId; - AuthTokenTimeToLiveInSeconds = authTokenTimeToLiveInSeconds; + LivenessModelVersion = livenessModelVersion; ReturnVerifyImageHash = returnVerifyImageHash; VerifyConfidenceThreshold = verifyConfidenceThreshold; + VerifyImage = verifyImage; + DeviceCorrelationId = deviceCorrelationId; + AuthTokenTimeToLiveInSeconds = authTokenTimeToLiveInSeconds; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -84,21 +90,21 @@ internal CreateLivenessWithVerifySessionContent() /// Type of liveness mode the client should follow. public LivenessOperationMode LivenessOperationMode { get; } - /// Whether or not to allow a '200 - Success' response body to be sent to the client, which may be undesirable for security reasons. Default is false, clients will receive a '204 - NoContent' empty body response. Regardless of selection, calling Session GetResult will always contain a response body enabling business logic to be implemented. - public bool? SendResultsToClient { get; set; } /// Whether or not to allow client to set their own 'deviceCorrelationId' via the Vision SDK. Default is false, and 'deviceCorrelationId' must be set in this request body. public bool? DeviceCorrelationIdSetInClient { get; set; } /// Whether or not store the session image. public bool? EnableSessionImage { get; set; } /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. - public LivenessModel? LivenessSingleModalModel { get; set; } + public LivenessModel? LivenessModelVersion { get; set; } + /// Whether or not return the verify image hash. + public bool? ReturnVerifyImageHash { get; set; } + /// Threshold for confidence of the face verification. Please refer to the documentation for more details. https://learn.microsoft.com/legal/cognitive-services/face/characteristics-and-limitations?context=%2Fazure%2Fai-services%2Fcomputer-vision%2Fcontext%2Fcontext#recognition-confidence-score. + public float? VerifyConfidenceThreshold { get; set; } + /// The image stream for verify. Content-Disposition header field for this part must have filename. + public Stream VerifyImage { get; } /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. public string DeviceCorrelationId { get; set; } /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. public int? AuthTokenTimeToLiveInSeconds { get; set; } - /// Whether or not return the verify image hash. - public bool? ReturnVerifyImageHash { get; set; } - /// Threshold for confidence of the face verification. - public float? VerifyConfidenceThreshold { get; set; } } } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.Serialization.cs deleted file mode 100644 index edc3e7532592..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.Serialization.cs +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.IO; -using System.Text.Json; -using Azure.Core; - -namespace Azure.AI.Vision.Face -{ - internal partial class CreateLivenessWithVerifySessionMultipartContent : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionMultipartContent)} does not support writing '{format}' format."); - } - - writer.WritePropertyName("Parameters"u8); - writer.WriteObjectValue(Parameters, options); - writer.WritePropertyName("VerifyImage"u8); -#if NET6_0_OR_GREATER - writer.WriteRawValue(global::System.BinaryData.FromStream(VerifyImage)); -#else - using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(VerifyImage), ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - if (options.Format != "W" && _serializedAdditionalRawData != null) - { - foreach (var item in _serializedAdditionalRawData) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - CreateLivenessWithVerifySessionMultipartContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionMultipartContent)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCreateLivenessWithVerifySessionMultipartContent(document.RootElement, options); - } - - internal static CreateLivenessWithVerifySessionMultipartContent DeserializeCreateLivenessWithVerifySessionMultipartContent(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - CreateLivenessWithVerifySessionContent parameters = default; - Stream verifyImage = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("Parameters"u8)) - { - parameters = CreateLivenessWithVerifySessionContent.DeserializeCreateLivenessWithVerifySessionContent(property.Value, options); - continue; - } - if (property.NameEquals("VerifyImage"u8)) - { - verifyImage = BinaryData.FromString(property.Value.GetRawText()).ToStream(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new CreateLivenessWithVerifySessionMultipartContent(parameters, verifyImage, serializedAdditionalRawData); - } - - private BinaryData SerializeMultipart(ModelReaderWriterOptions options) - { - using MultipartFormDataRequestContent content = ToMultipartRequestContent(); - using MemoryStream stream = new MemoryStream(); - content.WriteTo(stream); - if (stream.Position > int.MaxValue) - { - return BinaryData.FromStream(stream); - } - else - { - return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); - } - } - - internal virtual MultipartFormDataRequestContent ToMultipartRequestContent() - { - MultipartFormDataRequestContent content = new MultipartFormDataRequestContent(); - content.Add(ModelReaderWriter.Write(Parameters, ModelSerializationExtensions.WireOptions), "Parameters"); - content.Add(VerifyImage, "VerifyImage", "VerifyImage", "application/octet-stream"); - return content; - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - case "MFD": - return SerializeMultipart(options); - default: - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionMultipartContent)} does not support writing '{options.Format}' format."); - } - } - - CreateLivenessWithVerifySessionMultipartContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateLivenessWithVerifySessionMultipartContent(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionMultipartContent)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; - - /// Deserializes the model from a raw response. - /// The response to deserialize the model from. - internal static CreateLivenessWithVerifySessionMultipartContent FromResponse(Response response) - { - using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateLivenessWithVerifySessionMultipartContent(document.RootElement); - } - - /// Convert into a . - internal virtual RequestContent ToRequestContent() - { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); - return content; - } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.cs deleted file mode 100644 index 972c14733528..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.cs +++ /dev/null @@ -1,83 +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; - -namespace Azure.AI.Vision.Face -{ - /// Request of liveness with verify session creation. - internal partial class CreateLivenessWithVerifySessionMultipartContent - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The parameters for creating session. - /// The image stream for verify. Content-Disposition header field for this part must have filename. - /// or is null. - public CreateLivenessWithVerifySessionMultipartContent(CreateLivenessWithVerifySessionContent parameters, Stream verifyImage) - { - Argument.AssertNotNull(parameters, nameof(parameters)); - Argument.AssertNotNull(verifyImage, nameof(verifyImage)); - - Parameters = parameters; - VerifyImage = verifyImage; - } - - /// Initializes a new instance of . - /// The parameters for creating session. - /// The image stream for verify. Content-Disposition header field for this part must have filename. - /// Keeps track of any properties unknown to the library. - internal CreateLivenessWithVerifySessionMultipartContent(CreateLivenessWithVerifySessionContent parameters, Stream verifyImage, IDictionary serializedAdditionalRawData) - { - Parameters = parameters; - VerifyImage = verifyImage; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal CreateLivenessWithVerifySessionMultipartContent() - { - } - - /// The parameters for creating session. - public CreateLivenessWithVerifySessionContent Parameters { get; } - /// The image stream for verify. Content-Disposition header field for this part must have filename. - public Stream VerifyImage { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.cs deleted file mode 100644 index b969512f54ce..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// Response of liveness session with verify creation with verify image provided. - public partial class CreateLivenessWithVerifySessionResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - /// or is null. - internal CreateLivenessWithVerifySessionResult(string sessionId, string authToken) - { - Argument.AssertNotNull(sessionId, nameof(sessionId)); - Argument.AssertNotNull(authToken, nameof(authToken)); - - SessionId = sessionId; - AuthToken = authToken; - } - - /// Initializes a new instance of . - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - /// The detail of face for verification. - /// Keeps track of any properties unknown to the library. - internal CreateLivenessWithVerifySessionResult(string sessionId, string authToken, LivenessWithVerifyImage verifyImage, IDictionary serializedAdditionalRawData) - { - SessionId = sessionId; - AuthToken = authToken; - VerifyImage = verifyImage; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal CreateLivenessWithVerifySessionResult() - { - } - - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - public string SessionId { get; } - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - public string AuthToken { get; } - /// The detail of face for verification. - public LivenessWithVerifyImage VerifyImage { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/Docs/FaceSessionClient.xml b/sdk/face/Azure.AI.Vision.Face/src/Generated/Docs/FaceSessionClient.xml index 3754a0217479..8103910b8ae4 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/Docs/FaceSessionClient.xml +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/Docs/FaceSessionClient.xml @@ -11,12 +11,11 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); CreateLivenessSessionContent body = new CreateLivenessSessionContent(LivenessOperationMode.Passive) { - SendResultsToClient = true, - DeviceCorrelationIdSetInClient = true, + DeviceCorrelationIdSetInClient = false, DeviceCorrelationId = "your_device_correlation_id", AuthTokenTimeToLiveInSeconds = 60, }; -Response response = await client.CreateLivenessSessionAsync(body); +Response response = await client.CreateLivenessSessionAsync(body); ]]> @@ -29,12 +28,11 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); CreateLivenessSessionContent body = new CreateLivenessSessionContent(LivenessOperationMode.Passive) { - SendResultsToClient = true, - DeviceCorrelationIdSetInClient = true, + DeviceCorrelationIdSetInClient = false, DeviceCorrelationId = "your_device_correlation_id", AuthTokenTimeToLiveInSeconds = 60, }; -Response response = client.CreateLivenessSession(body); +Response response = client.CreateLivenessSession(body); ]]> @@ -48,8 +46,7 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); using RequestContent content = RequestContent.Create(new { livenessOperationMode = "Passive", - sendResultsToClient = true, - deviceCorrelationIdSetInClient = true, + deviceCorrelationIdSetInClient = false, deviceCorrelationId = "your_device_correlation_id", authTokenTimeToLiveInSeconds = 60, }); @@ -58,6 +55,9 @@ Response response = await client.CreateLivenessSessionAsync(content); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; Console.WriteLine(result.GetProperty("sessionId").ToString()); Console.WriteLine(result.GetProperty("authToken").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> @@ -71,8 +71,7 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); using RequestContent content = RequestContent.Create(new { livenessOperationMode = "Passive", - sendResultsToClient = true, - deviceCorrelationIdSetInClient = true, + deviceCorrelationIdSetInClient = false, deviceCorrelationId = "your_device_correlation_id", authTokenTimeToLiveInSeconds = 60, }); @@ -81,6 +80,9 @@ Response response = client.CreateLivenessSession(content); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; Console.WriteLine(result.GetProperty("sessionId").ToString()); Console.WriteLine(result.GetProperty("authToken").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> @@ -142,10 +144,11 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); Response response = await client.GetLivenessSessionResultAsync("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result.GetProperty("id").ToString()); -Console.WriteLine(result.GetProperty("createdDateTime").ToString()); -Console.WriteLine(result.GetProperty("sessionExpired").ToString()); +Console.WriteLine(result.GetProperty("sessionId").ToString()); +Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> @@ -159,136 +162,85 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); Response response = client.GetLivenessSessionResult("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result.GetProperty("id").ToString()); -Console.WriteLine(result.GetProperty("createdDateTime").ToString()); -Console.WriteLine(result.GetProperty("sessionExpired").ToString()); +Console.WriteLine(result.GetProperty("sessionId").ToString()); +Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> - - -This sample shows how to call GetLivenessSessionsAsync. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response> response = await client.GetLivenessSessionsAsync(); -]]> - - - -This sample shows how to call GetLivenessSessions. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response> response = client.GetLivenessSessions(); -]]> - - - -This sample shows how to call GetLivenessSessionsAsync and parse the result. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response response = await client.GetLivenessSessionsAsync("00000000-0000-0000-0000-000000000000", 20, null); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); -]]> - - - -This sample shows how to call GetLivenessSessions and parse the result. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response response = client.GetLivenessSessions("00000000-0000-0000-0000-000000000000", 20, null); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); -]]> - - + -This sample shows how to call GetLivenessSessionAuditEntriesAsync. +This sample shows how to call CreateLivenessWithVerifySessionAsync. "); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); -Response> response = await client.GetLivenessSessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e"); +CreateLivenessWithVerifySessionContent body = null; +Response response = await client.CreateLivenessWithVerifySessionAsync(body); ]]> - + -This sample shows how to call GetLivenessSessionAuditEntries. +This sample shows how to call CreateLivenessWithVerifySession. "); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); -Response> response = client.GetLivenessSessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e"); +CreateLivenessWithVerifySessionContent body = null; +Response response = client.CreateLivenessWithVerifySession(body); ]]> - + -This sample shows how to call GetLivenessSessionAuditEntriesAsync and parse the result. +This sample shows how to call CreateLivenessWithVerifySessionAsync and parse the result. "); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); -Response response = await client.GetLivenessSessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); +using RequestContent content = null; +Response response = await client.CreateLivenessWithVerifySessionAsync(content, null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("sessionId").ToString()); -Console.WriteLine(result[0].GetProperty("requestId").ToString()); -Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); -Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); -Console.WriteLine(result[0].GetProperty("digest").ToString()); +Console.WriteLine(result.GetProperty("sessionId").ToString()); +Console.WriteLine(result.GetProperty("authToken").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> - + -This sample shows how to call GetLivenessSessionAuditEntries and parse the result. +This sample shows how to call CreateLivenessWithVerifySession and parse the result. "); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); -Response response = client.GetLivenessSessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); +using RequestContent content = null; +Response response = client.CreateLivenessWithVerifySession(content, null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("sessionId").ToString()); -Console.WriteLine(result[0].GetProperty("requestId").ToString()); -Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); -Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); -Console.WriteLine(result[0].GetProperty("digest").ToString()); +Console.WriteLine(result.GetProperty("sessionId").ToString()); +Console.WriteLine(result.GetProperty("authToken").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> @@ -350,10 +302,17 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); Response response = await client.GetLivenessWithVerifySessionResultAsync("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result.GetProperty("id").ToString()); -Console.WriteLine(result.GetProperty("createdDateTime").ToString()); -Console.WriteLine(result.GetProperty("sessionExpired").ToString()); +Console.WriteLine(result.GetProperty("sessionId").ToString()); +Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> @@ -367,136 +326,17 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); Response response = client.GetLivenessWithVerifySessionResult("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result.GetProperty("id").ToString()); -Console.WriteLine(result.GetProperty("createdDateTime").ToString()); -Console.WriteLine(result.GetProperty("sessionExpired").ToString()); +Console.WriteLine(result.GetProperty("sessionId").ToString()); +Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessionsAsync. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response> response = await client.GetLivenessWithVerifySessionsAsync(); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessions. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response> response = client.GetLivenessWithVerifySessions(); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessionsAsync and parse the result. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response response = await client.GetLivenessWithVerifySessionsAsync("00000000-0000-0000-0000-000000000000", 20, null); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessions and parse the result. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response response = client.GetLivenessWithVerifySessions("00000000-0000-0000-0000-000000000000", 20, null); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessionAuditEntriesAsync. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response> response = await client.GetLivenessWithVerifySessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e"); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessionAuditEntries. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response> response = client.GetLivenessWithVerifySessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e"); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessionAuditEntriesAsync and parse the result. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response response = await client.GetLivenessWithVerifySessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("sessionId").ToString()); -Console.WriteLine(result[0].GetProperty("requestId").ToString()); -Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); -Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); -Console.WriteLine(result[0].GetProperty("digest").ToString()); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessionAuditEntries and parse the result. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response response = client.GetLivenessWithVerifySessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("sessionId").ToString()); -Console.WriteLine(result[0].GetProperty("requestId").ToString()); -Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); -Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); -Console.WriteLine(result[0].GetProperty("digest").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionClient.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionClient.cs index c3695cc5455d..2d54e4f2d175 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionClient.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionClient.cs @@ -108,14 +108,14 @@ public FaceSessionClient(Uri endpoint, TokenCredential credential, AzureAIVision /// is null. /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-session for more details. /// - public virtual async Task> CreateLivenessSessionAsync(CreateLivenessSessionContent body, CancellationToken cancellationToken = default) + public virtual async Task> CreateLivenessSessionAsync(CreateLivenessSessionContent body, CancellationToken cancellationToken = default) { Argument.AssertNotNull(body, nameof(body)); using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); Response response = await CreateLivenessSessionAsync(content, context).ConfigureAwait(false); - return Response.FromValue(CreateLivenessSessionResult.FromResponse(response), response); + return Response.FromValue(LivenessSession.FromResponse(response), response); } /// Create a new detect liveness session. @@ -124,14 +124,14 @@ public virtual async Task> CreateLivenessS /// is null. /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-session for more details. /// - public virtual Response CreateLivenessSession(CreateLivenessSessionContent body, CancellationToken cancellationToken = default) + public virtual Response CreateLivenessSession(CreateLivenessSessionContent body, CancellationToken cancellationToken = default) { Argument.AssertNotNull(body, nameof(body)); using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); Response response = CreateLivenessSession(content, context); - return Response.FromValue(CreateLivenessSessionResult.FromResponse(response), response); + return Response.FromValue(LivenessSession.FromResponse(response), response); } /// @@ -336,555 +336,15 @@ public virtual Response GetLivenessSessionResult(string session /// Service returned a non-success status code. /// The response returned from the service. /// - public virtual async Task GetLivenessSessionResultAsync(string sessionId, RequestContext context) - { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessionResult"); - scope.Start(); - try - { - using HttpMessage message = CreateGetLivenessSessionResultRequest(sessionId, context); - return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-session-result for more details. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// The unique ID to reference this session. - /// 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 GetLivenessSessionResult(string sessionId, RequestContext context) - { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessionResult"); - scope.Start(); - try - { - using HttpMessage message = CreateGetLivenessSessionResultRequest(sessionId, context); - return _pipeline.ProcessMessage(message, context); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Lists sessions for /detectLiveness/SingleModal. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The cancellation token to use. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-sessions for more details. - /// - public virtual async Task>> GetLivenessSessionsAsync(string start = null, int? top = null, CancellationToken cancellationToken = default) - { - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetLivenessSessionsAsync(start, top, context).ConfigureAwait(false); - IReadOnlyList value = default; - using var document = await JsonDocument.ParseAsync(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionItem.DeserializeLivenessSessionItem(item)); - } - value = array; - return Response.FromValue(value, response); - } - - /// Lists sessions for /detectLiveness/SingleModal. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The cancellation token to use. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-sessions for more details. - /// - public virtual Response> GetLivenessSessions(string start = null, int? top = null, CancellationToken cancellationToken = default) - { - RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetLivenessSessions(start, top, context); - IReadOnlyList value = default; - using var document = JsonDocument.Parse(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionItem.DeserializeLivenessSessionItem(item)); - } - value = array; - return Response.FromValue(value, response); - } - - /// - /// [Protocol Method] Lists sessions for /detectLiveness/SingleModal. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// 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 response returned from the service. - /// - public virtual async Task GetLivenessSessionsAsync(string start, int? top, RequestContext context) - { - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessions"); - scope.Start(); - try - { - using HttpMessage message = CreateGetLivenessSessionsRequest(start, top, context); - return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// [Protocol Method] Lists sessions for /detectLiveness/SingleModal. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// 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 response returned from the service. - /// - public virtual Response GetLivenessSessions(string start, int? top, RequestContext context) - { - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessions"); - scope.Start(); - try - { - using HttpMessage message = CreateGetLivenessSessionsRequest(start, top, context); - return _pipeline.ProcessMessage(message, context); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-session-audit-entries for more details. - /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// - public virtual async Task>> GetLivenessSessionAuditEntriesAsync(string sessionId, string start = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetLivenessSessionAuditEntriesAsync(sessionId, start, top, context).ConfigureAwait(false); - IReadOnlyList value = default; - using var document = await JsonDocument.ParseAsync(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionAuditEntry.DeserializeLivenessSessionAuditEntry(item)); - } - value = array; - return Response.FromValue(value, response); - } - - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-session-audit-entries for more details. - /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// - public virtual Response> GetLivenessSessionAuditEntries(string sessionId, string start = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - - RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetLivenessSessionAuditEntries(sessionId, start, top, context); - IReadOnlyList value = default; - using var document = JsonDocument.Parse(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionAuditEntry.DeserializeLivenessSessionAuditEntry(item)); - } - value = array; - return Response.FromValue(value, response); - } - - /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-session-audit-entries for more details. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// 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 GetLivenessSessionAuditEntriesAsync(string sessionId, string start, int? top, RequestContext context) - { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessionAuditEntries"); - scope.Start(); - try - { - using HttpMessage message = CreateGetLivenessSessionAuditEntriesRequest(sessionId, start, top, context); - return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-session-audit-entries for more details. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// 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 GetLivenessSessionAuditEntries(string sessionId, string start, int? top, RequestContext context) - { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessionAuditEntries"); - scope.Start(); - try - { - using HttpMessage message = CreateGetLivenessSessionAuditEntriesRequest(sessionId, start, top, context); - return _pipeline.ProcessMessage(message, context); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Create a new liveness session with verify. Client device submits VerifyImage during the /detectLivenessWithVerify/singleModal call. - /// Body parameter. - /// The cancellation token to use. - /// is null. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session for more details. - internal virtual async Task> CreateLivenessWithVerifySessionAsync(CreateLivenessWithVerifySessionContent body, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(body, nameof(body)); - - using RequestContent content = body.ToRequestContent(); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateLivenessWithVerifySessionAsync(content, context).ConfigureAwait(false); - return Response.FromValue(CreateLivenessWithVerifySessionResult.FromResponse(response), response); - } - - /// Create a new liveness session with verify. Client device submits VerifyImage during the /detectLivenessWithVerify/singleModal call. - /// Body parameter. - /// The cancellation token to use. - /// is null. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session for more details. - internal virtual Response CreateLivenessWithVerifySession(CreateLivenessWithVerifySessionContent body, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(body, nameof(body)); - - using RequestContent content = body.ToRequestContent(); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = CreateLivenessWithVerifySession(content, context); - return Response.FromValue(CreateLivenessWithVerifySessionResult.FromResponse(response), response); - } - - /// - /// [Protocol Method] Create a new liveness session with verify. Client device submits VerifyImage during the /detectLivenessWithVerify/singleModal call. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// 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. - /// Service returned a non-success status code. - /// The response returned from the service. - internal virtual async Task CreateLivenessWithVerifySessionAsync(RequestContent content, RequestContext context = null) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.CreateLivenessWithVerifySession"); - scope.Start(); - try - { - using HttpMessage message = CreateCreateLivenessWithVerifySessionRequest(content, context); - return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// [Protocol Method] Create a new liveness session with verify. Client device submits VerifyImage during the /detectLivenessWithVerify/singleModal call. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// 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. - /// Service returned a non-success status code. - /// The response returned from the service. - internal virtual Response CreateLivenessWithVerifySession(RequestContent content, RequestContext context = null) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.CreateLivenessWithVerifySession"); - scope.Start(); - try - { - using HttpMessage message = CreateCreateLivenessWithVerifySessionRequest(content, context); - return _pipeline.ProcessMessage(message, context); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Create a new liveness session with verify. Provide the verify image during session creation. - /// Request content of liveness with verify session creation. - /// The cancellation token to use. - /// is null. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session-with-verify-image for more details. - internal virtual async Task> CreateLivenessWithVerifySessionWithVerifyImageAsync(CreateLivenessWithVerifySessionMultipartContent body, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(body, nameof(body)); - - using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateLivenessWithVerifySessionWithVerifyImageAsync(content, content.ContentType, context).ConfigureAwait(false); - return Response.FromValue(CreateLivenessWithVerifySessionResult.FromResponse(response), response); - } - - /// Create a new liveness session with verify. Provide the verify image during session creation. - /// Request content of liveness with verify session creation. - /// The cancellation token to use. - /// is null. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session-with-verify-image for more details. - internal virtual Response CreateLivenessWithVerifySessionWithVerifyImage(CreateLivenessWithVerifySessionMultipartContent body, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(body, nameof(body)); - - using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = CreateLivenessWithVerifySessionWithVerifyImage(content, content.ContentType, context); - return Response.FromValue(CreateLivenessWithVerifySessionResult.FromResponse(response), response); - } - - /// - /// [Protocol Method] Create a new liveness session with verify. Provide the verify image during session creation. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// The content to send as the body of the request. - /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// Service returned a non-success status code. - /// The response returned from the service. - internal virtual async Task CreateLivenessWithVerifySessionWithVerifyImageAsync(RequestContent content, string contentType, RequestContext context = null) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.CreateLivenessWithVerifySessionWithVerifyImage"); - scope.Start(); - try - { - using HttpMessage message = CreateCreateLivenessWithVerifySessionWithVerifyImageRequest(content, contentType, context); - return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// [Protocol Method] Create a new liveness session with verify. Provide the verify image during session creation. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// The content to send as the body of the request. - /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// Service returned a non-success status code. - /// The response returned from the service. - internal virtual Response CreateLivenessWithVerifySessionWithVerifyImage(RequestContent content, string contentType, RequestContext context = null) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.CreateLivenessWithVerifySessionWithVerifyImage"); - scope.Start(); - try - { - using HttpMessage message = CreateCreateLivenessWithVerifySessionWithVerifyImageRequest(content, contentType, context); - return _pipeline.ProcessMessage(message, context); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method - /// - /// [Protocol Method] Delete all session related information for matching the specified session id. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// The unique ID to reference this session. - /// 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 DeleteLivenessWithVerifySessionAsync(string sessionId, RequestContext context = null) + public virtual async Task GetLivenessSessionResultAsync(string sessionId, RequestContext context) { Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.DeleteLivenessWithVerifySession"); + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessionResult"); scope.Start(); try { - using HttpMessage message = CreateDeleteLivenessWithVerifySessionRequest(sessionId, context); + using HttpMessage message = CreateGetLivenessSessionResultRequest(sessionId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -894,15 +354,19 @@ public virtual async Task DeleteLivenessWithVerifySessionAsync(string } } - // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method /// - /// [Protocol Method] Delete all session related information for matching the specified session id. + /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-session-result for more details. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// /// /// /// The unique ID to reference this session. @@ -911,16 +375,16 @@ public virtual async Task DeleteLivenessWithVerifySessionAsync(string /// 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 DeleteLivenessWithVerifySession(string sessionId, RequestContext context = null) + /// + public virtual Response GetLivenessSessionResult(string sessionId, RequestContext context) { Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.DeleteLivenessWithVerifySession"); + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessionResult"); scope.Start(); try { - using HttpMessage message = CreateDeleteLivenessWithVerifySessionRequest(sessionId, context); + using HttpMessage message = CreateGetLivenessSessionResultRequest(sessionId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -930,38 +394,40 @@ public virtual Response DeleteLivenessWithVerifySession(string sessionId, Reques } } - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. - /// The unique ID to reference this session. + /// Create a new liveness session with verify. Provide the verify image during session creation. + /// Request content of liveness with verify session creation. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// - public virtual async Task> GetLivenessWithVerifySessionResultAsync(string sessionId, CancellationToken cancellationToken = default) + /// is null. + /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session-with-verify-image for more details. + /// + public virtual async Task> CreateLivenessWithVerifySessionAsync(CreateLivenessWithVerifySessionContent body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); + Argument.AssertNotNull(body, nameof(body)); + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetLivenessWithVerifySessionResultAsync(sessionId, context).ConfigureAwait(false); + Response response = await CreateLivenessWithVerifySessionAsync(content, content.ContentType, context).ConfigureAwait(false); return Response.FromValue(LivenessWithVerifySession.FromResponse(response), response); } - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. - /// The unique ID to reference this session. + /// Create a new liveness session with verify. Provide the verify image during session creation. + /// Request content of liveness with verify session creation. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// - public virtual Response GetLivenessWithVerifySessionResult(string sessionId, CancellationToken cancellationToken = default) + /// is null. + /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session-with-verify-image for more details. + /// + public virtual Response CreateLivenessWithVerifySession(CreateLivenessWithVerifySessionContent body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); + Argument.AssertNotNull(body, nameof(body)); + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetLivenessWithVerifySessionResult(sessionId, context); + Response response = CreateLivenessWithVerifySession(content, content.ContentType, context); return Response.FromValue(LivenessWithVerifySession.FromResponse(response), response); } /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. + /// [Protocol Method] Create a new liveness session with verify. Provide the verify image during session creation. /// /// /// @@ -970,27 +436,27 @@ public virtual Response GetLivenessWithVerifySessionR /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The unique ID to reference this session. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". /// 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. + /// is null. /// Service returned a non-success status code. /// The response returned from the service. - /// - public virtual async Task GetLivenessWithVerifySessionResultAsync(string sessionId, RequestContext context) + /// + public virtual async Task CreateLivenessWithVerifySessionAsync(RequestContent content, string contentType, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessionResult"); + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.CreateLivenessWithVerifySession"); scope.Start(); try { - using HttpMessage message = CreateGetLivenessWithVerifySessionResultRequest(sessionId, context); + using HttpMessage message = CreateCreateLivenessWithVerifySessionRequest(content, contentType, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1001,7 +467,7 @@ public virtual async Task GetLivenessWithVerifySessionResultAsync(stri } /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. + /// [Protocol Method] Create a new liveness session with verify. Provide the verify image during session creation. /// /// /// @@ -1010,27 +476,27 @@ public virtual async Task GetLivenessWithVerifySessionResultAsync(stri /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The unique ID to reference this session. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". /// 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. + /// is null. /// Service returned a non-success status code. /// The response returned from the service. - /// - public virtual Response GetLivenessWithVerifySessionResult(string sessionId, RequestContext context) + /// + public virtual Response CreateLivenessWithVerifySession(RequestContent content, string contentType, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessionResult"); + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.CreateLivenessWithVerifySession"); scope.Start(); try { - using HttpMessage message = CreateGetLivenessWithVerifySessionResultRequest(sessionId, context); + using HttpMessage message = CreateCreateLivenessWithVerifySessionRequest(content, contentType, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1040,76 +506,33 @@ public virtual Response GetLivenessWithVerifySessionResult(string sessionId, Req } } - /// Lists sessions for /detectLivenessWithVerify/SingleModal. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The cancellation token to use. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-sessions for more details. - /// - public virtual async Task>> GetLivenessWithVerifySessionsAsync(string start = null, int? top = null, CancellationToken cancellationToken = default) - { - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetLivenessWithVerifySessionsAsync(start, top, context).ConfigureAwait(false); - IReadOnlyList value = default; - using var document = await JsonDocument.ParseAsync(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionItem.DeserializeLivenessSessionItem(item)); - } - value = array; - return Response.FromValue(value, response); - } - - /// Lists sessions for /detectLivenessWithVerify/SingleModal. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The cancellation token to use. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-sessions for more details. - /// - public virtual Response> GetLivenessWithVerifySessions(string start = null, int? top = null, CancellationToken cancellationToken = default) - { - RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetLivenessWithVerifySessions(start, top, context); - IReadOnlyList value = default; - using var document = JsonDocument.Parse(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionItem.DeserializeLivenessSessionItem(item)); - } - value = array; - return Response.FromValue(value, response); - } - + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method /// - /// [Protocol Method] Lists sessions for /detectLivenessWithVerify/SingleModal. + /// [Protocol Method] Delete all session related information for matching the specified session id. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. + /// The unique ID to reference this session. /// 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 GetLivenessWithVerifySessionsAsync(string start, int? top, RequestContext context) + /// + public virtual async Task DeleteLivenessWithVerifySessionAsync(string sessionId, RequestContext context = null) { - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessions"); + Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); + + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.DeleteLivenessWithVerifySession"); scope.Start(); try { - using HttpMessage message = CreateGetLivenessWithVerifySessionsRequest(start, top, context); + using HttpMessage message = CreateDeleteLivenessWithVerifySessionRequest(sessionId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1119,34 +542,33 @@ public virtual async Task GetLivenessWithVerifySessionsAsync(string st } } + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method /// - /// [Protocol Method] Lists sessions for /detectLivenessWithVerify/SingleModal. + /// [Protocol Method] Delete all session related information for matching the specified session id. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. + /// The unique ID to reference this session. /// 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 GetLivenessWithVerifySessions(string start, int? top, RequestContext context) + /// + public virtual Response DeleteLivenessWithVerifySession(string sessionId, RequestContext context = null) { - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessions"); + Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); + + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.DeleteLivenessWithVerifySession"); scope.Start(); try { - using HttpMessage message = CreateGetLivenessWithVerifySessionsRequest(start, top, context); + using HttpMessage message = CreateDeleteLivenessWithVerifySessionRequest(sessionId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1156,58 +578,38 @@ public virtual Response GetLivenessWithVerifySessions(string start, int? top, Re } } - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-audit-entries for more details. + /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. /// The cancellation token to use. /// is null. /// is an empty string, and was expected to be non-empty. - /// - public virtual async Task>> GetLivenessWithVerifySessionAuditEntriesAsync(string sessionId, string start = null, int? top = null, CancellationToken cancellationToken = default) + /// + public virtual async Task> GetLivenessWithVerifySessionResultAsync(string sessionId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetLivenessWithVerifySessionAuditEntriesAsync(sessionId, start, top, context).ConfigureAwait(false); - IReadOnlyList value = default; - using var document = await JsonDocument.ParseAsync(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionAuditEntry.DeserializeLivenessSessionAuditEntry(item)); - } - value = array; - return Response.FromValue(value, response); + Response response = await GetLivenessWithVerifySessionResultAsync(sessionId, context).ConfigureAwait(false); + return Response.FromValue(LivenessWithVerifySession.FromResponse(response), response); } - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-audit-entries for more details. + /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. /// The cancellation token to use. /// is null. /// is an empty string, and was expected to be non-empty. - /// - public virtual Response> GetLivenessWithVerifySessionAuditEntries(string sessionId, string start = null, int? top = null, CancellationToken cancellationToken = default) + /// + public virtual Response GetLivenessWithVerifySessionResult(string sessionId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetLivenessWithVerifySessionAuditEntries(sessionId, start, top, context); - IReadOnlyList value = default; - using var document = JsonDocument.Parse(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionAuditEntry.DeserializeLivenessSessionAuditEntry(item)); - } - value = array; - return Response.FromValue(value, response); + Response response = GetLivenessWithVerifySessionResult(sessionId, context); + return Response.FromValue(LivenessWithVerifySession.FromResponse(response), response); } /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-audit-entries for more details. + /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. /// /// /// @@ -1216,29 +618,27 @@ public virtual Response> GetLivenessWit /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. /// 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 GetLivenessWithVerifySessionAuditEntriesAsync(string sessionId, string start, int? top, RequestContext context) + /// + public virtual async Task GetLivenessWithVerifySessionResultAsync(string sessionId, RequestContext context) { Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessionAuditEntries"); + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessionResult"); scope.Start(); try { - using HttpMessage message = CreateGetLivenessWithVerifySessionAuditEntriesRequest(sessionId, start, top, context); + using HttpMessage message = CreateGetLivenessWithVerifySessionResultRequest(sessionId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1249,7 +649,7 @@ public virtual async Task GetLivenessWithVerifySessionAuditEntriesAsyn } /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-audit-entries for more details. + /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. /// /// /// @@ -1258,29 +658,27 @@ public virtual async Task GetLivenessWithVerifySessionAuditEntriesAsyn /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. /// 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 GetLivenessWithVerifySessionAuditEntries(string sessionId, string start, int? top, RequestContext context) + /// + public virtual Response GetLivenessWithVerifySessionResult(string sessionId, RequestContext context) { Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessionAuditEntries"); + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessionResult"); scope.Start(); try { - using HttpMessage message = CreateGetLivenessWithVerifySessionAuditEntriesRequest(sessionId, start, top, context); + using HttpMessage message = CreateGetLivenessWithVerifySessionResultRequest(sessionId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1563,7 +961,7 @@ internal HttpMessage CreateCreateLivenessSessionRequest(RequestContent content, uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLiveness/singleModal/sessions", false); + uri.AppendPath("/detectLiveness-sessions", false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); @@ -1573,14 +971,14 @@ internal HttpMessage CreateCreateLivenessSessionRequest(RequestContent content, internal HttpMessage CreateDeleteLivenessSessionRequest(string sessionId, RequestContext context) { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var message = _pipeline.CreateMessage(context, ResponseClassifier204); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLiveness/singleModal/sessions/", false); + uri.AppendPath("/detectLiveness-sessions/", false); uri.AppendPath(sessionId, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); @@ -1596,79 +994,14 @@ internal HttpMessage CreateGetLivenessSessionResultRequest(string sessionId, Req uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLiveness/singleModal/sessions/", false); - uri.AppendPath(sessionId, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; - } - - internal HttpMessage CreateGetLivenessSessionsRequest(string start, int? top, RequestContext context) - { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRaw("/face/", false); - uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLiveness/singleModal/sessions", false); - if (start != null) - { - uri.AppendQuery("start", start, true); - } - if (top != null) - { - uri.AppendQuery("top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; - } - - internal HttpMessage CreateGetLivenessSessionAuditEntriesRequest(string sessionId, string start, int? top, RequestContext context) - { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRaw("/face/", false); - uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLiveness/singleModal/sessions/", false); + uri.AppendPath("/detectLiveness-sessions/", false); uri.AppendPath(sessionId, true); - uri.AppendPath("/audit", false); - if (start != null) - { - uri.AppendQuery("start", start, true); - } - if (top != null) - { - uri.AppendQuery("top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; - } - - internal HttpMessage CreateCreateLivenessWithVerifySessionRequest(RequestContent content, RequestContext context) - { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRaw("/face/", false); - uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLivenessWithVerify/singleModal/sessions", false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - request.Content = content; return message; } - internal HttpMessage CreateCreateLivenessWithVerifySessionWithVerifyImageRequest(RequestContent content, string contentType, RequestContext context) + internal HttpMessage CreateCreateLivenessWithVerifySessionRequest(RequestContent content, string contentType, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; @@ -1677,7 +1010,7 @@ internal HttpMessage CreateCreateLivenessWithVerifySessionWithVerifyImageRequest uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLivenessWithVerify/singleModal/sessions", false); + uri.AppendPath("/detectLivenessWithVerify-sessions", false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", contentType); @@ -1687,14 +1020,14 @@ internal HttpMessage CreateCreateLivenessWithVerifySessionWithVerifyImageRequest internal HttpMessage CreateDeleteLivenessWithVerifySessionRequest(string sessionId, RequestContext context) { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var message = _pipeline.CreateMessage(context, ResponseClassifier204); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLivenessWithVerify/singleModal/sessions/", false); + uri.AppendPath("/detectLivenessWithVerify-sessions/", false); uri.AppendPath(sessionId, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); @@ -1710,56 +1043,8 @@ internal HttpMessage CreateGetLivenessWithVerifySessionResultRequest(string sess uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLivenessWithVerify/singleModal/sessions/", false); - uri.AppendPath(sessionId, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; - } - - internal HttpMessage CreateGetLivenessWithVerifySessionsRequest(string start, int? top, RequestContext context) - { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRaw("/face/", false); - uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLivenessWithVerify/singleModal/sessions", false); - if (start != null) - { - uri.AppendQuery("start", start, true); - } - if (top != null) - { - uri.AppendQuery("top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; - } - - internal HttpMessage CreateGetLivenessWithVerifySessionAuditEntriesRequest(string sessionId, string start, int? top, RequestContext context) - { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRaw("/face/", false); - uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLivenessWithVerify/singleModal/sessions/", false); + uri.AppendPath("/detectLivenessWithVerify-sessions/", false); uri.AppendPath(sessionId, true); - uri.AppendPath("/audit", false); - if (start != null) - { - uri.AppendQuery("start", start, true); - } - if (top != null) - { - uri.AppendQuery("top", top.Value, true); - } request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; @@ -1819,7 +1104,7 @@ internal HttpMessage CreateGetSessionImageRequest(string sessionImageId, Request uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/session/sessionImages/", false); + uri.AppendPath("/sessionImages/", false); uri.AppendPath(sessionImageId, true); request.Uri = uri; request.Headers.Add("Accept", "application/octet-stream"); @@ -1839,5 +1124,7 @@ internal static RequestContext FromCancellationToken(CancellationToken cancellat 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/face/Azure.AI.Vision.Face/src/Generated/FaceSessionStatus.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionStatus.cs deleted file mode 100644 index 6c583b333353..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionStatus.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.Vision.Face -{ - /// The current status of the session. - public readonly partial struct FaceSessionStatus : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public FaceSessionStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NotStartedValue = "NotStarted"; - private const string StartedValue = "Started"; - private const string ResultAvailableValue = "ResultAvailable"; - - /// Session has not started. - public static FaceSessionStatus NotStarted { get; } = new FaceSessionStatus(NotStartedValue); - /// Session has started. - public static FaceSessionStatus Started { get; } = new FaceSessionStatus(StartedValue); - /// Session has available result. - public static FaceSessionStatus ResultAvailable { get; } = new FaceSessionStatus(ResultAvailableValue); - /// Determines if two values are the same. - public static bool operator ==(FaceSessionStatus left, FaceSessionStatus right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(FaceSessionStatus left, FaceSessionStatus right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator FaceSessionStatus(string value) => new FaceSessionStatus(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is FaceSessionStatus other && Equals(other); - /// - public bool Equals(FaceSessionStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LargeFaceListClient.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LargeFaceListClient.cs index 77835b1ee957..df88bc879d6b 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LargeFaceListClient.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LargeFaceListClient.cs @@ -49,7 +49,7 @@ protected LargeFaceListClient() /// https://{resource-name}.cognitiveservices.azure.com). /// /// Valid character is letter in lower case or digit or '-' or '_', maximum length is 64. - /// API Version. Allowed values: "v1.1-preview.1" | "v1.2-preview.1". + /// API Version. Allowed values: "v1.1-preview.1" | "v1.2-preview.1" | "v1.2". internal LargeFaceListClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint, string largeFaceListId, string apiVersion) { ClientDiagnostics = clientDiagnostics; diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LargePersonGroupClient.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LargePersonGroupClient.cs index 4977323e0232..428215d0776f 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LargePersonGroupClient.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LargePersonGroupClient.cs @@ -49,7 +49,7 @@ protected LargePersonGroupClient() /// https://{resource-name}.cognitiveservices.azure.com). /// /// ID of the container. - /// API Version. Allowed values: "v1.1-preview.1" | "v1.2-preview.1". + /// API Version. Allowed values: "v1.1-preview.1" | "v1.2-preview.1" | "v1.2". internal LargePersonGroupClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint, string largePersonGroupId, string apiVersion) { ClientDiagnostics = clientDiagnostics; diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.Serialization.cs similarity index 65% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.Serialization.cs rename to sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.Serialization.cs index 15b072f6e4b7..f7ba4a27e38d 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.Vision.Face { - public partial class CreateLivenessSessionResult : IUtf8JsonSerializable, IJsonModel + public partial class LivenessColorDecisionTarget : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,16 +28,14 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateLivenessSessionResult)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(LivenessColorDecisionTarget)} does not support writing '{format}' format."); } - writer.WritePropertyName("sessionId"u8); - writer.WriteStringValue(SessionId); - writer.WritePropertyName("authToken"u8); - writer.WriteStringValue(AuthToken); + writer.WritePropertyName("faceRectangle"u8); + writer.WriteObjectValue(FaceRectangle, options); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -55,19 +53,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - CreateLivenessSessionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + LivenessColorDecisionTarget IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateLivenessSessionResult)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(LivenessColorDecisionTarget)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCreateLivenessSessionResult(document.RootElement, options); + return DeserializeLivenessColorDecisionTarget(document.RootElement, options); } - internal static CreateLivenessSessionResult DeserializeCreateLivenessSessionResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static LivenessColorDecisionTarget DeserializeLivenessColorDecisionTarget(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -75,20 +73,14 @@ internal static CreateLivenessSessionResult DeserializeCreateLivenessSessionResu { return null; } - string sessionId = default; - string authToken = default; + FaceRectangle faceRectangle = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("sessionId"u8)) + if (property.NameEquals("faceRectangle"u8)) { - sessionId = property.Value.GetString(); - continue; - } - if (property.NameEquals("authToken"u8)) - { - authToken = property.Value.GetString(); + faceRectangle = FaceRectangle.DeserializeFaceRectangle(property.Value, options); continue; } if (options.Format != "W") @@ -97,46 +89,46 @@ internal static CreateLivenessSessionResult DeserializeCreateLivenessSessionResu } } serializedAdditionalRawData = rawDataDictionary; - return new CreateLivenessSessionResult(sessionId, authToken, serializedAdditionalRawData); + return new LivenessColorDecisionTarget(faceRectangle, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(CreateLivenessSessionResult)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessColorDecisionTarget)} does not support writing '{options.Format}' format."); } } - CreateLivenessSessionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + LivenessColorDecisionTarget IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateLivenessSessionResult(document.RootElement, options); + return DeserializeLivenessColorDecisionTarget(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(CreateLivenessSessionResult)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessColorDecisionTarget)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static CreateLivenessSessionResult FromResponse(Response response) + internal static LivenessColorDecisionTarget FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateLivenessSessionResult(document.RootElement); + return DeserializeLivenessColorDecisionTarget(document.RootElement); } /// Convert into a . diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.cs similarity index 51% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.cs rename to sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.cs index 4469cf9f8d50..9a04763a6e3d 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.cs @@ -10,8 +10,8 @@ namespace Azure.AI.Vision.Face { - /// The liveness classification for target face. - public partial class LivenessOutputsTarget + /// The target from color image used for liveness classification. + public partial class LivenessColorDecisionTarget { /// /// Keeps track of any properties unknown to the library. @@ -45,50 +45,31 @@ public partial class LivenessOutputsTarget /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// The face region where the liveness classification was made on. - /// The file name which contains the face rectangle where the liveness classification was made on. - /// The time offset within the file of the frame which contains the face rectangle where the liveness classification was made on. - /// The image type which contains the face rectangle where the liveness classification was made on. - /// or is null. - internal LivenessOutputsTarget(FaceRectangle faceRectangle, string fileName, int timeOffsetWithinFile, FaceImageType imageType) + /// is null. + internal LivenessColorDecisionTarget(FaceRectangle faceRectangle) { Argument.AssertNotNull(faceRectangle, nameof(faceRectangle)); - Argument.AssertNotNull(fileName, nameof(fileName)); FaceRectangle = faceRectangle; - FileName = fileName; - TimeOffsetWithinFile = timeOffsetWithinFile; - ImageType = imageType; } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The face region where the liveness classification was made on. - /// The file name which contains the face rectangle where the liveness classification was made on. - /// The time offset within the file of the frame which contains the face rectangle where the liveness classification was made on. - /// The image type which contains the face rectangle where the liveness classification was made on. /// Keeps track of any properties unknown to the library. - internal LivenessOutputsTarget(FaceRectangle faceRectangle, string fileName, int timeOffsetWithinFile, FaceImageType imageType, IDictionary serializedAdditionalRawData) + internal LivenessColorDecisionTarget(FaceRectangle faceRectangle, IDictionary serializedAdditionalRawData) { FaceRectangle = faceRectangle; - FileName = fileName; - TimeOffsetWithinFile = timeOffsetWithinFile; - ImageType = imageType; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal LivenessOutputsTarget() + /// Initializes a new instance of for deserialization. + internal LivenessColorDecisionTarget() { } /// The face region where the liveness classification was made on. public FaceRectangle FaceRectangle { get; } - /// The file name which contains the face rectangle where the liveness classification was made on. - public string FileName { get; } - /// The time offset within the file of the frame which contains the face rectangle where the liveness classification was made on. - public int TimeOffsetWithinFile { get; } - /// The image type which contains the face rectangle where the liveness classification was made on. - public FaceImageType ImageType { get; } } } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.Serialization.cs new file mode 100644 index 000000000000..20ea28c7a099 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Vision.Face +{ + public partial class LivenessDecisionTargets : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessDecisionTargets)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("color"u8); + writer.WriteObjectValue(Color, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LivenessDecisionTargets IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessDecisionTargets)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLivenessDecisionTargets(document.RootElement, options); + } + + internal static LivenessDecisionTargets DeserializeLivenessDecisionTargets(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + LivenessColorDecisionTarget color = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("color"u8)) + { + color = LivenessColorDecisionTarget.DeserializeLivenessColorDecisionTarget(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LivenessDecisionTargets(color, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LivenessDecisionTargets)} does not support writing '{options.Format}' format."); + } + } + + LivenessDecisionTargets IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessDecisionTargets(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LivenessDecisionTargets)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LivenessDecisionTargets FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessDecisionTargets(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.cs new file mode 100644 index 000000000000..8e64b0560f73 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Vision.Face +{ + /// The targets used for liveness classification. + public partial class LivenessDecisionTargets + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The target from color image used for liveness classification. + /// is null. + internal LivenessDecisionTargets(LivenessColorDecisionTarget color) + { + Argument.AssertNotNull(color, nameof(color)); + + Color = color; + } + + /// Initializes a new instance of . + /// The target from color image used for liveness classification. + /// Keeps track of any properties unknown to the library. + internal LivenessDecisionTargets(LivenessColorDecisionTarget color, IDictionary serializedAdditionalRawData) + { + Color = color; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessDecisionTargets() + { + } + + /// The target from color image used for liveness classification. + public LivenessColorDecisionTarget Color { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.Serialization.cs similarity index 57% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.Serialization.cs rename to sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.Serialization.cs index 3d4f997e8429..617f0c01c590 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.Vision.Face { - public partial class AuditLivenessResponseInfo : IUtf8JsonSerializable, IJsonModel + public partial class LivenessError : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,18 +28,18 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(AuditLivenessResponseInfo)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(LivenessError)} does not support writing '{format}' format."); } - writer.WritePropertyName("body"u8); - writer.WriteObjectValue(Body, options); - writer.WritePropertyName("statusCode"u8); - writer.WriteNumberValue(StatusCode); - writer.WritePropertyName("latencyInMilliseconds"u8); - writer.WriteNumberValue(LatencyInMilliseconds); + writer.WritePropertyName("code"u8); + writer.WriteStringValue(Code); + writer.WritePropertyName("message"u8); + writer.WriteStringValue(Message); + writer.WritePropertyName("targets"u8); + writer.WriteObjectValue(Targets, options); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -57,19 +57,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - AuditLivenessResponseInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + LivenessError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(AuditLivenessResponseInfo)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(LivenessError)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAuditLivenessResponseInfo(document.RootElement, options); + return DeserializeLivenessError(document.RootElement, options); } - internal static AuditLivenessResponseInfo DeserializeAuditLivenessResponseInfo(JsonElement element, ModelReaderWriterOptions options = null) + internal static LivenessError DeserializeLivenessError(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -77,26 +77,26 @@ internal static AuditLivenessResponseInfo DeserializeAuditLivenessResponseInfo(J { return null; } - LivenessResponseBody body = default; - int statusCode = default; - long latencyInMilliseconds = default; + string code = default; + string message = default; + LivenessDecisionTargets targets = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("body"u8)) + if (property.NameEquals("code"u8)) { - body = LivenessResponseBody.DeserializeLivenessResponseBody(property.Value, options); + code = property.Value.GetString(); continue; } - if (property.NameEquals("statusCode"u8)) + if (property.NameEquals("message"u8)) { - statusCode = property.Value.GetInt32(); + message = property.Value.GetString(); continue; } - if (property.NameEquals("latencyInMilliseconds"u8)) + if (property.NameEquals("targets"u8)) { - latencyInMilliseconds = property.Value.GetInt64(); + targets = LivenessDecisionTargets.DeserializeLivenessDecisionTargets(property.Value, options); continue; } if (options.Format != "W") @@ -105,46 +105,46 @@ internal static AuditLivenessResponseInfo DeserializeAuditLivenessResponseInfo(J } } serializedAdditionalRawData = rawDataDictionary; - return new AuditLivenessResponseInfo(body, statusCode, latencyInMilliseconds, serializedAdditionalRawData); + return new LivenessError(code, message, targets, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(AuditLivenessResponseInfo)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessError)} does not support writing '{options.Format}' format."); } } - AuditLivenessResponseInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + LivenessError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAuditLivenessResponseInfo(document.RootElement, options); + return DeserializeLivenessError(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(AuditLivenessResponseInfo)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessError)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static AuditLivenessResponseInfo FromResponse(Response response) + internal static LivenessError FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAuditLivenessResponseInfo(document.RootElement); + return DeserializeLivenessError(document.RootElement); } /// Convert into a . diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.cs new file mode 100644 index 000000000000..4b38aa3b7260 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Vision.Face +{ + /// The error of the liveness classification. + public partial class LivenessError + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The error code. + /// The error message. + /// Targets used for liveness classification. + /// , or is null. + internal LivenessError(string code, string message, LivenessDecisionTargets targets) + { + Argument.AssertNotNull(code, nameof(code)); + Argument.AssertNotNull(message, nameof(message)); + Argument.AssertNotNull(targets, nameof(targets)); + + Code = code; + Message = message; + Targets = targets; + } + + /// Initializes a new instance of . + /// The error code. + /// The error message. + /// Targets used for liveness classification. + /// Keeps track of any properties unknown to the library. + internal LivenessError(string code, string message, LivenessDecisionTargets targets, IDictionary serializedAdditionalRawData) + { + Code = code; + Message = message; + Targets = targets; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessError() + { + } + + /// The error code. + public string Code { get; } + /// The error message. + public string Message { get; } + /// Targets used for liveness classification. + public LivenessDecisionTargets Targets { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessModel.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessModel.cs index f5a0af9fc967..8cf63b931713 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessModel.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessModel.cs @@ -22,13 +22,10 @@ public LivenessModel(string value) _value = value ?? throw new ArgumentNullException(nameof(value)); } - private const string V20221015Preview04Value = "2022-10-15-preview.04"; - private const string V20231220Preview06Value = "2023-12-20-preview.06"; + private const string V20241115Value = "2024-11-15"; - /// 2022-10-15-preview.04. - public static LivenessModel V20221015Preview04 { get; } = new LivenessModel(V20221015Preview04Value); - /// 2023-12-20-preview.06. - public static LivenessModel V20231220Preview06 { get; } = new LivenessModel(V20231220Preview06Value); + /// 2024-11-15. + public static LivenessModel V20241115 { get; } = new LivenessModel(V20241115Value); /// Determines if two values are the same. public static bool operator ==(LivenessModel left, LivenessModel right) => left.Equals(right); /// Determines if two values are not the same. diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.Serialization.cs deleted file mode 100644 index 02ee779e066f..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.Serialization.cs +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.AI.Vision.Face -{ - public partial class LivenessResponseBody : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LivenessResponseBody)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(LivenessDecision)) - { - writer.WritePropertyName("livenessDecision"u8); - writer.WriteStringValue(LivenessDecision.Value.ToString()); - } - if (Optional.IsDefined(Target)) - { - writer.WritePropertyName("target"u8); - writer.WriteObjectValue(Target, options); - } - if (Optional.IsDefined(ModelVersionUsed)) - { - writer.WritePropertyName("modelVersionUsed"u8); - writer.WriteStringValue(ModelVersionUsed.Value.ToString()); - } - if (Optional.IsDefined(VerifyResult)) - { - writer.WritePropertyName("verifyResult"u8); - writer.WriteObjectValue(VerifyResult, options); - } - foreach (var item in AdditionalProperties) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - - LivenessResponseBody IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LivenessResponseBody)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLivenessResponseBody(document.RootElement, options); - } - - internal static LivenessResponseBody DeserializeLivenessResponseBody(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - FaceLivenessDecision? livenessDecision = default; - LivenessOutputsTarget target = default; - LivenessModel? modelVersionUsed = default; - LivenessWithVerifyOutputs verifyResult = default; - IReadOnlyDictionary additionalProperties = default; - Dictionary additionalPropertiesDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("livenessDecision"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - livenessDecision = new FaceLivenessDecision(property.Value.GetString()); - continue; - } - if (property.NameEquals("target"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - target = LivenessOutputsTarget.DeserializeLivenessOutputsTarget(property.Value, options); - continue; - } - if (property.NameEquals("modelVersionUsed"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - modelVersionUsed = new LivenessModel(property.Value.GetString()); - continue; - } - if (property.NameEquals("verifyResult"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - verifyResult = LivenessWithVerifyOutputs.DeserializeLivenessWithVerifyOutputs(property.Value, options); - continue; - } - additionalPropertiesDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - additionalProperties = additionalPropertiesDictionary; - return new LivenessResponseBody(livenessDecision, target, modelVersionUsed, verifyResult, additionalProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(LivenessResponseBody)} does not support writing '{options.Format}' format."); - } - } - - LivenessResponseBody IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessResponseBody(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(LivenessResponseBody)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The response to deserialize the model from. - internal static LivenessResponseBody FromResponse(Response response) - { - using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessResponseBody(document.RootElement); - } - - /// Convert into a . - internal virtual RequestContent ToRequestContent() - { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); - return content; - } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.cs deleted file mode 100644 index 5d831412b0a9..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// The response body of detect liveness API call. - public partial class LivenessResponseBody - { - /// Initializes a new instance of . - internal LivenessResponseBody() - { - AdditionalProperties = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// The liveness classification for the target face. - /// Specific targets used for liveness classification. - /// The model version used for liveness classification. - /// The face verification output. Only available when the request is liveness with verify. - /// Additional Properties. - internal LivenessResponseBody(FaceLivenessDecision? livenessDecision, LivenessOutputsTarget target, LivenessModel? modelVersionUsed, LivenessWithVerifyOutputs verifyResult, IReadOnlyDictionary additionalProperties) - { - LivenessDecision = livenessDecision; - Target = target; - ModelVersionUsed = modelVersionUsed; - VerifyResult = verifyResult; - AdditionalProperties = additionalProperties; - } - - /// The liveness classification for the target face. - public FaceLivenessDecision? LivenessDecision { get; } - /// Specific targets used for liveness classification. - public LivenessOutputsTarget Target { get; } - /// The model version used for liveness classification. - public LivenessModel? ModelVersionUsed { get; } - /// The face verification output. Only available when the request is liveness with verify. - public LivenessWithVerifyOutputs VerifyResult { get; } - /// - /// Additional Properties - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - public IReadOnlyDictionary AdditionalProperties { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.Serialization.cs similarity index 55% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.Serialization.cs rename to sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.Serialization.cs index fe769e9deb54..6a386a5fd74b 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.Vision.Face { - public partial class LivenessOutputsTarget : IUtf8JsonSerializable, IJsonModel + public partial class LivenessResult : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,20 +28,26 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessOutputsTarget)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(LivenessResult)} does not support writing '{format}' format."); } - writer.WritePropertyName("faceRectangle"u8); - writer.WriteObjectValue(FaceRectangle, options); - writer.WritePropertyName("fileName"u8); - writer.WriteStringValue(FileName); - writer.WritePropertyName("timeOffsetWithinFile"u8); - writer.WriteNumberValue(TimeOffsetWithinFile); - writer.WritePropertyName("imageType"u8); - writer.WriteStringValue(ImageType.ToString()); + if (Optional.IsDefined(LivenessDecision)) + { + writer.WritePropertyName("livenessDecision"u8); + writer.WriteStringValue(LivenessDecision.Value.ToString()); + } + writer.WritePropertyName("targets"u8); + writer.WriteObjectValue(Targets, options); + writer.WritePropertyName("digest"u8); + writer.WriteStringValue(Digest); + if (Optional.IsDefined(SessionImageId)) + { + writer.WritePropertyName("sessionImageId"u8); + writer.WriteStringValue(SessionImageId); + } if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -59,19 +65,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - LivenessOutputsTarget IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + LivenessResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessOutputsTarget)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(LivenessResult)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLivenessOutputsTarget(document.RootElement, options); + return DeserializeLivenessResult(document.RootElement, options); } - internal static LivenessOutputsTarget DeserializeLivenessOutputsTarget(JsonElement element, ModelReaderWriterOptions options = null) + internal static LivenessResult DeserializeLivenessResult(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -79,32 +85,36 @@ internal static LivenessOutputsTarget DeserializeLivenessOutputsTarget(JsonEleme { return null; } - FaceRectangle faceRectangle = default; - string fileName = default; - int timeOffsetWithinFile = default; - FaceImageType imageType = default; + FaceLivenessDecision? livenessDecision = default; + LivenessDecisionTargets targets = default; + string digest = default; + string sessionImageId = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("faceRectangle"u8)) + if (property.NameEquals("livenessDecision"u8)) { - faceRectangle = FaceRectangle.DeserializeFaceRectangle(property.Value, options); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + livenessDecision = new FaceLivenessDecision(property.Value.GetString()); continue; } - if (property.NameEquals("fileName"u8)) + if (property.NameEquals("targets"u8)) { - fileName = property.Value.GetString(); + targets = LivenessDecisionTargets.DeserializeLivenessDecisionTargets(property.Value, options); continue; } - if (property.NameEquals("timeOffsetWithinFile"u8)) + if (property.NameEquals("digest"u8)) { - timeOffsetWithinFile = property.Value.GetInt32(); + digest = property.Value.GetString(); continue; } - if (property.NameEquals("imageType"u8)) + if (property.NameEquals("sessionImageId"u8)) { - imageType = new FaceImageType(property.Value.GetString()); + sessionImageId = property.Value.GetString(); continue; } if (options.Format != "W") @@ -113,46 +123,46 @@ internal static LivenessOutputsTarget DeserializeLivenessOutputsTarget(JsonEleme } } serializedAdditionalRawData = rawDataDictionary; - return new LivenessOutputsTarget(faceRectangle, fileName, timeOffsetWithinFile, imageType, serializedAdditionalRawData); + return new LivenessResult(livenessDecision, targets, digest, sessionImageId, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(LivenessOutputsTarget)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessResult)} does not support writing '{options.Format}' format."); } } - LivenessOutputsTarget IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + LivenessResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessOutputsTarget(document.RootElement, options); + return DeserializeLivenessResult(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(LivenessOutputsTarget)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessResult)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static LivenessOutputsTarget FromResponse(Response response) + internal static LivenessResult FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessOutputsTarget(document.RootElement); + return DeserializeLivenessResult(document.RootElement); } /// Convert into a . diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.cs new file mode 100644 index 000000000000..cf20e1fdeca9 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.cs @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Vision.Face +{ + /// The results of the liveness classification. + public partial class LivenessResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Targets used for liveness classification. + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + /// or is null. + internal LivenessResult(LivenessDecisionTargets targets, string digest) + { + Argument.AssertNotNull(targets, nameof(targets)); + Argument.AssertNotNull(digest, nameof(digest)); + + Targets = targets; + Digest = digest; + } + + /// Initializes a new instance of . + /// The liveness classification for the target face. + /// Targets used for liveness classification. + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + /// The image ID of the session request. + /// Keeps track of any properties unknown to the library. + internal LivenessResult(FaceLivenessDecision? livenessDecision, LivenessDecisionTargets targets, string digest, string sessionImageId, IDictionary serializedAdditionalRawData) + { + LivenessDecision = livenessDecision; + Targets = targets; + Digest = digest; + SessionImageId = sessionImageId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessResult() + { + } + + /// The liveness classification for the target face. + public FaceLivenessDecision? LivenessDecision { get; } + /// Targets used for liveness classification. + public LivenessDecisionTargets Targets { get; } + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + public string Digest { get; } + /// The image ID of the session request. + public string SessionImageId { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.Serialization.cs index 64b251d3ced0..0513d2d422a9 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.Serialization.cs @@ -36,35 +36,20 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit if (options.Format != "W") { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - writer.WritePropertyName("createdDateTime"u8); - writer.WriteStringValue(CreatedDateTime, "O"); - if (Optional.IsDefined(SessionStartDateTime)) - { - writer.WritePropertyName("sessionStartDateTime"u8); - writer.WriteStringValue(SessionStartDateTime.Value, "O"); - } - writer.WritePropertyName("sessionExpired"u8); - writer.WriteBooleanValue(SessionExpired); - if (Optional.IsDefined(DeviceCorrelationId)) - { - writer.WritePropertyName("deviceCorrelationId"u8); - writer.WriteStringValue(DeviceCorrelationId); - } - if (Optional.IsDefined(AuthTokenTimeToLiveInSeconds)) - { - writer.WritePropertyName("authTokenTimeToLiveInSeconds"u8); - writer.WriteNumberValue(AuthTokenTimeToLiveInSeconds.Value); + writer.WritePropertyName("sessionId"u8); + writer.WriteStringValue(SessionId); } + writer.WritePropertyName("authToken"u8); + writer.WriteStringValue(AuthToken); writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); - if (Optional.IsDefined(Result)) + if (Optional.IsDefined(ModelVersion)) { - writer.WritePropertyName("result"u8); - writer.WriteObjectValue(Result, options); + writer.WritePropertyName("modelVersion"u8); + writer.WriteStringValue(ModelVersion.Value.ToString()); } + writer.WritePropertyName("results"u8); + writer.WriteObjectValue(Results, options); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -102,68 +87,42 @@ internal static LivenessSession DeserializeLivenessSession(JsonElement element, { return null; } - string id = default; - DateTimeOffset createdDateTime = default; - DateTimeOffset? sessionStartDateTime = default; - bool sessionExpired = default; - string deviceCorrelationId = default; - int? authTokenTimeToLiveInSeconds = default; - FaceSessionStatus status = default; - LivenessSessionAuditEntry result = default; + string sessionId = default; + string authToken = default; + OperationState status = default; + LivenessModel? modelVersion = default; + LivenessSessionResults results = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (property.NameEquals("sessionId"u8)) { - id = property.Value.GetString(); + sessionId = property.Value.GetString(); continue; } - if (property.NameEquals("createdDateTime"u8)) + if (property.NameEquals("authToken"u8)) { - createdDateTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("sessionStartDateTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sessionStartDateTime = property.Value.GetDateTimeOffset("O"); + authToken = property.Value.GetString(); continue; } - if (property.NameEquals("sessionExpired"u8)) - { - sessionExpired = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("deviceCorrelationId"u8)) + if (property.NameEquals("status"u8)) { - deviceCorrelationId = property.Value.GetString(); + status = new OperationState(property.Value.GetString()); continue; } - if (property.NameEquals("authTokenTimeToLiveInSeconds"u8)) + if (property.NameEquals("modelVersion"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - authTokenTimeToLiveInSeconds = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("status"u8)) - { - status = new FaceSessionStatus(property.Value.GetString()); + modelVersion = new LivenessModel(property.Value.GetString()); continue; } - if (property.NameEquals("result"u8)) + if (property.NameEquals("results"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - result = LivenessSessionAuditEntry.DeserializeLivenessSessionAuditEntry(property.Value, options); + results = LivenessSessionResults.DeserializeLivenessSessionResults(property.Value, options); continue; } if (options.Format != "W") @@ -173,14 +132,11 @@ internal static LivenessSession DeserializeLivenessSession(JsonElement element, } serializedAdditionalRawData = rawDataDictionary; return new LivenessSession( - id, - createdDateTime, - sessionStartDateTime, - sessionExpired, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + sessionId, + authToken, status, - result, + modelVersion, + results, serializedAdditionalRawData); } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.cs index bda0898e67ff..7a073ee5cd14 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.cs @@ -46,36 +46,34 @@ public partial class LivenessSession private IDictionary _serializedAdditionalRawData; /// Initializes a new instance of . - /// DateTime when this session was created. - /// Whether or not the session is expired. + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. /// The current status of the session. - internal LivenessSession(DateTimeOffset createdDateTime, bool sessionExpired, FaceSessionStatus status) + /// The results of the liveness session. + /// or is null. + internal LivenessSession(string authToken, OperationState status, LivenessSessionResults results) { - CreatedDateTime = createdDateTime; - SessionExpired = sessionExpired; + Argument.AssertNotNull(authToken, nameof(authToken)); + Argument.AssertNotNull(results, nameof(results)); + + AuthToken = authToken; Status = status; + Results = results; } /// Initializes a new instance of . - /// The unique ID to reference this session. - /// DateTime when this session was created. - /// DateTime when this session was started by the client. - /// Whether or not the session is expired. - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. + /// The unique ID to reference this session. + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. /// The current status of the session. - /// The latest session audit result only populated if status == 'ResultAvailable'. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The results of the liveness session. /// Keeps track of any properties unknown to the library. - internal LivenessSession(string id, DateTimeOffset createdDateTime, DateTimeOffset? sessionStartDateTime, bool sessionExpired, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, FaceSessionStatus status, LivenessSessionAuditEntry result, IDictionary serializedAdditionalRawData) + internal LivenessSession(string sessionId, string authToken, OperationState status, LivenessModel? modelVersion, LivenessSessionResults results, IDictionary serializedAdditionalRawData) { - Id = id; - CreatedDateTime = createdDateTime; - SessionStartDateTime = sessionStartDateTime; - SessionExpired = sessionExpired; - DeviceCorrelationId = deviceCorrelationId; - AuthTokenTimeToLiveInSeconds = authTokenTimeToLiveInSeconds; + SessionId = sessionId; + AuthToken = authToken; Status = status; - Result = result; + ModelVersion = modelVersion; + Results = results; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -85,20 +83,14 @@ internal LivenessSession() } /// The unique ID to reference this session. - public string Id { get; } - /// DateTime when this session was created. - public DateTimeOffset CreatedDateTime { get; } - /// DateTime when this session was started by the client. - public DateTimeOffset? SessionStartDateTime { get; } - /// Whether or not the session is expired. - public bool SessionExpired { get; } - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - public string DeviceCorrelationId { get; } - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - public int? AuthTokenTimeToLiveInSeconds { get; } + public string SessionId { get; } + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. + public string AuthToken { get; } /// The current status of the session. - public FaceSessionStatus Status { get; } - /// The latest session audit result only populated if status == 'ResultAvailable'. - public LivenessSessionAuditEntry Result { get; } + public OperationState Status { get; } + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + public LivenessModel? ModelVersion { get; } + /// The results of the liveness session. + public LivenessSessionResults Results { get; } } } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.Serialization.cs new file mode 100644 index 000000000000..35f22ed2bb12 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.Serialization.cs @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Vision.Face +{ + public partial class LivenessSessionAttempt : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessSessionAttempt)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("attemptId"u8); + writer.WriteNumberValue(AttemptId); + writer.WritePropertyName("attemptStatus"u8); + writer.WriteStringValue(AttemptStatus.ToString()); + if (Optional.IsDefined(Result)) + { + writer.WritePropertyName("result"u8); + writer.WriteObjectValue(Result, options); + } + if (Optional.IsDefined(Error)) + { + writer.WritePropertyName("error"u8); + writer.WriteObjectValue(Error, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LivenessSessionAttempt IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessSessionAttempt)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLivenessSessionAttempt(document.RootElement, options); + } + + internal static LivenessSessionAttempt DeserializeLivenessSessionAttempt(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int attemptId = default; + OperationState attemptStatus = default; + LivenessResult result = default; + LivenessError error = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("attemptId"u8)) + { + attemptId = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("attemptStatus"u8)) + { + attemptStatus = new OperationState(property.Value.GetString()); + continue; + } + if (property.NameEquals("result"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + result = LivenessResult.DeserializeLivenessResult(property.Value, options); + continue; + } + if (property.NameEquals("error"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + error = LivenessError.DeserializeLivenessError(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LivenessSessionAttempt(attemptId, attemptStatus, result, error, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LivenessSessionAttempt)} does not support writing '{options.Format}' format."); + } + } + + LivenessSessionAttempt IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessSessionAttempt(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LivenessSessionAttempt)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LivenessSessionAttempt FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessSessionAttempt(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.cs new file mode 100644 index 000000000000..0f414f5127d8 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Vision.Face +{ + /// The liveness session attempt. + public partial class LivenessSessionAttempt + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The attempt ID, start from 1. + /// The status of the attempt. + internal LivenessSessionAttempt(int attemptId, OperationState attemptStatus) + { + AttemptId = attemptId; + AttemptStatus = attemptStatus; + } + + /// Initializes a new instance of . + /// The attempt ID, start from 1. + /// The status of the attempt. + /// The result of the liveness call, will be null if there is error. + /// The error of the liveness call, will be null if there is result. + /// Keeps track of any properties unknown to the library. + internal LivenessSessionAttempt(int attemptId, OperationState attemptStatus, LivenessResult result, LivenessError error, IDictionary serializedAdditionalRawData) + { + AttemptId = attemptId; + AttemptStatus = attemptStatus; + Result = result; + Error = error; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessSessionAttempt() + { + } + + /// The attempt ID, start from 1. + public int AttemptId { get; } + /// The status of the attempt. + public OperationState AttemptStatus { get; } + /// The result of the liveness call, will be null if there is error. + public LivenessResult Result { get; } + /// The error of the liveness call, will be null if there is result. + public LivenessError Error { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.cs deleted file mode 100644 index 46b364a13ffd..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.cs +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// Audit entry for a request in session. - public partial class LivenessSessionAuditEntry - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The unique id to refer to this audit request. Use this id with the 'start' query parameter to continue on to the next page of audit results. - /// The unique sessionId of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding session DELETE operation. - /// The unique requestId that is returned by the service to the client in the 'apim-request-id' header. - /// The unique clientRequestId that is sent by the client in the 'client-request-id' header. - /// The UTC DateTime that the request was received. - /// The request of this entry. - /// The response of this entry. - /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. - /// , , , , or is null. - internal LivenessSessionAuditEntry(long id, string sessionId, string requestId, string clientRequestId, DateTimeOffset receivedDateTime, AuditRequestInfo request, AuditLivenessResponseInfo response, string digest) - { - Argument.AssertNotNull(sessionId, nameof(sessionId)); - Argument.AssertNotNull(requestId, nameof(requestId)); - Argument.AssertNotNull(clientRequestId, nameof(clientRequestId)); - Argument.AssertNotNull(request, nameof(request)); - Argument.AssertNotNull(response, nameof(response)); - Argument.AssertNotNull(digest, nameof(digest)); - - Id = id; - SessionId = sessionId; - RequestId = requestId; - ClientRequestId = clientRequestId; - ReceivedDateTime = receivedDateTime; - Request = request; - Response = response; - Digest = digest; - } - - /// Initializes a new instance of . - /// The unique id to refer to this audit request. Use this id with the 'start' query parameter to continue on to the next page of audit results. - /// The unique sessionId of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding session DELETE operation. - /// The unique requestId that is returned by the service to the client in the 'apim-request-id' header. - /// The unique clientRequestId that is sent by the client in the 'client-request-id' header. - /// The UTC DateTime that the request was received. - /// The request of this entry. - /// The response of this entry. - /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. - /// The image ID of the session request. - /// The sha256 hash of the verify-image in the request. - /// Keeps track of any properties unknown to the library. - internal LivenessSessionAuditEntry(long id, string sessionId, string requestId, string clientRequestId, DateTimeOffset receivedDateTime, AuditRequestInfo request, AuditLivenessResponseInfo response, string digest, string sessionImageId, string verifyImageHash, IDictionary serializedAdditionalRawData) - { - Id = id; - SessionId = sessionId; - RequestId = requestId; - ClientRequestId = clientRequestId; - ReceivedDateTime = receivedDateTime; - Request = request; - Response = response; - Digest = digest; - SessionImageId = sessionImageId; - VerifyImageHash = verifyImageHash; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal LivenessSessionAuditEntry() - { - } - - /// The unique id to refer to this audit request. Use this id with the 'start' query parameter to continue on to the next page of audit results. - public long Id { get; } - /// The unique sessionId of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding session DELETE operation. - public string SessionId { get; } - /// The unique requestId that is returned by the service to the client in the 'apim-request-id' header. - public string RequestId { get; } - /// The unique clientRequestId that is sent by the client in the 'client-request-id' header. - public string ClientRequestId { get; } - /// The UTC DateTime that the request was received. - public DateTimeOffset ReceivedDateTime { get; } - /// The request of this entry. - public AuditRequestInfo Request { get; } - /// The response of this entry. - public AuditLivenessResponseInfo Response { get; } - /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. - public string Digest { get; } - /// The image ID of the session request. - public string SessionImageId { get; } - /// The sha256 hash of the verify-image in the request. - public string VerifyImageHash { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.cs deleted file mode 100644 index e46e4901a8a1..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// Session data returned for enumeration. - public partial class LivenessSessionItem - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// DateTime when this session was created. - /// Whether or not the session is expired. - internal LivenessSessionItem(DateTimeOffset createdDateTime, bool sessionExpired) - { - CreatedDateTime = createdDateTime; - SessionExpired = sessionExpired; - } - - /// Initializes a new instance of . - /// The unique ID to reference this session. - /// DateTime when this session was created. - /// DateTime when this session was started by the client. - /// Whether or not the session is expired. - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - /// Keeps track of any properties unknown to the library. - internal LivenessSessionItem(string id, DateTimeOffset createdDateTime, DateTimeOffset? sessionStartDateTime, bool sessionExpired, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, IDictionary serializedAdditionalRawData) - { - Id = id; - CreatedDateTime = createdDateTime; - SessionStartDateTime = sessionStartDateTime; - SessionExpired = sessionExpired; - DeviceCorrelationId = deviceCorrelationId; - AuthTokenTimeToLiveInSeconds = authTokenTimeToLiveInSeconds; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal LivenessSessionItem() - { - } - - /// The unique ID to reference this session. - public string Id { get; } - /// DateTime when this session was created. - public DateTimeOffset CreatedDateTime { get; } - /// DateTime when this session was started by the client. - public DateTimeOffset? SessionStartDateTime { get; } - /// Whether or not the session is expired. - public bool SessionExpired { get; } - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - public string DeviceCorrelationId { get; } - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - public int? AuthTokenTimeToLiveInSeconds { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.Serialization.cs new file mode 100644 index 000000000000..75f8162577e8 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Vision.Face +{ + public partial class LivenessSessionResults : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessSessionResults)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("attempts"u8); + writer.WriteStartArray(); + foreach (var item in Attempts) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LivenessSessionResults IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessSessionResults)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLivenessSessionResults(document.RootElement, options); + } + + internal static LivenessSessionResults DeserializeLivenessSessionResults(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList attempts = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("attempts"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(LivenessSessionAttempt.DeserializeLivenessSessionAttempt(item, options)); + } + attempts = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LivenessSessionResults(attempts, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LivenessSessionResults)} does not support writing '{options.Format}' format."); + } + } + + LivenessSessionResults IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessSessionResults(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LivenessSessionResults)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LivenessSessionResults FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessSessionResults(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.cs new file mode 100644 index 000000000000..1a3686a45577 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.Vision.Face +{ + /// The results of the liveness session. + public partial class LivenessSessionResults + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The attempts data of underlying liveness call with the session. + /// is null. + internal LivenessSessionResults(IEnumerable attempts) + { + Argument.AssertNotNull(attempts, nameof(attempts)); + + Attempts = attempts.ToList(); + } + + /// Initializes a new instance of . + /// The attempts data of underlying liveness call with the session. + /// Keeps track of any properties unknown to the library. + internal LivenessSessionResults(IReadOnlyList attempts, IDictionary serializedAdditionalRawData) + { + Attempts = attempts; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessSessionResults() + { + } + + /// The attempts data of underlying liveness call with the session. + public IReadOnlyList Attempts { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.Serialization.cs index f82efb60a43d..79f11aaffbd3 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.Serialization.cs @@ -34,8 +34,6 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit throw new FormatException($"The model {nameof(LivenessWithVerifyOutputs)} does not support writing '{format}' format."); } - writer.WritePropertyName("verifyImage"u8); - writer.WriteObjectValue(VerifyImage, options); writer.WritePropertyName("matchConfidence"u8); writer.WriteNumberValue(MatchConfidence); writer.WritePropertyName("isIdentical"u8); @@ -77,18 +75,12 @@ internal static LivenessWithVerifyOutputs DeserializeLivenessWithVerifyOutputs(J { return null; } - LivenessWithVerifyImage verifyImage = default; float matchConfidence = default; bool isIdentical = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("verifyImage"u8)) - { - verifyImage = LivenessWithVerifyImage.DeserializeLivenessWithVerifyImage(property.Value, options); - continue; - } if (property.NameEquals("matchConfidence"u8)) { matchConfidence = property.Value.GetSingle(); @@ -105,7 +97,7 @@ internal static LivenessWithVerifyOutputs DeserializeLivenessWithVerifyOutputs(J } } serializedAdditionalRawData = rawDataDictionary; - return new LivenessWithVerifyOutputs(verifyImage, matchConfidence, isIdentical, serializedAdditionalRawData); + return new LivenessWithVerifyOutputs(matchConfidence, isIdentical, serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.cs index 45c6d6405b7f..3abf91ab403f 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.cs @@ -46,27 +46,20 @@ public partial class LivenessWithVerifyOutputs private IDictionary _serializedAdditionalRawData; /// Initializes a new instance of . - /// The detail of face for verification. /// The target face liveness face and comparison image face verification confidence. /// Whether the target liveness face and comparison image face match. - /// is null. - internal LivenessWithVerifyOutputs(LivenessWithVerifyImage verifyImage, float matchConfidence, bool isIdentical) + internal LivenessWithVerifyOutputs(float matchConfidence, bool isIdentical) { - Argument.AssertNotNull(verifyImage, nameof(verifyImage)); - - VerifyImage = verifyImage; MatchConfidence = matchConfidence; IsIdentical = isIdentical; } /// Initializes a new instance of . - /// The detail of face for verification. /// The target face liveness face and comparison image face verification confidence. /// Whether the target liveness face and comparison image face match. /// Keeps track of any properties unknown to the library. - internal LivenessWithVerifyOutputs(LivenessWithVerifyImage verifyImage, float matchConfidence, bool isIdentical, IDictionary serializedAdditionalRawData) + internal LivenessWithVerifyOutputs(float matchConfidence, bool isIdentical, IDictionary serializedAdditionalRawData) { - VerifyImage = verifyImage; MatchConfidence = matchConfidence; IsIdentical = isIdentical; _serializedAdditionalRawData = serializedAdditionalRawData; @@ -77,8 +70,6 @@ internal LivenessWithVerifyOutputs() { } - /// The detail of face for verification. - public LivenessWithVerifyImage VerifyImage { get; } /// The target face liveness face and comparison image face verification confidence. public float MatchConfidence { get; } /// Whether the target liveness face and comparison image face match. diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyImage.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyReference.Serialization.cs similarity index 65% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyImage.Serialization.cs rename to sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyReference.Serialization.cs index fa30773e4bc8..dcf2014c1505 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyImage.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyReference.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.Vision.Face { - public partial class LivenessWithVerifyImage : IUtf8JsonSerializable, IJsonModel + public partial class LivenessWithVerifyReference : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,12 +28,14 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessWithVerifyImage)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyReference)} does not support writing '{format}' format."); } + writer.WritePropertyName("referenceType"u8); + writer.WriteStringValue(ReferenceType.ToString()); writer.WritePropertyName("faceRectangle"u8); writer.WriteObjectValue(FaceRectangle, options); writer.WritePropertyName("qualityForRecognition"u8); @@ -55,19 +57,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - LivenessWithVerifyImage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + LivenessWithVerifyReference IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessWithVerifyImage)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyReference)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLivenessWithVerifyImage(document.RootElement, options); + return DeserializeLivenessWithVerifyReference(document.RootElement, options); } - internal static LivenessWithVerifyImage DeserializeLivenessWithVerifyImage(JsonElement element, ModelReaderWriterOptions options = null) + internal static LivenessWithVerifyReference DeserializeLivenessWithVerifyReference(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -75,12 +77,18 @@ internal static LivenessWithVerifyImage DeserializeLivenessWithVerifyImage(JsonE { return null; } + FaceImageType referenceType = default; FaceRectangle faceRectangle = default; QualityForRecognition qualityForRecognition = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { + if (property.NameEquals("referenceType"u8)) + { + referenceType = new FaceImageType(property.Value.GetString()); + continue; + } if (property.NameEquals("faceRectangle"u8)) { faceRectangle = FaceRectangle.DeserializeFaceRectangle(property.Value, options); @@ -97,46 +105,46 @@ internal static LivenessWithVerifyImage DeserializeLivenessWithVerifyImage(JsonE } } serializedAdditionalRawData = rawDataDictionary; - return new LivenessWithVerifyImage(faceRectangle, qualityForRecognition, serializedAdditionalRawData); + return new LivenessWithVerifyReference(referenceType, faceRectangle, qualityForRecognition, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(LivenessWithVerifyImage)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyReference)} does not support writing '{options.Format}' format."); } } - LivenessWithVerifyImage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + LivenessWithVerifyReference IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessWithVerifyImage(document.RootElement, options); + return DeserializeLivenessWithVerifyReference(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(LivenessWithVerifyImage)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyReference)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static LivenessWithVerifyImage FromResponse(Response response) + internal static LivenessWithVerifyReference FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessWithVerifyImage(document.RootElement); + return DeserializeLivenessWithVerifyReference(document.RootElement); } /// Convert into a . diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyImage.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyReference.cs similarity index 73% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyImage.cs rename to sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyReference.cs index 2cb09a6725ef..fe5f68bc902c 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyImage.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyReference.cs @@ -11,7 +11,7 @@ namespace Azure.AI.Vision.Face { /// The detail of face for verification. - public partial class LivenessWithVerifyImage + public partial class LivenessWithVerifyReference { /// /// Keeps track of any properties unknown to the library. @@ -45,34 +45,40 @@ public partial class LivenessWithVerifyImage /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . + /// The image type which contains the face rectangle where the liveness classification was made on. /// The face region where the comparison image's classification was made. /// Quality of face image for recognition. /// is null. - internal LivenessWithVerifyImage(FaceRectangle faceRectangle, QualityForRecognition qualityForRecognition) + internal LivenessWithVerifyReference(FaceImageType referenceType, FaceRectangle faceRectangle, QualityForRecognition qualityForRecognition) { Argument.AssertNotNull(faceRectangle, nameof(faceRectangle)); + ReferenceType = referenceType; FaceRectangle = faceRectangle; QualityForRecognition = qualityForRecognition; } - /// Initializes a new instance of . + /// Initializes a new instance of . + /// The image type which contains the face rectangle where the liveness classification was made on. /// The face region where the comparison image's classification was made. /// Quality of face image for recognition. /// Keeps track of any properties unknown to the library. - internal LivenessWithVerifyImage(FaceRectangle faceRectangle, QualityForRecognition qualityForRecognition, IDictionary serializedAdditionalRawData) + internal LivenessWithVerifyReference(FaceImageType referenceType, FaceRectangle faceRectangle, QualityForRecognition qualityForRecognition, IDictionary serializedAdditionalRawData) { + ReferenceType = referenceType; FaceRectangle = faceRectangle; QualityForRecognition = qualityForRecognition; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal LivenessWithVerifyImage() + /// Initializes a new instance of for deserialization. + internal LivenessWithVerifyReference() { } + /// The image type which contains the face rectangle where the liveness classification was made on. + public FaceImageType ReferenceType { get; } /// The face region where the comparison image's classification was made. public FaceRectangle FaceRectangle { get; } /// Quality of face image for recognition. diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.Serialization.cs similarity index 55% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.Serialization.cs rename to sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.Serialization.cs index 48df626d12e3..f34e22a4cdbe 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.Vision.Face { - public partial class LivenessSessionAuditEntry : IUtf8JsonSerializable, IJsonModel + public partial class LivenessWithVerifyResult : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,26 +28,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessSessionAuditEntry)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyResult)} does not support writing '{format}' format."); } - writer.WritePropertyName("id"u8); - writer.WriteNumberValue(Id); - writer.WritePropertyName("sessionId"u8); - writer.WriteStringValue(SessionId); - writer.WritePropertyName("requestId"u8); - writer.WriteStringValue(RequestId); - writer.WritePropertyName("clientRequestId"u8); - writer.WriteStringValue(ClientRequestId); - writer.WritePropertyName("receivedDateTime"u8); - writer.WriteStringValue(ReceivedDateTime, "O"); - writer.WritePropertyName("request"u8); - writer.WriteObjectValue(Request, options); - writer.WritePropertyName("response"u8); - writer.WriteObjectValue(Response, options); + if (Optional.IsDefined(LivenessDecision)) + { + writer.WritePropertyName("livenessDecision"u8); + writer.WriteStringValue(LivenessDecision.Value.ToString()); + } + writer.WritePropertyName("targets"u8); + writer.WriteObjectValue(Targets, options); writer.WritePropertyName("digest"u8); writer.WriteStringValue(Digest); if (Optional.IsDefined(SessionImageId)) @@ -55,6 +48,11 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("sessionImageId"u8); writer.WriteStringValue(SessionImageId); } + if (Optional.IsDefined(VerifyResult)) + { + writer.WritePropertyName("verifyResult"u8); + writer.WriteObjectValue(VerifyResult, options); + } if (Optional.IsDefined(VerifyImageHash)) { writer.WritePropertyName("verifyImageHash"u8); @@ -77,19 +75,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - LivenessSessionAuditEntry IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + LivenessWithVerifyResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessSessionAuditEntry)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyResult)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLivenessSessionAuditEntry(document.RootElement, options); + return DeserializeLivenessWithVerifyResult(document.RootElement, options); } - internal static LivenessSessionAuditEntry DeserializeLivenessSessionAuditEntry(JsonElement element, ModelReaderWriterOptions options = null) + internal static LivenessWithVerifyResult DeserializeLivenessWithVerifyResult(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -97,53 +95,28 @@ internal static LivenessSessionAuditEntry DeserializeLivenessSessionAuditEntry(J { return null; } - long id = default; - string sessionId = default; - string requestId = default; - string clientRequestId = default; - DateTimeOffset receivedDateTime = default; - AuditRequestInfo request = default; - AuditLivenessResponseInfo response = default; + FaceLivenessDecision? livenessDecision = default; + LivenessDecisionTargets targets = default; string digest = default; string sessionImageId = default; + LivenessWithVerifyOutputs verifyResult = default; string verifyImageHash = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetInt64(); - continue; - } - if (property.NameEquals("sessionId"u8)) - { - sessionId = property.Value.GetString(); - continue; - } - if (property.NameEquals("requestId"u8)) - { - requestId = property.Value.GetString(); - continue; - } - if (property.NameEquals("clientRequestId"u8)) + if (property.NameEquals("livenessDecision"u8)) { - clientRequestId = property.Value.GetString(); - continue; - } - if (property.NameEquals("receivedDateTime"u8)) - { - receivedDateTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("request"u8)) - { - request = AuditRequestInfo.DeserializeAuditRequestInfo(property.Value, options); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + livenessDecision = new FaceLivenessDecision(property.Value.GetString()); continue; } - if (property.NameEquals("response"u8)) + if (property.NameEquals("targets"u8)) { - response = AuditLivenessResponseInfo.DeserializeAuditLivenessResponseInfo(property.Value, options); + targets = LivenessDecisionTargets.DeserializeLivenessDecisionTargets(property.Value, options); continue; } if (property.NameEquals("digest"u8)) @@ -156,6 +129,15 @@ internal static LivenessSessionAuditEntry DeserializeLivenessSessionAuditEntry(J sessionImageId = property.Value.GetString(); continue; } + if (property.NameEquals("verifyResult"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + verifyResult = LivenessWithVerifyOutputs.DeserializeLivenessWithVerifyOutputs(property.Value, options); + continue; + } if (property.NameEquals("verifyImageHash"u8)) { verifyImageHash = property.Value.GetString(); @@ -167,57 +149,53 @@ internal static LivenessSessionAuditEntry DeserializeLivenessSessionAuditEntry(J } } serializedAdditionalRawData = rawDataDictionary; - return new LivenessSessionAuditEntry( - id, - sessionId, - requestId, - clientRequestId, - receivedDateTime, - request, - response, + return new LivenessWithVerifyResult( + livenessDecision, + targets, digest, sessionImageId, + verifyResult, verifyImageHash, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(LivenessSessionAuditEntry)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyResult)} does not support writing '{options.Format}' format."); } } - LivenessSessionAuditEntry IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + LivenessWithVerifyResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessSessionAuditEntry(document.RootElement, options); + return DeserializeLivenessWithVerifyResult(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(LivenessSessionAuditEntry)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyResult)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static LivenessSessionAuditEntry FromResponse(Response response) + internal static LivenessWithVerifyResult FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessSessionAuditEntry(document.RootElement); + return DeserializeLivenessWithVerifyResult(document.RootElement); } /// Convert into a . diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.cs new file mode 100644 index 000000000000..730d5cac8f3c --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.cs @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Vision.Face +{ + /// The results of the liveness with verify call. + public partial class LivenessWithVerifyResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Targets used for liveness classification. + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + /// or is null. + internal LivenessWithVerifyResult(LivenessDecisionTargets targets, string digest) + { + Argument.AssertNotNull(targets, nameof(targets)); + Argument.AssertNotNull(digest, nameof(digest)); + + Targets = targets; + Digest = digest; + } + + /// Initializes a new instance of . + /// The liveness classification for the target face. + /// Targets used for liveness classification. + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + /// The image ID of the session request. + /// The face verification output. Only available when the request is liveness with verify. + /// The sha256 hash of the verify-image in the request. + /// Keeps track of any properties unknown to the library. + internal LivenessWithVerifyResult(FaceLivenessDecision? livenessDecision, LivenessDecisionTargets targets, string digest, string sessionImageId, LivenessWithVerifyOutputs verifyResult, string verifyImageHash, IDictionary serializedAdditionalRawData) + { + LivenessDecision = livenessDecision; + Targets = targets; + Digest = digest; + SessionImageId = sessionImageId; + VerifyResult = verifyResult; + VerifyImageHash = verifyImageHash; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessWithVerifyResult() + { + } + + /// The liveness classification for the target face. + public FaceLivenessDecision? LivenessDecision { get; } + /// Targets used for liveness classification. + public LivenessDecisionTargets Targets { get; } + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + public string Digest { get; } + /// The image ID of the session request. + public string SessionImageId { get; } + /// The face verification output. Only available when the request is liveness with verify. + public LivenessWithVerifyOutputs VerifyResult { get; } + /// The sha256 hash of the verify-image in the request. + public string VerifyImageHash { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.Serialization.cs index d025789726cf..e8db35212e75 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.Serialization.cs @@ -36,35 +36,20 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit if (options.Format != "W") { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - writer.WritePropertyName("createdDateTime"u8); - writer.WriteStringValue(CreatedDateTime, "O"); - if (Optional.IsDefined(SessionStartDateTime)) - { - writer.WritePropertyName("sessionStartDateTime"u8); - writer.WriteStringValue(SessionStartDateTime.Value, "O"); - } - writer.WritePropertyName("sessionExpired"u8); - writer.WriteBooleanValue(SessionExpired); - if (Optional.IsDefined(DeviceCorrelationId)) - { - writer.WritePropertyName("deviceCorrelationId"u8); - writer.WriteStringValue(DeviceCorrelationId); - } - if (Optional.IsDefined(AuthTokenTimeToLiveInSeconds)) - { - writer.WritePropertyName("authTokenTimeToLiveInSeconds"u8); - writer.WriteNumberValue(AuthTokenTimeToLiveInSeconds.Value); + writer.WritePropertyName("sessionId"u8); + writer.WriteStringValue(SessionId); } + writer.WritePropertyName("authToken"u8); + writer.WriteStringValue(AuthToken); writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); - if (Optional.IsDefined(Result)) + if (Optional.IsDefined(ModelVersion)) { - writer.WritePropertyName("result"u8); - writer.WriteObjectValue(Result, options); + writer.WritePropertyName("modelVersion"u8); + writer.WriteStringValue(ModelVersion.Value.ToString()); } + writer.WritePropertyName("results"u8); + writer.WriteObjectValue(Results, options); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -102,68 +87,42 @@ internal static LivenessWithVerifySession DeserializeLivenessWithVerifySession(J { return null; } - string id = default; - DateTimeOffset createdDateTime = default; - DateTimeOffset? sessionStartDateTime = default; - bool sessionExpired = default; - string deviceCorrelationId = default; - int? authTokenTimeToLiveInSeconds = default; - FaceSessionStatus status = default; - LivenessSessionAuditEntry result = default; + string sessionId = default; + string authToken = default; + OperationState status = default; + LivenessModel? modelVersion = default; + LivenessWithVerifySessionResults results = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (property.NameEquals("sessionId"u8)) { - id = property.Value.GetString(); + sessionId = property.Value.GetString(); continue; } - if (property.NameEquals("createdDateTime"u8)) + if (property.NameEquals("authToken"u8)) { - createdDateTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("sessionStartDateTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sessionStartDateTime = property.Value.GetDateTimeOffset("O"); + authToken = property.Value.GetString(); continue; } - if (property.NameEquals("sessionExpired"u8)) - { - sessionExpired = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("deviceCorrelationId"u8)) + if (property.NameEquals("status"u8)) { - deviceCorrelationId = property.Value.GetString(); + status = new OperationState(property.Value.GetString()); continue; } - if (property.NameEquals("authTokenTimeToLiveInSeconds"u8)) + if (property.NameEquals("modelVersion"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - authTokenTimeToLiveInSeconds = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("status"u8)) - { - status = new FaceSessionStatus(property.Value.GetString()); + modelVersion = new LivenessModel(property.Value.GetString()); continue; } - if (property.NameEquals("result"u8)) + if (property.NameEquals("results"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - result = LivenessSessionAuditEntry.DeserializeLivenessSessionAuditEntry(property.Value, options); + results = LivenessWithVerifySessionResults.DeserializeLivenessWithVerifySessionResults(property.Value, options); continue; } if (options.Format != "W") @@ -173,14 +132,11 @@ internal static LivenessWithVerifySession DeserializeLivenessWithVerifySession(J } serializedAdditionalRawData = rawDataDictionary; return new LivenessWithVerifySession( - id, - createdDateTime, - sessionStartDateTime, - sessionExpired, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + sessionId, + authToken, status, - result, + modelVersion, + results, serializedAdditionalRawData); } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.cs index 9aaec1db8d47..5db8b918edbc 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.cs @@ -46,36 +46,34 @@ public partial class LivenessWithVerifySession private IDictionary _serializedAdditionalRawData; /// Initializes a new instance of . - /// DateTime when this session was created. - /// Whether or not the session is expired. + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. /// The current status of the session. - internal LivenessWithVerifySession(DateTimeOffset createdDateTime, bool sessionExpired, FaceSessionStatus status) + /// The results of the liveness with verify session. + /// or is null. + internal LivenessWithVerifySession(string authToken, OperationState status, LivenessWithVerifySessionResults results) { - CreatedDateTime = createdDateTime; - SessionExpired = sessionExpired; + Argument.AssertNotNull(authToken, nameof(authToken)); + Argument.AssertNotNull(results, nameof(results)); + + AuthToken = authToken; Status = status; + Results = results; } /// Initializes a new instance of . - /// The unique ID to reference this session. - /// DateTime when this session was created. - /// DateTime when this session was started by the client. - /// Whether or not the session is expired. - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. + /// The unique ID to reference this session. + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. /// The current status of the session. - /// The latest session audit result only populated if status == 'ResultAvailable'. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The results of the liveness with verify session. /// Keeps track of any properties unknown to the library. - internal LivenessWithVerifySession(string id, DateTimeOffset createdDateTime, DateTimeOffset? sessionStartDateTime, bool sessionExpired, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, FaceSessionStatus status, LivenessSessionAuditEntry result, IDictionary serializedAdditionalRawData) + internal LivenessWithVerifySession(string sessionId, string authToken, OperationState status, LivenessModel? modelVersion, LivenessWithVerifySessionResults results, IDictionary serializedAdditionalRawData) { - Id = id; - CreatedDateTime = createdDateTime; - SessionStartDateTime = sessionStartDateTime; - SessionExpired = sessionExpired; - DeviceCorrelationId = deviceCorrelationId; - AuthTokenTimeToLiveInSeconds = authTokenTimeToLiveInSeconds; + SessionId = sessionId; + AuthToken = authToken; Status = status; - Result = result; + ModelVersion = modelVersion; + Results = results; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -85,20 +83,14 @@ internal LivenessWithVerifySession() } /// The unique ID to reference this session. - public string Id { get; } - /// DateTime when this session was created. - public DateTimeOffset CreatedDateTime { get; } - /// DateTime when this session was started by the client. - public DateTimeOffset? SessionStartDateTime { get; } - /// Whether or not the session is expired. - public bool SessionExpired { get; } - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - public string DeviceCorrelationId { get; } - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - public int? AuthTokenTimeToLiveInSeconds { get; } + public string SessionId { get; } + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. + public string AuthToken { get; } /// The current status of the session. - public FaceSessionStatus Status { get; } - /// The latest session audit result only populated if status == 'ResultAvailable'. - public LivenessSessionAuditEntry Result { get; } + public OperationState Status { get; } + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + public LivenessModel? ModelVersion { get; } + /// The results of the liveness with verify session. + public LivenessWithVerifySessionResults Results { get; } } } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.Serialization.cs similarity index 51% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.Serialization.cs rename to sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.Serialization.cs index e86fb126c760..97f9fadec5e6 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.Vision.Face { - public partial class LivenessSessionItem : IUtf8JsonSerializable, IJsonModel + public partial class LivenessWithVerifySessionAttempt : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,35 +28,25 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessSessionItem)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifySessionAttempt)} does not support writing '{format}' format."); } - if (options.Format != "W") + writer.WritePropertyName("attemptId"u8); + writer.WriteNumberValue(AttemptId); + writer.WritePropertyName("attemptStatus"u8); + writer.WriteStringValue(AttemptStatus.ToString()); + if (Optional.IsDefined(Result)) { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); + writer.WritePropertyName("result"u8); + writer.WriteObjectValue(Result, options); } - writer.WritePropertyName("createdDateTime"u8); - writer.WriteStringValue(CreatedDateTime, "O"); - if (Optional.IsDefined(SessionStartDateTime)) + if (Optional.IsDefined(Error)) { - writer.WritePropertyName("sessionStartDateTime"u8); - writer.WriteStringValue(SessionStartDateTime.Value, "O"); - } - writer.WritePropertyName("sessionExpired"u8); - writer.WriteBooleanValue(SessionExpired); - if (Optional.IsDefined(DeviceCorrelationId)) - { - writer.WritePropertyName("deviceCorrelationId"u8); - writer.WriteStringValue(DeviceCorrelationId); - } - if (Optional.IsDefined(AuthTokenTimeToLiveInSeconds)) - { - writer.WritePropertyName("authTokenTimeToLiveInSeconds"u8); - writer.WriteNumberValue(AuthTokenTimeToLiveInSeconds.Value); + writer.WritePropertyName("error"u8); + writer.WriteObjectValue(Error, options); } if (options.Format != "W" && _serializedAdditionalRawData != null) { @@ -75,19 +65,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - LivenessSessionItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + LivenessWithVerifySessionAttempt IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessSessionItem)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifySessionAttempt)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLivenessSessionItem(document.RootElement, options); + return DeserializeLivenessWithVerifySessionAttempt(document.RootElement, options); } - internal static LivenessSessionItem DeserializeLivenessSessionItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static LivenessWithVerifySessionAttempt DeserializeLivenessWithVerifySessionAttempt(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -95,52 +85,40 @@ internal static LivenessSessionItem DeserializeLivenessSessionItem(JsonElement e { return null; } - string id = default; - DateTimeOffset createdDateTime = default; - DateTimeOffset? sessionStartDateTime = default; - bool sessionExpired = default; - string deviceCorrelationId = default; - int? authTokenTimeToLiveInSeconds = default; + int attemptId = default; + OperationState attemptStatus = default; + LivenessWithVerifyResult result = default; + LivenessError error = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (property.NameEquals("attemptId"u8)) { - id = property.Value.GetString(); + attemptId = property.Value.GetInt32(); continue; } - if (property.NameEquals("createdDateTime"u8)) + if (property.NameEquals("attemptStatus"u8)) { - createdDateTime = property.Value.GetDateTimeOffset("O"); + attemptStatus = new OperationState(property.Value.GetString()); continue; } - if (property.NameEquals("sessionStartDateTime"u8)) + if (property.NameEquals("result"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - sessionStartDateTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("sessionExpired"u8)) - { - sessionExpired = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("deviceCorrelationId"u8)) - { - deviceCorrelationId = property.Value.GetString(); + result = LivenessWithVerifyResult.DeserializeLivenessWithVerifyResult(property.Value, options); continue; } - if (property.NameEquals("authTokenTimeToLiveInSeconds"u8)) + if (property.NameEquals("error"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - authTokenTimeToLiveInSeconds = property.Value.GetInt32(); + error = LivenessError.DeserializeLivenessError(property.Value, options); continue; } if (options.Format != "W") @@ -149,53 +127,46 @@ internal static LivenessSessionItem DeserializeLivenessSessionItem(JsonElement e } } serializedAdditionalRawData = rawDataDictionary; - return new LivenessSessionItem( - id, - createdDateTime, - sessionStartDateTime, - sessionExpired, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, - serializedAdditionalRawData); + return new LivenessWithVerifySessionAttempt(attemptId, attemptStatus, result, error, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(LivenessSessionItem)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifySessionAttempt)} does not support writing '{options.Format}' format."); } } - LivenessSessionItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + LivenessWithVerifySessionAttempt IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessSessionItem(document.RootElement, options); + return DeserializeLivenessWithVerifySessionAttempt(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(LivenessSessionItem)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifySessionAttempt)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static LivenessSessionItem FromResponse(Response response) + internal static LivenessWithVerifySessionAttempt FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessSessionItem(document.RootElement); + return DeserializeLivenessWithVerifySessionAttempt(document.RootElement); } /// Convert into a . diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.cs new file mode 100644 index 000000000000..947837cf1967 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Vision.Face +{ + /// The liveness with verify session attempt. + public partial class LivenessWithVerifySessionAttempt + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The attempt ID, start from 1. + /// The status of the attempt. + internal LivenessWithVerifySessionAttempt(int attemptId, OperationState attemptStatus) + { + AttemptId = attemptId; + AttemptStatus = attemptStatus; + } + + /// Initializes a new instance of . + /// The attempt ID, start from 1. + /// The status of the attempt. + /// The result of the liveness with verify call, will be null if there is error. + /// The error of the liveness with verify call, will be null if there is result. + /// Keeps track of any properties unknown to the library. + internal LivenessWithVerifySessionAttempt(int attemptId, OperationState attemptStatus, LivenessWithVerifyResult result, LivenessError error, IDictionary serializedAdditionalRawData) + { + AttemptId = attemptId; + AttemptStatus = attemptStatus; + Result = result; + Error = error; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessWithVerifySessionAttempt() + { + } + + /// The attempt ID, start from 1. + public int AttemptId { get; } + /// The status of the attempt. + public OperationState AttemptStatus { get; } + /// The result of the liveness with verify call, will be null if there is error. + public LivenessWithVerifyResult Result { get; } + /// The error of the liveness with verify call, will be null if there is result. + public LivenessError Error { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.Serialization.cs new file mode 100644 index 000000000000..9a8dda439b7b --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.Serialization.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Vision.Face +{ + public partial class LivenessWithVerifySessionResults : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessWithVerifySessionResults)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("verifyReferences"u8); + writer.WriteStartArray(); + foreach (var item in VerifyReferences) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + writer.WritePropertyName("attempts"u8); + writer.WriteStartArray(); + foreach (var item in Attempts) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LivenessWithVerifySessionResults IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessWithVerifySessionResults)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLivenessWithVerifySessionResults(document.RootElement, options); + } + + internal static LivenessWithVerifySessionResults DeserializeLivenessWithVerifySessionResults(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList verifyReferences = default; + IReadOnlyList attempts = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("verifyReferences"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(LivenessWithVerifyReference.DeserializeLivenessWithVerifyReference(item, options)); + } + verifyReferences = array; + continue; + } + if (property.NameEquals("attempts"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(LivenessWithVerifySessionAttempt.DeserializeLivenessWithVerifySessionAttempt(item, options)); + } + attempts = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LivenessWithVerifySessionResults(verifyReferences, attempts, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LivenessWithVerifySessionResults)} does not support writing '{options.Format}' format."); + } + } + + LivenessWithVerifySessionResults IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessWithVerifySessionResults(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LivenessWithVerifySessionResults)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LivenessWithVerifySessionResults FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessWithVerifySessionResults(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.cs new file mode 100644 index 000000000000..570a83f964c2 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.Vision.Face +{ + /// The results of the liveness with verify session. + public partial class LivenessWithVerifySessionResults + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The references used for face verification. + /// The attempts data of underlying liveness with verify call with the session. + /// or is null. + internal LivenessWithVerifySessionResults(IEnumerable verifyReferences, IEnumerable attempts) + { + Argument.AssertNotNull(verifyReferences, nameof(verifyReferences)); + Argument.AssertNotNull(attempts, nameof(attempts)); + + VerifyReferences = verifyReferences.ToList(); + Attempts = attempts.ToList(); + } + + /// Initializes a new instance of . + /// The references used for face verification. + /// The attempts data of underlying liveness with verify call with the session. + /// Keeps track of any properties unknown to the library. + internal LivenessWithVerifySessionResults(IReadOnlyList verifyReferences, IReadOnlyList attempts, IDictionary serializedAdditionalRawData) + { + VerifyReferences = verifyReferences; + Attempts = attempts; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessWithVerifySessionResults() + { + } + + /// The references used for face verification. + public IReadOnlyList VerifyReferences { get; } + /// The attempts data of underlying liveness with verify call with the session. + public IReadOnlyList Attempts { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/OperationState.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/OperationState.cs new file mode 100644 index 000000000000..11c8033fba6a --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/OperationState.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.AI.Vision.Face +{ + /// Enum describing allowed operation states. + public readonly partial struct OperationState : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OperationState(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string NotStartedValue = "NotStarted"; + private const string RunningValue = "Running"; + private const string SucceededValue = "Succeeded"; + private const string FailedValue = "Failed"; + private const string CanceledValue = "Canceled"; + + /// The operation has not started. + public static OperationState NotStarted { get; } = new OperationState(NotStartedValue); + /// The operation is in progress. + public static OperationState Running { get; } = new OperationState(RunningValue); + /// The operation has completed successfully. + public static OperationState Succeeded { get; } = new OperationState(SucceededValue); + /// The operation has failed. + public static OperationState Failed { get; } = new OperationState(FailedValue); + /// The operation has been canceled by the user. + public static OperationState Canceled { get; } = new OperationState(CanceledValue); + /// Determines if two values are the same. + public static bool operator ==(OperationState left, OperationState right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OperationState left, OperationState right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OperationState(string value) => new OperationState(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OperationState other && Equals(other); + /// + public bool Equals(OperationState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/tests/Generated/Samples/Samples_FaceSessionClient.cs b/sdk/face/Azure.AI.Vision.Face/tests/Generated/Samples/Samples_FaceSessionClient.cs index b793cf92c5e9..01e05583b87c 100644 --- a/sdk/face/Azure.AI.Vision.Face/tests/Generated/Samples/Samples_FaceSessionClient.cs +++ b/sdk/face/Azure.AI.Vision.Face/tests/Generated/Samples/Samples_FaceSessionClient.cs @@ -28,8 +28,7 @@ public void Example_LivenessSession_CreateLivenessSession_CreateLivenessSession( using RequestContent content = RequestContent.Create(new { livenessOperationMode = "Passive", - sendResultsToClient = true, - deviceCorrelationIdSetInClient = true, + deviceCorrelationIdSetInClient = false, deviceCorrelationId = "your_device_correlation_id", authTokenTimeToLiveInSeconds = 60, }); @@ -38,6 +37,9 @@ public void Example_LivenessSession_CreateLivenessSession_CreateLivenessSession( JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; Console.WriteLine(result.GetProperty("sessionId").ToString()); Console.WriteLine(result.GetProperty("authToken").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] @@ -51,8 +53,7 @@ public async Task Example_LivenessSession_CreateLivenessSession_CreateLivenessSe using RequestContent content = RequestContent.Create(new { livenessOperationMode = "Passive", - sendResultsToClient = true, - deviceCorrelationIdSetInClient = true, + deviceCorrelationIdSetInClient = false, deviceCorrelationId = "your_device_correlation_id", authTokenTimeToLiveInSeconds = 60, }); @@ -61,6 +62,9 @@ public async Task Example_LivenessSession_CreateLivenessSession_CreateLivenessSe JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; Console.WriteLine(result.GetProperty("sessionId").ToString()); Console.WriteLine(result.GetProperty("authToken").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] @@ -73,12 +77,11 @@ public void Example_LivenessSession_CreateLivenessSession_CreateLivenessSession_ CreateLivenessSessionContent body = new CreateLivenessSessionContent(LivenessOperationMode.Passive) { - SendResultsToClient = true, - DeviceCorrelationIdSetInClient = true, + DeviceCorrelationIdSetInClient = false, DeviceCorrelationId = "your_device_correlation_id", AuthTokenTimeToLiveInSeconds = 60, }; - Response response = client.CreateLivenessSession(body); + Response response = client.CreateLivenessSession(body); } [Test] @@ -91,12 +94,11 @@ public async Task Example_LivenessSession_CreateLivenessSession_CreateLivenessSe CreateLivenessSessionContent body = new CreateLivenessSessionContent(LivenessOperationMode.Passive) { - SendResultsToClient = true, - DeviceCorrelationIdSetInClient = true, + DeviceCorrelationIdSetInClient = false, DeviceCorrelationId = "your_device_correlation_id", AuthTokenTimeToLiveInSeconds = 60, }; - Response response = await client.CreateLivenessSessionAsync(body); + Response response = await client.CreateLivenessSessionAsync(body); } [Test] @@ -136,10 +138,11 @@ public void Example_LivenessSession_GetLivenessSessionResult_GetLivenessSessionR Response response = client.GetLivenessSessionResult("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result.GetProperty("id").ToString()); - Console.WriteLine(result.GetProperty("createdDateTime").ToString()); - Console.WriteLine(result.GetProperty("sessionExpired").ToString()); + Console.WriteLine(result.GetProperty("sessionId").ToString()); + Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] @@ -153,10 +156,11 @@ public async Task Example_LivenessSession_GetLivenessSessionResult_GetLivenessSe Response response = await client.GetLivenessSessionResultAsync("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result.GetProperty("id").ToString()); - Console.WriteLine(result.GetProperty("createdDateTime").ToString()); - Console.WriteLine(result.GetProperty("sessionExpired").ToString()); + Console.WriteLine(result.GetProperty("sessionId").ToString()); + Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] @@ -183,128 +187,76 @@ public async Task Example_LivenessSession_GetLivenessSessionResult_GetLivenessSe [Test] [Ignore("Only validating compilation of examples")] - public void Example_LivenessSession_GetLivenessSessions_GetLivenessSessions() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = client.GetLivenessSessions("00000000-0000-0000-0000-000000000000", 20, null); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_LivenessSession_GetLivenessSessions_GetLivenessSessions_Async() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = await client.GetLivenessSessionsAsync("00000000-0000-0000-0000-000000000000", 20, null); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_LivenessSession_GetLivenessSessions_GetLivenessSessions_Convenience() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response> response = client.GetLivenessSessions(); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_LivenessSession_GetLivenessSessions_GetLivenessSessions_Convenience_Async() + public void Example_LivenessWithVerifySession_CreateLivenessWithVerifySession_CreateLivenessWithVerifySession() { Uri endpoint = new Uri(""); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); - Response> response = await client.GetLivenessSessionsAsync(); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_FaceSessionClient_GetLivenessSessionAuditEntries_GetLivenessSessionAuditEntries() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = client.GetLivenessSessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); + using RequestContent content = null; + Response response = client.CreateLivenessWithVerifySession(content, null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("sessionId").ToString()); - Console.WriteLine(result[0].GetProperty("requestId").ToString()); - Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); - Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); - Console.WriteLine(result[0].GetProperty("digest").ToString()); + Console.WriteLine(result.GetProperty("sessionId").ToString()); + Console.WriteLine(result.GetProperty("authToken").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Example_FaceSessionClient_GetLivenessSessionAuditEntries_GetLivenessSessionAuditEntries_Async() + public async Task Example_LivenessWithVerifySession_CreateLivenessWithVerifySession_CreateLivenessWithVerifySession_Async() { Uri endpoint = new Uri(""); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); - Response response = await client.GetLivenessSessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); + using RequestContent content = null; + Response response = await client.CreateLivenessWithVerifySessionAsync(content, null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("sessionId").ToString()); - Console.WriteLine(result[0].GetProperty("requestId").ToString()); - Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); - Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); - Console.WriteLine(result[0].GetProperty("digest").ToString()); + Console.WriteLine(result.GetProperty("sessionId").ToString()); + Console.WriteLine(result.GetProperty("authToken").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] [Ignore("Only validating compilation of examples")] - public void Example_FaceSessionClient_GetLivenessSessionAuditEntries_GetLivenessSessionAuditEntries_Convenience() + public void Example_LivenessWithVerifySession_CreateLivenessWithVerifySession_CreateLivenessWithVerifySession_Convenience() { Uri endpoint = new Uri(""); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); - Response> response = client.GetLivenessSessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e"); + CreateLivenessWithVerifySessionContent body = null; + Response response = client.CreateLivenessWithVerifySession(body); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Example_FaceSessionClient_GetLivenessSessionAuditEntries_GetLivenessSessionAuditEntries_Convenience_Async() + public async Task Example_LivenessWithVerifySession_CreateLivenessWithVerifySession_CreateLivenessWithVerifySession_Convenience_Async() { Uri endpoint = new Uri(""); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); - Response> response = await client.GetLivenessSessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e"); + CreateLivenessWithVerifySessionContent body = null; + Response response = await client.CreateLivenessWithVerifySessionAsync(body); } [Test] @@ -344,10 +296,17 @@ public void Example_LivenessWithVerifySession_GetLivenessWithVerifySessionResult Response response = client.GetLivenessWithVerifySessionResult("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result.GetProperty("id").ToString()); - Console.WriteLine(result.GetProperty("createdDateTime").ToString()); - Console.WriteLine(result.GetProperty("sessionExpired").ToString()); + Console.WriteLine(result.GetProperty("sessionId").ToString()); + Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] @@ -361,10 +320,17 @@ public async Task Example_LivenessWithVerifySession_GetLivenessWithVerifySession Response response = await client.GetLivenessWithVerifySessionResultAsync("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result.GetProperty("id").ToString()); - Console.WriteLine(result.GetProperty("createdDateTime").ToString()); - Console.WriteLine(result.GetProperty("sessionExpired").ToString()); + Console.WriteLine(result.GetProperty("sessionId").ToString()); + Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] @@ -389,132 +355,6 @@ public async Task Example_LivenessWithVerifySession_GetLivenessWithVerifySession Response response = await client.GetLivenessWithVerifySessionResultAsync("b12e033e-bda7-4b83-a211-e721c661f30e"); } - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_LivenessWithVerifySession_GetLivenessWithVerifySessions_GetLivenessWithVerifySessions() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = client.GetLivenessWithVerifySessions("00000000-0000-0000-0000-000000000000", 20, null); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_LivenessWithVerifySession_GetLivenessWithVerifySessions_GetLivenessWithVerifySessions_Async() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = await client.GetLivenessWithVerifySessionsAsync("00000000-0000-0000-0000-000000000000", 20, null); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_LivenessWithVerifySession_GetLivenessWithVerifySessions_GetLivenessWithVerifySessions_Convenience() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response> response = client.GetLivenessWithVerifySessions(); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_LivenessWithVerifySession_GetLivenessWithVerifySessions_GetLivenessWithVerifySessions_Convenience_Async() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response> response = await client.GetLivenessWithVerifySessionsAsync(); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_FaceSessionClient_GetLivenessWithVerifySessionAuditEntries_GetLivenessWithVerifySessionAuditEntries() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = client.GetLivenessWithVerifySessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("sessionId").ToString()); - Console.WriteLine(result[0].GetProperty("requestId").ToString()); - Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); - Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); - Console.WriteLine(result[0].GetProperty("digest").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_FaceSessionClient_GetLivenessWithVerifySessionAuditEntries_GetLivenessWithVerifySessionAuditEntries_Async() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = await client.GetLivenessWithVerifySessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("sessionId").ToString()); - Console.WriteLine(result[0].GetProperty("requestId").ToString()); - Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); - Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); - Console.WriteLine(result[0].GetProperty("digest").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_FaceSessionClient_GetLivenessWithVerifySessionAuditEntries_GetLivenessWithVerifySessionAuditEntries_Convenience() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response> response = client.GetLivenessWithVerifySessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e"); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_FaceSessionClient_GetLivenessWithVerifySessionAuditEntries_GetLivenessWithVerifySessionAuditEntries_Convenience_Async() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response> response = await client.GetLivenessWithVerifySessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e"); - } - [Test] [Ignore("Only validating compilation of examples")] public void Example_FaceSessionClient_DetectFromSessionImage_DetectFromSessionImageId() diff --git a/sdk/face/Azure.AI.Vision.Face/tsp-location.yaml b/sdk/face/Azure.AI.Vision.Face/tsp-location.yaml index 04929cc061e0..3fb171e5c952 100644 --- a/sdk/face/Azure.AI.Vision.Face/tsp-location.yaml +++ b/sdk/face/Azure.AI.Vision.Face/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/ai/Face -commit: 3eeb18be88d0d6ca7b0a365df1e4122c01c9e84b +commit: e86f9dade22bbb783fde4ee2879b0bf1cc3f9ec0 repo: Azure/azure-rest-api-specs - +additionalDirectories: diff --git a/sdk/resourcemanager/ci.mgmt.yml b/sdk/resourcemanager/ci.mgmt.yml index 5516ff2d5e57..ed50ff483e1b 100644 --- a/sdk/resourcemanager/ci.mgmt.yml +++ b/sdk/resourcemanager/ci.mgmt.yml @@ -54,6 +54,7 @@ trigger: - sdk/containerorchestratorruntime/Azure.ResourceManager.ContainerOrchestratorRuntime - sdk/containerregistry/Azure.ResourceManager.ContainerRegistry - sdk/containerservice/Azure.ResourceManager.ContainerService + - sdk/contoso/Azure.ResourceManager.Contoso - sdk/cosmosdb/Azure.ResourceManager.CosmosDB - sdk/cosmosdbforpostgresql/Azure.ResourceManager.CosmosDBForPostgreSql - sdk/costmanagement/Azure.ResourceManager.CostManagement @@ -268,6 +269,7 @@ pr: - sdk/containerorchestratorruntime/Azure.ResourceManager.ContainerOrchestratorRuntime - sdk/containerregistry/Azure.ResourceManager.ContainerRegistry - sdk/containerservice/Azure.ResourceManager.ContainerService + - sdk/contoso/Azure.ResourceManager.Contoso - sdk/cosmosdb/Azure.ResourceManager.CosmosDB - sdk/cosmosdbforpostgresql/Azure.ResourceManager.CosmosDBForPostgreSql - sdk/costmanagement/Azure.ResourceManager.CostManagement diff --git a/sdk/storage/ci.yml b/sdk/storage/ci.yml index 2ca0501b60bd..4e749e6b85b1 100644 --- a/sdk/storage/ci.yml +++ b/sdk/storage/ci.yml @@ -12,6 +12,8 @@ trigger: - sdk/storage/Azure.Storage.DataMovement/ - sdk/storage/Azure.Storage.DataMovement.Blobs/ - sdk/storage/Azure.Storage.DataMovement.Files/ + exclude: + - sdk/storage/Azure.ResourceManager.Storage/ - sdk/storage/Azure.Storage.DataMovement.Blobs.Files.Shares/ exclude: - sdk/storage/Azure.ResourceManager.Storage/