diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/Azure.ResourceManager.CloudHealth.sln b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/Azure.ResourceManager.CloudHealth.sln new file mode 100644 index 000000000000..1ac6623d8de4 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/Azure.ResourceManager.CloudHealth.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.CloudHealth.Samples", "samples\Azure.ResourceManager.CloudHealth.Samples.csproj", "{7A2DFF15-5746-49F4-BD0F-C6C35337088A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.ResourceManager.CloudHealth", "src\Azure.ResourceManager.CloudHealth.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.ResourceManager.CloudHealth.Tests", "tests\Azure.ResourceManager.CloudHealth.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/cloudhealth/Azure.ResourceManager.CloudHealth/CHANGELOG.md b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/CHANGELOG.md new file mode 100644 index 000000000000..8b33f0fedccc --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/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/cloudhealth/Azure.ResourceManager.CloudHealth/Directory.Build.props b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/Directory.Build.props new file mode 100644 index 000000000000..63bd836ad44b --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/Directory.Build.props @@ -0,0 +1,6 @@ + + + + diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/README.md b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/README.md new file mode 100644 index 000000000000..d1b46f05140a --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/README.md @@ -0,0 +1,80 @@ +# Microsoft Azure CloudHealth 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 CloudHealth management library for .NET with [NuGet](https://www.nuget.org/): + +```dotnetcli +dotnet add package Azure.ResourceManager.CloudHealth --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/cloudhealth/Azure.ResourceManager.CloudHealth/assets.json b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/assets.json new file mode 100644 index 000000000000..6dd722f0b712 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/assets.json @@ -0,0 +1,7 @@ + +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "net", + "TagPrefix": "net/cloudhealth/Azure.ResourceManager.CloudHealth", + "Tag": "" +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Azure.ResourceManager.CloudHealth.Samples.csproj b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Azure.ResourceManager.CloudHealth.Samples.csproj new file mode 100644 index 000000000000..e2724e938c57 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Azure.ResourceManager.CloudHealth.Samples.csproj @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_AuthenticationSettingCollection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_AuthenticationSettingCollection.cs new file mode 100644 index 000000000000..0a63a7cb2c25 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_AuthenticationSettingCollection.cs @@ -0,0 +1,203 @@ +// 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.CloudHealth.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.CloudHealth.Samples +{ + public partial class Sample_AuthenticationSettingCollection + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task CreateOrUpdate_AuthenticationSettingsCreateOrUpdate() + { + // Generated from example definition: 2023-10-01-preview/AuthenticationSettings_CreateOrUpdate.json + // this example is just showing the usage of "AuthenticationSetting_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "myResourceGroup"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this AuthenticationSettingResource + AuthenticationSettingCollection collection = healthModel.GetAuthenticationSettings(); + + // invoke the operation + string authenticationSettingName = "myAuthSetting"; + AuthenticationSettingData data = new AuthenticationSettingData + { + Properties = new ManagedIdentityAuthenticationSettingProperties("SystemAssigned") + { + DisplayName = "myDisplayName", + }, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, authenticationSettingName, data); + AuthenticationSettingResource 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 + AuthenticationSettingData 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_AuthenticationSettingsGet() + { + // Generated from example definition: 2023-10-01-preview/AuthenticationSettings_Get.json + // this example is just showing the usage of "AuthenticationSetting_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "my-resource-group"; + string healthModelName = "my-health-model"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this AuthenticationSettingResource + AuthenticationSettingCollection collection = healthModel.GetAuthenticationSettings(); + + // invoke the operation + string authenticationSettingName = "my-auth-setting"; + AuthenticationSettingResource result = await collection.GetAsync(authenticationSettingName); + + // 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 + AuthenticationSettingData 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_AuthenticationSettingsListByHealthModel() + { + // Generated from example definition: 2023-10-01-preview/AuthenticationSettings_ListByHealthModel.json + // this example is just showing the usage of "AuthenticationSetting_ListByHealthModel" 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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "my-resource-group"; + string healthModelName = "my-health-model"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this AuthenticationSettingResource + AuthenticationSettingCollection collection = healthModel.GetAuthenticationSettings(); + + // invoke the operation and iterate over the result + await foreach (AuthenticationSettingResource 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 + AuthenticationSettingData 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_AuthenticationSettingsGet() + { + // Generated from example definition: 2023-10-01-preview/AuthenticationSettings_Get.json + // this example is just showing the usage of "AuthenticationSetting_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "my-resource-group"; + string healthModelName = "my-health-model"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this AuthenticationSettingResource + AuthenticationSettingCollection collection = healthModel.GetAuthenticationSettings(); + + // invoke the operation + string authenticationSettingName = "my-auth-setting"; + bool result = await collection.ExistsAsync(authenticationSettingName); + + Console.WriteLine($"Succeeded: {result}"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetIfExists_AuthenticationSettingsGet() + { + // Generated from example definition: 2023-10-01-preview/AuthenticationSettings_Get.json + // this example is just showing the usage of "AuthenticationSetting_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "my-resource-group"; + string healthModelName = "my-health-model"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this AuthenticationSettingResource + AuthenticationSettingCollection collection = healthModel.GetAuthenticationSettings(); + + // invoke the operation + string authenticationSettingName = "my-auth-setting"; + NullableResponse response = await collection.GetIfExistsAsync(authenticationSettingName); + AuthenticationSettingResource 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 + AuthenticationSettingData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_AuthenticationSettingResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_AuthenticationSettingResource.cs new file mode 100644 index 000000000000..a1ebc193e539 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_AuthenticationSettingResource.cs @@ -0,0 +1,116 @@ +// 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.CloudHealth.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.CloudHealth.Samples +{ + public partial class Sample_AuthenticationSettingResource + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Get_AuthenticationSettingsGet() + { + // Generated from example definition: 2023-10-01-preview/AuthenticationSettings_Get.json + // this example is just showing the usage of "AuthenticationSetting_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 AuthenticationSettingResource created on azure + // for more information of creating AuthenticationSettingResource, please refer to the document of AuthenticationSettingResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "my-resource-group"; + string healthModelName = "my-health-model"; + string authenticationSettingName = "my-auth-setting"; + ResourceIdentifier authenticationSettingResourceId = AuthenticationSettingResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, authenticationSettingName); + AuthenticationSettingResource authenticationSetting = client.GetAuthenticationSettingResource(authenticationSettingResourceId); + + // invoke the operation + AuthenticationSettingResource result = await authenticationSetting.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 + AuthenticationSettingData 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_AuthenticationSettingsDelete() + { + // Generated from example definition: 2023-10-01-preview/AuthenticationSettings_Delete.json + // this example is just showing the usage of "AuthenticationSetting_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 AuthenticationSettingResource created on azure + // for more information of creating AuthenticationSettingResource, please refer to the document of AuthenticationSettingResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "my-resource-group"; + string healthModelName = "my-health-model"; + string authenticationSettingName = "my-auth-setting"; + ResourceIdentifier authenticationSettingResourceId = AuthenticationSettingResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, authenticationSettingName); + AuthenticationSettingResource authenticationSetting = client.GetAuthenticationSettingResource(authenticationSettingResourceId); + + // invoke the operation + await authenticationSetting.DeleteAsync(WaitUntil.Completed); + + Console.WriteLine("Succeeded"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Update_AuthenticationSettingsCreateOrUpdate() + { + // Generated from example definition: 2023-10-01-preview/AuthenticationSettings_CreateOrUpdate.json + // this example is just showing the usage of "AuthenticationSetting_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 AuthenticationSettingResource created on azure + // for more information of creating AuthenticationSettingResource, please refer to the document of AuthenticationSettingResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "myResourceGroup"; + string healthModelName = "myHealthModel"; + string authenticationSettingName = "myAuthSetting"; + ResourceIdentifier authenticationSettingResourceId = AuthenticationSettingResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, authenticationSettingName); + AuthenticationSettingResource authenticationSetting = client.GetAuthenticationSettingResource(authenticationSettingResourceId); + + // invoke the operation + AuthenticationSettingData data = new AuthenticationSettingData + { + Properties = new ManagedIdentityAuthenticationSettingProperties("SystemAssigned") + { + DisplayName = "myDisplayName", + }, + }; + ArmOperation lro = await authenticationSetting.UpdateAsync(WaitUntil.Completed, data); + AuthenticationSettingResource 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 + AuthenticationSettingData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_DiscoveryRuleCollection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_DiscoveryRuleCollection.cs new file mode 100644 index 000000000000..50503f13d0c7 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_DiscoveryRuleCollection.cs @@ -0,0 +1,203 @@ +// 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.CloudHealth.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.CloudHealth.Samples +{ + public partial class Sample_DiscoveryRuleCollection + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task CreateOrUpdate_DiscoveryRulesCreateOrUpdate() + { + // Generated from example definition: 2023-10-01-preview/DiscoveryRules_CreateOrUpdate.json + // this example is just showing the usage of "DiscoveryRule_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "myResourceGroup"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this DiscoveryRuleResource + DiscoveryRuleCollection collection = healthModel.GetDiscoveryRules(); + + // invoke the operation + string discoveryRuleName = "myDiscoveryRule"; + DiscoveryRuleData data = new DiscoveryRuleData + { + Properties = new DiscoveryRuleProperties("resources | where subscriptionId == '7ddfffd7-9b32-40df-1234-828cbd55d6f4' | where resourceGroup == 'my-rg'", "authSetting1", DiscoveryRuleRelationshipDiscoveryBehavior.Enabled, DiscoveryRuleRecommendedSignalsBehavior.Enabled, null) + { + DisplayName = "myDisplayName", + }, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, discoveryRuleName, data); + DiscoveryRuleResource 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 + DiscoveryRuleData 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_DiscoveryRulesGet() + { + // Generated from example definition: 2023-10-01-preview/DiscoveryRules_Get.json + // this example is just showing the usage of "DiscoveryRule_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "myResourceGroup"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this DiscoveryRuleResource + DiscoveryRuleCollection collection = healthModel.GetDiscoveryRules(); + + // invoke the operation + string discoveryRuleName = "myDiscoveryRule"; + DiscoveryRuleResource result = await collection.GetAsync(discoveryRuleName); + + // 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 + DiscoveryRuleData 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_DiscoveryRulesListByHealthModel() + { + // Generated from example definition: 2023-10-01-preview/DiscoveryRules_ListByHealthModel.json + // this example is just showing the usage of "DiscoveryRule_ListByHealthModel" 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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "my-resource-group"; + string healthModelName = "my-health-model"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this DiscoveryRuleResource + DiscoveryRuleCollection collection = healthModel.GetDiscoveryRules(); + + // invoke the operation and iterate over the result + await foreach (DiscoveryRuleResource 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 + DiscoveryRuleData 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_DiscoveryRulesGet() + { + // Generated from example definition: 2023-10-01-preview/DiscoveryRules_Get.json + // this example is just showing the usage of "DiscoveryRule_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "myResourceGroup"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this DiscoveryRuleResource + DiscoveryRuleCollection collection = healthModel.GetDiscoveryRules(); + + // invoke the operation + string discoveryRuleName = "myDiscoveryRule"; + bool result = await collection.ExistsAsync(discoveryRuleName); + + Console.WriteLine($"Succeeded: {result}"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetIfExists_DiscoveryRulesGet() + { + // Generated from example definition: 2023-10-01-preview/DiscoveryRules_Get.json + // this example is just showing the usage of "DiscoveryRule_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "myResourceGroup"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this DiscoveryRuleResource + DiscoveryRuleCollection collection = healthModel.GetDiscoveryRules(); + + // invoke the operation + string discoveryRuleName = "myDiscoveryRule"; + NullableResponse response = await collection.GetIfExistsAsync(discoveryRuleName); + DiscoveryRuleResource 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 + DiscoveryRuleData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_DiscoveryRuleResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_DiscoveryRuleResource.cs new file mode 100644 index 000000000000..c5b82d3024f7 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_DiscoveryRuleResource.cs @@ -0,0 +1,116 @@ +// 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.CloudHealth.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.CloudHealth.Samples +{ + public partial class Sample_DiscoveryRuleResource + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Get_DiscoveryRulesGet() + { + // Generated from example definition: 2023-10-01-preview/DiscoveryRules_Get.json + // this example is just showing the usage of "DiscoveryRule_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 DiscoveryRuleResource created on azure + // for more information of creating DiscoveryRuleResource, please refer to the document of DiscoveryRuleResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "myResourceGroup"; + string healthModelName = "myHealthModel"; + string discoveryRuleName = "myDiscoveryRule"; + ResourceIdentifier discoveryRuleResourceId = DiscoveryRuleResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, discoveryRuleName); + DiscoveryRuleResource discoveryRule = client.GetDiscoveryRuleResource(discoveryRuleResourceId); + + // invoke the operation + DiscoveryRuleResource result = await discoveryRule.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 + DiscoveryRuleData 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_DiscoveryRulesDelete() + { + // Generated from example definition: 2023-10-01-preview/DiscoveryRules_Delete.json + // this example is just showing the usage of "DiscoveryRule_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 DiscoveryRuleResource created on azure + // for more information of creating DiscoveryRuleResource, please refer to the document of DiscoveryRuleResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "my-resource-group"; + string healthModelName = "my-health-model"; + string discoveryRuleName = "my-discovery-rule"; + ResourceIdentifier discoveryRuleResourceId = DiscoveryRuleResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, discoveryRuleName); + DiscoveryRuleResource discoveryRule = client.GetDiscoveryRuleResource(discoveryRuleResourceId); + + // invoke the operation + await discoveryRule.DeleteAsync(WaitUntil.Completed); + + Console.WriteLine("Succeeded"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Update_DiscoveryRulesCreateOrUpdate() + { + // Generated from example definition: 2023-10-01-preview/DiscoveryRules_CreateOrUpdate.json + // this example is just showing the usage of "DiscoveryRule_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 DiscoveryRuleResource created on azure + // for more information of creating DiscoveryRuleResource, please refer to the document of DiscoveryRuleResource + string subscriptionId = "00000000-0000-0000-0000-000000000000"; + string resourceGroupName = "myResourceGroup"; + string healthModelName = "myHealthModel"; + string discoveryRuleName = "myDiscoveryRule"; + ResourceIdentifier discoveryRuleResourceId = DiscoveryRuleResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, discoveryRuleName); + DiscoveryRuleResource discoveryRule = client.GetDiscoveryRuleResource(discoveryRuleResourceId); + + // invoke the operation + DiscoveryRuleData data = new DiscoveryRuleData + { + Properties = new DiscoveryRuleProperties("resources | where subscriptionId == '7ddfffd7-9b32-40df-1234-828cbd55d6f4' | where resourceGroup == 'my-rg'", "authSetting1", DiscoveryRuleRelationshipDiscoveryBehavior.Enabled, DiscoveryRuleRecommendedSignalsBehavior.Enabled, null) + { + DisplayName = "myDisplayName", + }, + }; + ArmOperation lro = await discoveryRule.UpdateAsync(WaitUntil.Completed, data); + DiscoveryRuleResource 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 + DiscoveryRuleData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_EntityCollection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_EntityCollection.cs new file mode 100644 index 000000000000..1de5f1aec47a --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_EntityCollection.cs @@ -0,0 +1,243 @@ +// 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.CloudHealth.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.CloudHealth.Samples +{ + public partial class Sample_EntityCollection + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task CreateOrUpdate_EntitiesCreateOrUpdate() + { + // Generated from example definition: 2023-10-01-preview/Entities_CreateOrUpdate.json + // this example is just showing the usage of "Entity_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this EntityResource + EntityCollection collection = healthModel.GetEntities(); + + // invoke the operation + string entityName = "uszrxbdkxesdrxhmagmzywebgbjj"; + EntityData data = new EntityData + { + Properties = new EntityProperties + { + DisplayName = "My entity", + CanvasPosition = new EntityCoordinates(14F, 13F), + Icon = new IconDefinition("Custom") + { + CustomData = "rcitntvapruccrhtxmkqjphbxunkz", + }, + HealthObjective = 62F, + Impact = EntityImpact.Standard, + Labels = +{ +["key1376"] = "ixfvzsfnpvkkbrce" +}, + Signals = new SignalGroup + { + AzureResource = new AzureResourceSignalGroup("B3P1X3e-FZtZ-4Ak-2VLHGQ-4m4-05DE-XNW5zW3P-46XY-DC3SSX", new ResourceIdentifier("/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1")) + { + SignalAssignments = { new SignalAssignment(new string[] { "sigdef1" }) }, + }, + AzureLogAnalytics = new LogAnalyticsSignalGroup("B3P1X3e-FZtZ-4Ak-2VLHGQ-4m4-05DE-XNW5zW3P-46XY-DC3SSX", new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.OperationalInsights/workspaces/myworkspace")) + { + SignalAssignments = { new SignalAssignment(new string[] { "B3P1X3e-FZtZ-4Ak-2VLHGQ-4m4-05DE-XNW5zW3P-46XY-DC3SSX" }) }, + }, + AzureMonitorWorkspace = new AzureMonitorWorkspaceSignalGroup("B3P1X3e-FZtZ-4Ak-2VLHGQ-4m4-05DE-XNW5zW3P-46XY-DC3SSX", new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.OperationalInsights/workspaces/myworkspace")) + { + SignalAssignments = { new SignalAssignment(new string[] { "sigdef2" }), new SignalAssignment(new string[] { "sigdef3" }) }, + }, + Dependencies = new DependenciesSignalGroup(DependenciesAggregationType.WorstOf), + }, + Alerts = new EntityAlerts + { + Unhealthy = new AlertConfiguration(AlertSeverity.Sev1) + { + Description = "Alert description", + ActionGroupIds = { new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.Insights/actionGroups/myactiongroup") }, + }, + Degraded = new AlertConfiguration(AlertSeverity.Sev4) + { + Description = "Alert description", + ActionGroupIds = { new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.Insights/actionGroups/myactiongroup") }, + }, + }, + }, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, entityName, data); + EntityResource 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 + EntityData 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_EntitiesGet() + { + // Generated from example definition: 2023-10-01-preview/Entities_Get.json + // this example is just showing the usage of "Entity_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this EntityResource + EntityCollection collection = healthModel.GetEntities(); + + // invoke the operation + string entityName = "entity1"; + EntityResource result = await collection.GetAsync(entityName); + + // 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 + EntityData 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_EntitiesListByHealthModel() + { + // Generated from example definition: 2023-10-01-preview/Entities_ListByHealthModel.json + // this example is just showing the usage of "Entity_ListByHealthModel" 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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "gPWT6GP85xRV248L7LhNRTD--2Yc73wu-5Qk-0tS"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this EntityResource + EntityCollection collection = healthModel.GetEntities(); + + // invoke the operation and iterate over the result + await foreach (EntityResource 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 + EntityData 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_EntitiesGet() + { + // Generated from example definition: 2023-10-01-preview/Entities_Get.json + // this example is just showing the usage of "Entity_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this EntityResource + EntityCollection collection = healthModel.GetEntities(); + + // invoke the operation + string entityName = "entity1"; + bool result = await collection.ExistsAsync(entityName); + + Console.WriteLine($"Succeeded: {result}"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetIfExists_EntitiesGet() + { + // Generated from example definition: 2023-10-01-preview/Entities_Get.json + // this example is just showing the usage of "Entity_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this EntityResource + EntityCollection collection = healthModel.GetEntities(); + + // invoke the operation + string entityName = "entity1"; + NullableResponse response = await collection.GetIfExistsAsync(entityName); + EntityResource 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 + EntityData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_EntityResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_EntityResource.cs new file mode 100644 index 000000000000..0c2e7ccda985 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_EntityResource.cs @@ -0,0 +1,156 @@ +// 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.CloudHealth.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.CloudHealth.Samples +{ + public partial class Sample_EntityResource + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Get_EntitiesGet() + { + // Generated from example definition: 2023-10-01-preview/Entities_Get.json + // this example is just showing the usage of "Entity_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 EntityResource created on azure + // for more information of creating EntityResource, please refer to the document of EntityResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + string entityName = "entity1"; + ResourceIdentifier entityResourceId = EntityResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, entityName); + EntityResource entity = client.GetEntityResource(entityResourceId); + + // invoke the operation + EntityResource result = await entity.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 + EntityData 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_EntitiesDelete() + { + // Generated from example definition: 2023-10-01-preview/Entities_Delete.json + // this example is just showing the usage of "Entity_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 EntityResource created on azure + // for more information of creating EntityResource, please refer to the document of EntityResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "model1"; + string entityName = "U4VTRFlUkm9kR6H23-c-6U-XHq7n"; + ResourceIdentifier entityResourceId = EntityResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, entityName); + EntityResource entity = client.GetEntityResource(entityResourceId); + + // invoke the operation + await entity.DeleteAsync(WaitUntil.Completed); + + Console.WriteLine("Succeeded"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Update_EntitiesCreateOrUpdate() + { + // Generated from example definition: 2023-10-01-preview/Entities_CreateOrUpdate.json + // this example is just showing the usage of "Entity_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 EntityResource created on azure + // for more information of creating EntityResource, please refer to the document of EntityResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + string entityName = "uszrxbdkxesdrxhmagmzywebgbjj"; + ResourceIdentifier entityResourceId = EntityResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, entityName); + EntityResource entity = client.GetEntityResource(entityResourceId); + + // invoke the operation + EntityData data = new EntityData + { + Properties = new EntityProperties + { + DisplayName = "My entity", + CanvasPosition = new EntityCoordinates(14F, 13F), + Icon = new IconDefinition("Custom") + { + CustomData = "rcitntvapruccrhtxmkqjphbxunkz", + }, + HealthObjective = 62F, + Impact = EntityImpact.Standard, + Labels = +{ +["key1376"] = "ixfvzsfnpvkkbrce" +}, + Signals = new SignalGroup + { + AzureResource = new AzureResourceSignalGroup("B3P1X3e-FZtZ-4Ak-2VLHGQ-4m4-05DE-XNW5zW3P-46XY-DC3SSX", new ResourceIdentifier("/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1")) + { + SignalAssignments = { new SignalAssignment(new string[] { "sigdef1" }) }, + }, + AzureLogAnalytics = new LogAnalyticsSignalGroup("B3P1X3e-FZtZ-4Ak-2VLHGQ-4m4-05DE-XNW5zW3P-46XY-DC3SSX", new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.OperationalInsights/workspaces/myworkspace")) + { + SignalAssignments = { new SignalAssignment(new string[] { "B3P1X3e-FZtZ-4Ak-2VLHGQ-4m4-05DE-XNW5zW3P-46XY-DC3SSX" }) }, + }, + AzureMonitorWorkspace = new AzureMonitorWorkspaceSignalGroup("B3P1X3e-FZtZ-4Ak-2VLHGQ-4m4-05DE-XNW5zW3P-46XY-DC3SSX", new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.OperationalInsights/workspaces/myworkspace")) + { + SignalAssignments = { new SignalAssignment(new string[] { "sigdef2" }), new SignalAssignment(new string[] { "sigdef3" }) }, + }, + Dependencies = new DependenciesSignalGroup(DependenciesAggregationType.WorstOf), + }, + Alerts = new EntityAlerts + { + Unhealthy = new AlertConfiguration(AlertSeverity.Sev1) + { + Description = "Alert description", + ActionGroupIds = { new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.Insights/actionGroups/myactiongroup") }, + }, + Degraded = new AlertConfiguration(AlertSeverity.Sev4) + { + Description = "Alert description", + ActionGroupIds = { new ResourceIdentifier("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.Insights/actionGroups/myactiongroup") }, + }, + }, + }, + }; + ArmOperation lro = await entity.UpdateAsync(WaitUntil.Completed, data); + EntityResource 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 + EntityData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_HealthModelCollection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_HealthModelCollection.cs new file mode 100644 index 000000000000..dba037191d3b --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_HealthModelCollection.cs @@ -0,0 +1,214 @@ +// 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.CloudHealth.Models; +using Azure.ResourceManager.Models; +using Azure.ResourceManager.Resources; +using NUnit.Framework; + +namespace Azure.ResourceManager.CloudHealth.Samples +{ + public partial class Sample_HealthModelCollection + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task CreateOrUpdate_HealthModelsCreate() + { + // Generated from example definition: 2023-10-01-preview/HealthModels_Create.json + // this example is just showing the usage of "HealthModel_Create" 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 = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this HealthModelResource + HealthModelCollection collection = resourceGroupResource.GetHealthModels(); + + // invoke the operation + string healthModelName = "model1"; + HealthModelData data = new HealthModelData(new AzureLocation("eastus2")) + { + Properties = new HealthModelProperties + { + Discovery = new ModelDiscoverySettings("/providers/Microsoft.Management/serviceGroups/myServiceGroup", DiscoveryRuleRecommendedSignalsBehavior.Enabled) + { + Identity = "SystemAssigned", + }, + }, + Identity = new ManagedServiceIdentity("SystemAssigned, UserAssigned") + { + UserAssignedIdentities = +{ +[new ResourceIdentifier("/subscriptions/4980D7D5-4E07-47AD-AD34-E76C6BC9F061/resourceGroups/rgopenapi/providers/Microsoft.ManagedIdentity/userAssignedIdentities/ua1")] = new UserAssignedIdentity() +}, + }, + Tags = +{ +["key2961"] = "hbljozzkqrpcthsjtfkyozpwyx" +}, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, healthModelName, data); + HealthModelResource 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 + HealthModelData 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_HealthModelsGet() + { + // Generated from example definition: 2023-10-01-preview/HealthModels_Get.json + // this example is just showing the usage of "HealthModel_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 = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this HealthModelResource + HealthModelCollection collection = resourceGroupResource.GetHealthModels(); + + // invoke the operation + string healthModelName = "myHealthModel"; + HealthModelResource result = await collection.GetAsync(healthModelName); + + // 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 + HealthModelData 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_HealthModelsListByResourceGroup() + { + // Generated from example definition: 2023-10-01-preview/HealthModels_ListByResourceGroup.json + // this example is just showing the usage of "HealthModel_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 = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this HealthModelResource + HealthModelCollection collection = resourceGroupResource.GetHealthModels(); + + // invoke the operation and iterate over the result + await foreach (HealthModelResource 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 + HealthModelData 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_HealthModelsGet() + { + // Generated from example definition: 2023-10-01-preview/HealthModels_Get.json + // this example is just showing the usage of "HealthModel_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 = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this HealthModelResource + HealthModelCollection collection = resourceGroupResource.GetHealthModels(); + + // invoke the operation + string healthModelName = "myHealthModel"; + bool result = await collection.ExistsAsync(healthModelName); + + Console.WriteLine($"Succeeded: {result}"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetIfExists_HealthModelsGet() + { + // Generated from example definition: 2023-10-01-preview/HealthModels_Get.json + // this example is just showing the usage of "HealthModel_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 = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + ResourceIdentifier resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName); + ResourceGroupResource resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId); + + // get the collection of this HealthModelResource + HealthModelCollection collection = resourceGroupResource.GetHealthModels(); + + // invoke the operation + string healthModelName = "myHealthModel"; + NullableResponse response = await collection.GetIfExistsAsync(healthModelName); + HealthModelResource 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 + HealthModelData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_HealthModelResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_HealthModelResource.cs new file mode 100644 index 000000000000..df600b979c88 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_HealthModelResource.cs @@ -0,0 +1,121 @@ +// 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.CloudHealth.Models; +using Azure.ResourceManager.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.CloudHealth.Samples +{ + public partial class Sample_HealthModelResource + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Get_HealthModelsGet() + { + // Generated from example definition: 2023-10-01-preview/HealthModels_Get.json + // this example is just showing the usage of "HealthModel_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // invoke the operation + HealthModelResource result = await healthModel.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 + HealthModelData 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_HealthModelsDelete() + { + // Generated from example definition: 2023-10-01-preview/HealthModels_Delete.json + // this example is just showing the usage of "HealthModel_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "model1"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // invoke the operation + await healthModel.DeleteAsync(WaitUntil.Completed); + + Console.WriteLine("Succeeded"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Update_HealthModelsUpdate() + { + // Generated from example definition: 2023-10-01-preview/HealthModels_Update.json + // this example is just showing the usage of "HealthModel_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "model1"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // invoke the operation + HealthModelPatch patch = new HealthModelPatch + { + Identity = new ManagedServiceIdentity("SystemAssigned, UserAssigned") + { + UserAssignedIdentities = +{ +[new ResourceIdentifier("/subscriptions/4980D7D5-4E07-47AD-AD34-E76C6BC9F061/resourceGroups/rgopenapi/providers/Microsoft.ManagedIdentity/userAssignedIdentities/ua1")] = new UserAssignedIdentity() +}, + }, + Tags = +{ +["key21"] = "menfkmseplchh" +}, + }; + ArmOperation lro = await healthModel.UpdateAsync(WaitUntil.Completed, patch); + HealthModelResource 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 + HealthModelData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_RelationshipCollection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_RelationshipCollection.cs new file mode 100644 index 000000000000..bcc03911390f --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_RelationshipCollection.cs @@ -0,0 +1,207 @@ +// 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.CloudHealth.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.CloudHealth.Samples +{ + public partial class Sample_RelationshipCollection + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task CreateOrUpdate_RelationshipsCreateOrUpdate() + { + // Generated from example definition: 2023-10-01-preview/Relationships_CreateOrUpdate.json + // this example is just showing the usage of "Relationship_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "model1"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this RelationshipResource + RelationshipCollection collection = healthModel.GetRelationships(); + + // invoke the operation + string relationshipName = "rel1"; + RelationshipData data = new RelationshipData + { + Properties = new RelationshipProperties("Entity1", "Entity2") + { + DisplayName = "My relationship", + Labels = +{ +["key9681"] = "ixfvzsfnpvkkbrce" +}, + }, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, relationshipName, data); + RelationshipResource 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 + RelationshipData 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_RelationshipsGet() + { + // Generated from example definition: 2023-10-01-preview/Relationships_Get.json + // this example is just showing the usage of "Relationship_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this RelationshipResource + RelationshipCollection collection = healthModel.GetRelationships(); + + // invoke the operation + string relationshipName = "Ue-21-F3M12V3w-13x18F8H-7HOk--kq6tP-HB"; + RelationshipResource result = await collection.GetAsync(relationshipName); + + // 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 + RelationshipData 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_RelationshipsListByHealthModel() + { + // Generated from example definition: 2023-10-01-preview/Relationships_ListByHealthModel.json + // this example is just showing the usage of "Relationship_ListByHealthModel" 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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "model1"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this RelationshipResource + RelationshipCollection collection = healthModel.GetRelationships(); + + // invoke the operation and iterate over the result + await foreach (RelationshipResource 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 + RelationshipData 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_RelationshipsGet() + { + // Generated from example definition: 2023-10-01-preview/Relationships_Get.json + // this example is just showing the usage of "Relationship_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this RelationshipResource + RelationshipCollection collection = healthModel.GetRelationships(); + + // invoke the operation + string relationshipName = "Ue-21-F3M12V3w-13x18F8H-7HOk--kq6tP-HB"; + bool result = await collection.ExistsAsync(relationshipName); + + Console.WriteLine($"Succeeded: {result}"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetIfExists_RelationshipsGet() + { + // Generated from example definition: 2023-10-01-preview/Relationships_Get.json + // this example is just showing the usage of "Relationship_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this RelationshipResource + RelationshipCollection collection = healthModel.GetRelationships(); + + // invoke the operation + string relationshipName = "Ue-21-F3M12V3w-13x18F8H-7HOk--kq6tP-HB"; + NullableResponse response = await collection.GetIfExistsAsync(relationshipName); + RelationshipResource 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 + RelationshipData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_RelationshipResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_RelationshipResource.cs new file mode 100644 index 000000000000..fafc3c58d1a5 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_RelationshipResource.cs @@ -0,0 +1,120 @@ +// 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.CloudHealth.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.CloudHealth.Samples +{ + public partial class Sample_RelationshipResource + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Get_RelationshipsGet() + { + // Generated from example definition: 2023-10-01-preview/Relationships_Get.json + // this example is just showing the usage of "Relationship_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 RelationshipResource created on azure + // for more information of creating RelationshipResource, please refer to the document of RelationshipResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + string relationshipName = "Ue-21-F3M12V3w-13x18F8H-7HOk--kq6tP-HB"; + ResourceIdentifier relationshipResourceId = RelationshipResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, relationshipName); + RelationshipResource relationship = client.GetRelationshipResource(relationshipResourceId); + + // invoke the operation + RelationshipResource result = await relationship.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 + RelationshipData 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_RelationshipsDelete() + { + // Generated from example definition: 2023-10-01-preview/Relationships_Delete.json + // this example is just showing the usage of "Relationship_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 RelationshipResource created on azure + // for more information of creating RelationshipResource, please refer to the document of RelationshipResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "model1"; + string relationshipName = "rel1"; + ResourceIdentifier relationshipResourceId = RelationshipResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, relationshipName); + RelationshipResource relationship = client.GetRelationshipResource(relationshipResourceId); + + // invoke the operation + await relationship.DeleteAsync(WaitUntil.Completed); + + Console.WriteLine("Succeeded"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Update_RelationshipsCreateOrUpdate() + { + // Generated from example definition: 2023-10-01-preview/Relationships_CreateOrUpdate.json + // this example is just showing the usage of "Relationship_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 RelationshipResource created on azure + // for more information of creating RelationshipResource, please refer to the document of RelationshipResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "model1"; + string relationshipName = "rel1"; + ResourceIdentifier relationshipResourceId = RelationshipResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, relationshipName); + RelationshipResource relationship = client.GetRelationshipResource(relationshipResourceId); + + // invoke the operation + RelationshipData data = new RelationshipData + { + Properties = new RelationshipProperties("Entity1", "Entity2") + { + DisplayName = "My relationship", + Labels = +{ +["key9681"] = "ixfvzsfnpvkkbrce" +}, + }, + }; + ArmOperation lro = await relationship.UpdateAsync(WaitUntil.Completed, data); + RelationshipResource 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 + RelationshipData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_SignalDefinitionCollection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_SignalDefinitionCollection.cs new file mode 100644 index 000000000000..4a7bc7106e23 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_SignalDefinitionCollection.cs @@ -0,0 +1,215 @@ +// 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.CloudHealth.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.CloudHealth.Samples +{ + public partial class Sample_SignalDefinitionCollection + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task CreateOrUpdate_SignalDefinitionsCreateOrUpdate() + { + // Generated from example definition: 2023-10-01-preview/SignalDefinitions_CreateOrUpdate.json + // this example is just showing the usage of "SignalDefinition_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this SignalDefinitionResource + SignalDefinitionCollection collection = healthModel.GetSignalDefinitions(); + + // invoke the operation + string signalDefinitionName = "sig1"; + SignalDefinitionData data = new SignalDefinitionData + { + Properties = new ResourceMetricSignalDefinitionProperties(new EvaluationRule + { + DegradedRule = new ThresholdRule(SignalOperator.LowerThan, "65"), + UnhealthyRule = new ThresholdRule(SignalOperator.LowerThan, "60"), + }, "microsoft.compute/virtualMachines", "cpuusage", "PT1M", MetricAggregationType.None) + { + Dimension = "nodename", + DimensionFilter = "node1", + DisplayName = "cpu usage", + RefreshInterval = RefreshInterval.PT1M, + Labels = +{ +["key4788"] = "ixfvzsfnpvkkbrce" +}, + DataUnit = "byte", + }, + }; + ArmOperation lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, signalDefinitionName, data); + SignalDefinitionResource 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 + SignalDefinitionData 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_SignalDefinitionsGet() + { + // Generated from example definition: 2023-10-01-preview/SignalDefinitions_Get.json + // this example is just showing the usage of "SignalDefinition_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this SignalDefinitionResource + SignalDefinitionCollection collection = healthModel.GetSignalDefinitions(); + + // invoke the operation + string signalDefinitionName = "sig1"; + SignalDefinitionResource result = await collection.GetAsync(signalDefinitionName); + + // 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 + SignalDefinitionData 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_SignalDefinitionsListByHealthModel() + { + // Generated from example definition: 2023-10-01-preview/SignalDefinitions_ListByHealthModel.json + // this example is just showing the usage of "SignalDefinition_ListByHealthModel" 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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this SignalDefinitionResource + SignalDefinitionCollection collection = healthModel.GetSignalDefinitions(); + + // invoke the operation and iterate over the result + await foreach (SignalDefinitionResource 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 + SignalDefinitionData 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_SignalDefinitionsGet() + { + // Generated from example definition: 2023-10-01-preview/SignalDefinitions_Get.json + // this example is just showing the usage of "SignalDefinition_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this SignalDefinitionResource + SignalDefinitionCollection collection = healthModel.GetSignalDefinitions(); + + // invoke the operation + string signalDefinitionName = "sig1"; + bool result = await collection.ExistsAsync(signalDefinitionName); + + Console.WriteLine($"Succeeded: {result}"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetIfExists_SignalDefinitionsGet() + { + // Generated from example definition: 2023-10-01-preview/SignalDefinitions_Get.json + // this example is just showing the usage of "SignalDefinition_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 HealthModelResource created on azure + // for more information of creating HealthModelResource, please refer to the document of HealthModelResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + ResourceIdentifier healthModelResourceId = HealthModelResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName); + HealthModelResource healthModel = client.GetHealthModelResource(healthModelResourceId); + + // get the collection of this SignalDefinitionResource + SignalDefinitionCollection collection = healthModel.GetSignalDefinitions(); + + // invoke the operation + string signalDefinitionName = "sig1"; + NullableResponse response = await collection.GetIfExistsAsync(signalDefinitionName); + SignalDefinitionResource 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 + SignalDefinitionData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_SignalDefinitionResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_SignalDefinitionResource.cs new file mode 100644 index 000000000000..75d04684cff5 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_SignalDefinitionResource.cs @@ -0,0 +1,128 @@ +// 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.CloudHealth.Models; +using NUnit.Framework; + +namespace Azure.ResourceManager.CloudHealth.Samples +{ + public partial class Sample_SignalDefinitionResource + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Get_SignalDefinitionsGet() + { + // Generated from example definition: 2023-10-01-preview/SignalDefinitions_Get.json + // this example is just showing the usage of "SignalDefinition_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 SignalDefinitionResource created on azure + // for more information of creating SignalDefinitionResource, please refer to the document of SignalDefinitionResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + string signalDefinitionName = "sig1"; + ResourceIdentifier signalDefinitionResourceId = SignalDefinitionResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, signalDefinitionName); + SignalDefinitionResource signalDefinition = client.GetSignalDefinitionResource(signalDefinitionResourceId); + + // invoke the operation + SignalDefinitionResource result = await signalDefinition.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 + SignalDefinitionData 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_SignalDefinitionsDelete() + { + // Generated from example definition: 2023-10-01-preview/SignalDefinitions_Delete.json + // this example is just showing the usage of "SignalDefinition_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 SignalDefinitionResource created on azure + // for more information of creating SignalDefinitionResource, please refer to the document of SignalDefinitionResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "model1"; + string signalDefinitionName = "sig"; + ResourceIdentifier signalDefinitionResourceId = SignalDefinitionResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, signalDefinitionName); + SignalDefinitionResource signalDefinition = client.GetSignalDefinitionResource(signalDefinitionResourceId); + + // invoke the operation + await signalDefinition.DeleteAsync(WaitUntil.Completed); + + Console.WriteLine("Succeeded"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Update_SignalDefinitionsCreateOrUpdate() + { + // Generated from example definition: 2023-10-01-preview/SignalDefinitions_CreateOrUpdate.json + // this example is just showing the usage of "SignalDefinition_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 SignalDefinitionResource created on azure + // for more information of creating SignalDefinitionResource, please refer to the document of SignalDefinitionResource + string subscriptionId = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + string resourceGroupName = "rgopenapi"; + string healthModelName = "myHealthModel"; + string signalDefinitionName = "sig1"; + ResourceIdentifier signalDefinitionResourceId = SignalDefinitionResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, healthModelName, signalDefinitionName); + SignalDefinitionResource signalDefinition = client.GetSignalDefinitionResource(signalDefinitionResourceId); + + // invoke the operation + SignalDefinitionData data = new SignalDefinitionData + { + Properties = new ResourceMetricSignalDefinitionProperties(new EvaluationRule + { + DegradedRule = new ThresholdRule(SignalOperator.LowerThan, "65"), + UnhealthyRule = new ThresholdRule(SignalOperator.LowerThan, "60"), + }, "microsoft.compute/virtualMachines", "cpuusage", "PT1M", MetricAggregationType.None) + { + Dimension = "nodename", + DimensionFilter = "node1", + DisplayName = "cpu usage", + RefreshInterval = RefreshInterval.PT1M, + Labels = +{ +["key4788"] = "ixfvzsfnpvkkbrce" +}, + DataUnit = "byte", + }, + }; + ArmOperation lro = await signalDefinition.UpdateAsync(WaitUntil.Completed, data); + SignalDefinitionResource 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 + SignalDefinitionData resourceData = result.Data; + // for demo we just print out the id + Console.WriteLine($"Succeeded on id: {resourceData.Id}"); + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_SubscriptionResourceExtensions.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/samples/Generated/Samples/Sample_SubscriptionResourceExtensions.cs new file mode 100644 index 000000000000..871a8154c275 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/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.CloudHealth.Samples +{ + public partial class Sample_SubscriptionResourceExtensions + { + [Test] + [Ignore("Only validating compilation of examples")] + public async Task GetHealthModels_HealthModelsListBySubscription() + { + // Generated from example definition: 2023-10-01-preview/HealthModels_ListBySubscription.json + // this example is just showing the usage of "HealthModel_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 = "4980D7D5-4E07-47AD-AD34-E76C6BC9F061"; + ResourceIdentifier subscriptionResourceId = SubscriptionResource.CreateResourceIdentifier(subscriptionId); + SubscriptionResource subscriptionResource = client.GetSubscriptionResource(subscriptionResourceId); + + // invoke the operation and iterate over the result + await foreach (HealthModelResource item in subscriptionResource.GetHealthModelsAsync()) + { + // 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 + HealthModelData 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Azure.ResourceManager.CloudHealth.csproj b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Azure.ResourceManager.CloudHealth.csproj new file mode 100644 index 000000000000..917693408c82 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Azure.ResourceManager.CloudHealth.csproj @@ -0,0 +1,8 @@ + + + Azure Resource Manager client SDK for Azure resource provider CloudHealth. + 1.0.0-beta.1 + azure;management;arm;resource manager;cloudhealth + Azure.ResourceManager.CloudHealth + + diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/ArmCloudHealthModelFactory.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/ArmCloudHealthModelFactory.cs new file mode 100644 index 000000000000..0a4b6f57d6cf --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/ArmCloudHealthModelFactory.cs @@ -0,0 +1,384 @@ +// 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.CloudHealth.Models +{ + /// Model factory for models. + public static partial class ArmCloudHealthModelFactory + { + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// The tags. + /// The location. + /// The resource-specific properties for this resource. + /// The managed service identities assigned to this resource. + /// A new instance for mocking. + public static HealthModelData HealthModelData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, IDictionary tags = null, AzureLocation location = default, HealthModelProperties properties = null, ManagedServiceIdentity identity = null) + { + tags ??= new Dictionary(); + + return new HealthModelData( + id, + name, + resourceType, + systemData, + tags, + location, + properties, + identity, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The data plane endpoint for interacting with health data. + /// The status of the last operation. + /// Configure to automatically discover entities from a given scope, such as a Service Group. The discovered entities will be linked to the root entity of the health model. + /// A new instance for mocking. + public static HealthModelProperties HealthModelProperties(string dataplaneEndpoint = null, HealthModelProvisioningState? provisioningState = null, ModelDiscoverySettings discovery = null) + { + return new HealthModelProperties(dataplaneEndpoint, provisioningState, discovery, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// + /// The resource-specific properties for this resource. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + /// A new instance for mocking. + public static SignalDefinitionData SignalDefinitionData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, SignalDefinitionProperties properties = null) + { + return new SignalDefinitionData( + id, + name, + resourceType, + systemData, + properties, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Kind of the signal definition. + /// Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + /// Optional set of labels (key-value pairs). + /// Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)). + /// Evaluation rules for the signal definition. + /// Date when the signal definition was (soft-)deleted. + /// A new instance for mocking. + public static SignalDefinitionProperties SignalDefinitionProperties(HealthModelProvisioningState? provisioningState = null, string displayName = null, string signalKind = null, RefreshInterval? refreshInterval = null, IDictionary labels = null, string dataUnit = null, EvaluationRule evaluationRules = null, DateTimeOffset? deletedOn = null) + { + labels ??= new Dictionary(); + + return new UnknownSignalDefinitionProperties( + provisioningState, + displayName, + signalKind == null ? default : new SignalKind(signalKind), + refreshInterval, + labels, + dataUnit, + evaluationRules, + deletedOn, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + /// Optional set of labels (key-value pairs). + /// Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)). + /// Evaluation rules for the signal definition. + /// Date when the signal definition was (soft-)deleted. + /// Metric namespace. + /// Name of the metric. + /// Time range of signal. ISO duration format like PT10M. + /// Type of aggregation to apply to the metric. + /// Optional: Dimension to split by. + /// Optional: Dimension filter to apply to the dimension. Must only be set if also Dimension is set. + /// A new instance for mocking. + public static ResourceMetricSignalDefinitionProperties ResourceMetricSignalDefinitionProperties(HealthModelProvisioningState? provisioningState = null, string displayName = null, RefreshInterval? refreshInterval = null, IDictionary labels = null, string dataUnit = null, EvaluationRule evaluationRules = null, DateTimeOffset? deletedOn = null, string metricNamespace = null, string metricName = null, string timeGrain = null, MetricAggregationType aggregationType = default, string dimension = null, string dimensionFilter = null) + { + labels ??= new Dictionary(); + + return new ResourceMetricSignalDefinitionProperties( + provisioningState, + displayName, + SignalKind.AzureResourceMetric, + refreshInterval, + labels, + dataUnit, + evaluationRules, + deletedOn, + serializedAdditionalRawData: null, + metricNamespace, + metricName, + timeGrain, + aggregationType, + dimension, + dimensionFilter); + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + /// Optional set of labels (key-value pairs). + /// Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)). + /// Evaluation rules for the signal definition. + /// Date when the signal definition was (soft-)deleted. + /// Query text in KQL syntax. + /// Time range of signal. ISO duration format like PT10M. If not specified, the KQL query must define a time range. + /// Name of the column in the result set to evaluate against the thresholds. Defaults to the first column in the result set if not specified. The column must be numeric. + /// A new instance for mocking. + public static LogAnalyticsQuerySignalDefinitionProperties LogAnalyticsQuerySignalDefinitionProperties(HealthModelProvisioningState? provisioningState = null, string displayName = null, RefreshInterval? refreshInterval = null, IDictionary labels = null, string dataUnit = null, EvaluationRule evaluationRules = null, DateTimeOffset? deletedOn = null, string queryText = null, string timeGrain = null, string valueColumnName = null) + { + labels ??= new Dictionary(); + + return new LogAnalyticsQuerySignalDefinitionProperties( + provisioningState, + displayName, + SignalKind.LogAnalyticsQuery, + refreshInterval, + labels, + dataUnit, + evaluationRules, + deletedOn, + serializedAdditionalRawData: null, + queryText, + timeGrain, + valueColumnName); + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + /// Optional set of labels (key-value pairs). + /// Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)). + /// Evaluation rules for the signal definition. + /// Date when the signal definition was (soft-)deleted. + /// Query text in PromQL syntax. + /// Time range of signal. ISO duration format like PT10M. + /// A new instance for mocking. + public static PrometheusMetricsSignalDefinitionProperties PrometheusMetricsSignalDefinitionProperties(HealthModelProvisioningState? provisioningState = null, string displayName = null, RefreshInterval? refreshInterval = null, IDictionary labels = null, string dataUnit = null, EvaluationRule evaluationRules = null, DateTimeOffset? deletedOn = null, string queryText = null, string timeGrain = null) + { + labels ??= new Dictionary(); + + return new PrometheusMetricsSignalDefinitionProperties( + provisioningState, + displayName, + SignalKind.PrometheusMetricsQuery, + refreshInterval, + labels, + dataUnit, + evaluationRules, + deletedOn, + serializedAdditionalRawData: null, + queryText, + timeGrain); + } + + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// + /// The resource-specific properties for this resource. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + /// A new instance for mocking. + public static AuthenticationSettingData AuthenticationSettingData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, AuthenticationSettingProperties properties = null) + { + return new AuthenticationSettingData( + id, + name, + resourceType, + systemData, + properties, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Kind of the authentication setting. + /// A new instance for mocking. + public static AuthenticationSettingProperties AuthenticationSettingProperties(HealthModelProvisioningState? provisioningState = null, string displayName = null, string authenticationKind = null) + { + return new UnknownAuthenticationSettingProperties(provisioningState, displayName, authenticationKind == null ? default : new AuthenticationKind(authenticationKind), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Name of the managed identity to use. Either 'SystemAssigned' or the resourceId of a user-assigned identity. + /// A new instance for mocking. + public static ManagedIdentityAuthenticationSettingProperties ManagedIdentityAuthenticationSettingProperties(HealthModelProvisioningState? provisioningState = null, string displayName = null, string managedIdentityName = null) + { + return new ManagedIdentityAuthenticationSettingProperties(provisioningState, displayName, AuthenticationKind.ManagedIdentity, serializedAdditionalRawData: null, managedIdentityName); + } + + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// The resource-specific properties for this resource. + /// A new instance for mocking. + public static EntityData EntityData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, EntityProperties properties = null) + { + return new EntityData( + id, + name, + resourceType, + systemData, + properties, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Entity kind. + /// Positioning of the entity on the model canvas. + /// Visual icon definition. If not set, a default icon is used. + /// Health objective as a percentage of time the entity should be healthy. + /// Impact of the entity in health state propagation. + /// Optional set of labels (key-value pairs). + /// Signal groups which are assigned to this entity. + /// Discovered by which discovery rule. If set, the entity cannot be deleted manually. + /// Date when the entity was (soft-)deleted. + /// Health state of this entity. + /// Alert configuration for this entity. + /// A new instance for mocking. + public static EntityProperties EntityProperties(HealthModelProvisioningState? provisioningState = null, string displayName = null, string kind = null, EntityCoordinates canvasPosition = null, IconDefinition icon = null, float? healthObjective = null, EntityImpact? impact = null, IDictionary labels = null, SignalGroup signals = null, string discoveredBy = null, DateTimeOffset? deletedOn = null, HealthState? healthState = null, EntityAlerts alerts = null) + { + labels ??= new Dictionary(); + + return new EntityProperties( + provisioningState, + displayName, + kind, + canvasPosition, + icon, + healthObjective, + impact, + labels, + signals, + discoveredBy, + deletedOn, + healthState, + alerts, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// The resource-specific properties for this resource. + /// A new instance for mocking. + public static RelationshipData RelationshipData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, RelationshipProperties properties = null) + { + return new RelationshipData( + id, + name, + resourceType, + systemData, + properties, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Resource name of the parent entity. + /// Resource name of the child entity. + /// Optional set of labels (key-value pairs). + /// Discovered by which discovery rule. If set, the relationship cannot be deleted manually. + /// Date when the relationship was (soft-)deleted. + /// A new instance for mocking. + public static RelationshipProperties RelationshipProperties(HealthModelProvisioningState? provisioningState = null, string displayName = null, string parentEntityName = null, string childEntityName = null, IDictionary labels = null, string discoveredBy = null, DateTimeOffset? deletedOn = null) + { + labels ??= new Dictionary(); + + return new RelationshipProperties( + provisioningState, + displayName, + parentEntityName, + childEntityName, + labels, + discoveredBy, + deletedOn, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// The resource-specific properties for this resource. + /// A new instance for mocking. + public static DiscoveryRuleData DiscoveryRuleData(ResourceIdentifier id = null, string name = null, ResourceType resourceType = default, SystemData systemData = null, DiscoveryRuleProperties properties = null) + { + return new DiscoveryRuleData( + id, + name, + resourceType, + systemData, + properties, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Azure Resource Graph query text in KQL syntax. The query must return at least a column named 'id' which contains the resource ID of the discovered resources. + /// Reference to the name of the authentication setting which is used for querying Azure Resource Graph. The same authentication setting will also be assigned to any discovered entities. + /// Whether to create relationships between the discovered entities based on a set of built-in rules. These relationships cannot be manually deleted. + /// Whether to add all recommended signals to the discovered entities. + /// Date when the discovery rule was (soft-)deleted. + /// Error message if the last discovery operation failed. + /// Number of discovered entities in the last discovery operation. + /// Name of the entity which represents the discovery rule. Note: It might take a few minutes after creating the discovery rule until the entity is created. + /// A new instance for mocking. + public static DiscoveryRuleProperties DiscoveryRuleProperties(HealthModelProvisioningState? provisioningState = null, string displayName = null, string resourceGraphQuery = null, string authenticationSetting = null, DiscoveryRuleRelationshipDiscoveryBehavior discoverRelationships = default, DiscoveryRuleRecommendedSignalsBehavior addRecommendedSignals = default, DateTimeOffset? deletedOn = null, string errorMessage = null, int? numberOfDiscoveredEntities = null, string entityName = null) + { + return new DiscoveryRuleProperties( + provisioningState, + displayName, + resourceGraphQuery, + authenticationSetting, + discoverRelationships, + addRecommendedSignals, + deletedOn, + errorMessage, + numberOfDiscoveredEntities, + entityName, + serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingCollection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingCollection.cs new file mode 100644 index 000000000000..2aa52f4e980a --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingCollection.cs @@ -0,0 +1,497 @@ +// 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; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// 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 GetAuthenticationSettings method from an instance of . + /// + public partial class AuthenticationSettingCollection : ArmCollection, IEnumerable, IAsyncEnumerable + { + private readonly ClientDiagnostics _authenticationSettingClientDiagnostics; + private readonly AuthenticationSettingsRestOperations _authenticationSettingRestClient; + + /// Initializes a new instance of the class for mocking. + protected AuthenticationSettingCollection() + { + } + + /// 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 AuthenticationSettingCollection(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _authenticationSettingClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CloudHealth", AuthenticationSettingResource.ResourceType.Namespace, Diagnostics); + TryGetApiVersion(AuthenticationSettingResource.ResourceType, out string authenticationSettingApiVersion); + _authenticationSettingRestClient = new AuthenticationSettingsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, authenticationSettingApiVersion); +#if DEBUG + ValidateResourceId(Id); +#endif + } + + internal static void ValidateResourceId(ResourceIdentifier id) + { + if (id.ResourceType != HealthModelResource.ResourceType) + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, HealthModelResource.ResourceType), nameof(id)); + } + + /// + /// Create a AuthenticationSetting + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Name of the authentication setting. Must be unique within a health model. + /// 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 authenticationSettingName, AuthenticationSettingData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = await _authenticationSettingRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, authenticationSettingName, data, cancellationToken).ConfigureAwait(false); + var uri = _authenticationSettingRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, authenticationSettingName, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new AuthenticationSettingResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a AuthenticationSetting + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Name of the authentication setting. Must be unique within a health model. + /// 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 authenticationSettingName, AuthenticationSettingData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = _authenticationSettingRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, authenticationSettingName, data, cancellationToken); + var uri = _authenticationSettingRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, authenticationSettingName, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new AuthenticationSettingResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a AuthenticationSetting + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the authentication setting. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetAsync(string authenticationSettingName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + + using var scope = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingCollection.Get"); + scope.Start(); + try + { + var response = await _authenticationSettingRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, authenticationSettingName, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new AuthenticationSettingResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a AuthenticationSetting + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the authentication setting. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Get(string authenticationSettingName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + + using var scope = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingCollection.Get"); + scope.Start(); + try + { + var response = _authenticationSettingRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, authenticationSettingName, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new AuthenticationSettingResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// List AuthenticationSetting resources by HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings + /// + /// + /// Operation Id + /// AuthenticationSetting_ListByHealthModel + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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) => _authenticationSettingRestClient.CreateListByHealthModelRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _authenticationSettingRestClient.CreateListByHealthModelNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new AuthenticationSettingResource(Client, AuthenticationSettingData.DeserializeAuthenticationSettingData(e)), _authenticationSettingClientDiagnostics, Pipeline, "AuthenticationSettingCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// List AuthenticationSetting resources by HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings + /// + /// + /// Operation Id + /// AuthenticationSetting_ListByHealthModel + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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) => _authenticationSettingRestClient.CreateListByHealthModelRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _authenticationSettingRestClient.CreateListByHealthModelNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new AuthenticationSettingResource(Client, AuthenticationSettingData.DeserializeAuthenticationSettingData(e)), _authenticationSettingClientDiagnostics, Pipeline, "AuthenticationSettingCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// Checks to see if the resource exists in azure. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the authentication setting. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> ExistsAsync(string authenticationSettingName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + + using var scope = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingCollection.Exists"); + scope.Start(); + try + { + var response = await _authenticationSettingRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, authenticationSettingName, 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.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the authentication setting. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Exists(string authenticationSettingName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + + using var scope = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingCollection.Exists"); + scope.Start(); + try + { + var response = _authenticationSettingRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, authenticationSettingName, 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.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the authentication setting. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetIfExistsAsync(string authenticationSettingName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + + using var scope = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingCollection.GetIfExists"); + scope.Start(); + try + { + var response = await _authenticationSettingRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, authenticationSettingName, cancellationToken: cancellationToken).ConfigureAwait(false); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new AuthenticationSettingResource(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.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the authentication setting. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual NullableResponse GetIfExists(string authenticationSettingName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + + using var scope = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingCollection.GetIfExists"); + scope.Start(); + try + { + var response = _authenticationSettingRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, authenticationSettingName, cancellationToken: cancellationToken); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new AuthenticationSettingResource(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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingData.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingData.Serialization.cs new file mode 100644 index 000000000000..126c36e8bce2 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingData.Serialization.cs @@ -0,0 +1,155 @@ +// 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.CloudHealth.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + public partial class AuthenticationSettingData : 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(AuthenticationSettingData)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Properties)) + { + writer.WritePropertyName("properties"u8); + writer.WriteObjectValue(Properties, options); + } + } + + AuthenticationSettingData 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(AuthenticationSettingData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAuthenticationSettingData(document.RootElement, options); + } + + internal static AuthenticationSettingData DeserializeAuthenticationSettingData(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AuthenticationSettingProperties properties = 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 = AuthenticationSettingProperties.DeserializeAuthenticationSettingProperties(property.Value, options); + 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 AuthenticationSettingData( + id, + name, + type, + systemData, + 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(AuthenticationSettingData)} does not support writing '{options.Format}' format."); + } + } + + AuthenticationSettingData 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 DeserializeAuthenticationSettingData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AuthenticationSettingData)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingData.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingData.cs new file mode 100644 index 000000000000..34d98d972656 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingData.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.CloudHealth.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A class representing the AuthenticationSetting data model. + /// An authentication setting in a health model + /// + public partial class AuthenticationSettingData : ResourceData + { + /// + /// 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 AuthenticationSettingData() + { + } + + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// + /// The resource-specific properties for this resource. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + /// Keeps track of any properties unknown to the library. + internal AuthenticationSettingData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, AuthenticationSettingProperties properties, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) + { + Properties = properties; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// The resource-specific properties for this resource. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public AuthenticationSettingProperties Properties { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingResource.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingResource.Serialization.cs new file mode 100644 index 000000000000..a238b5b713a8 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingResource.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.CloudHealth +{ + public partial class AuthenticationSettingResource : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); + + AuthenticationSettingData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)Data).Create(ref reader, options); + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options); + + AuthenticationSettingData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options); + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)Data).GetFormatFromOptions(options); + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingResource.cs new file mode 100644 index 000000000000..b320ced926bb --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/AuthenticationSettingResource.cs @@ -0,0 +1,355 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A Class representing an AuthenticationSetting 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 GetAuthenticationSettingResource method. + /// Otherwise you can get one from its parent resource using the GetAuthenticationSetting method. + /// + public partial class AuthenticationSettingResource : ArmResource + { + /// Generate the resource identifier of a instance. + /// The subscriptionId. + /// The resourceGroupName. + /// The healthModelName. + /// The authenticationSettingName. + public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string healthModelName, string authenticationSettingName) + { + var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName}"; + return new ResourceIdentifier(resourceId); + } + + private readonly ClientDiagnostics _authenticationSettingClientDiagnostics; + private readonly AuthenticationSettingsRestOperations _authenticationSettingRestClient; + private readonly AuthenticationSettingData _data; + + /// Gets the resource type for the operations. + public static readonly ResourceType ResourceType = "Microsoft.CloudHealth/healthmodels/authenticationsettings"; + + /// Initializes a new instance of the class for mocking. + protected AuthenticationSettingResource() + { + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The resource that is the target of operations. + internal AuthenticationSettingResource(ArmClient client, AuthenticationSettingData 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 AuthenticationSettingResource(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _authenticationSettingClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CloudHealth", ResourceType.Namespace, Diagnostics); + TryGetApiVersion(ResourceType, out string authenticationSettingApiVersion); + _authenticationSettingRestClient = new AuthenticationSettingsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, authenticationSettingApiVersion); +#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 AuthenticationSettingData 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 AuthenticationSetting + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual async Task> GetAsync(CancellationToken cancellationToken = default) + { + using var scope = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingResource.Get"); + scope.Start(); + try + { + var response = await _authenticationSettingRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new AuthenticationSettingResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a AuthenticationSetting + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual Response Get(CancellationToken cancellationToken = default) + { + using var scope = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingResource.Get"); + scope.Start(); + try + { + var response = _authenticationSettingRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new AuthenticationSettingResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a AuthenticationSetting + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_Delete + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingResource.Delete"); + scope.Start(); + try + { + var response = await _authenticationSettingRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); + var uri = _authenticationSettingRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(response, rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a AuthenticationSetting + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_Delete + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingResource.Delete"); + scope.Start(); + try + { + var response = _authenticationSettingRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); + var uri = _authenticationSettingRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(response, rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletionResponse(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a AuthenticationSetting + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Resource create parameters. + /// The cancellation token to use. + /// is null. + public virtual async Task> UpdateAsync(WaitUntil waitUntil, AuthenticationSettingData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingResource.Update"); + scope.Start(); + try + { + var response = await _authenticationSettingRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false); + var uri = _authenticationSettingRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new AuthenticationSettingResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a AuthenticationSetting + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Resource create parameters. + /// The cancellation token to use. + /// is null. + public virtual ArmOperation Update(WaitUntil waitUntil, AuthenticationSettingData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _authenticationSettingClientDiagnostics.CreateScope("AuthenticationSettingResource.Update"); + scope.Start(); + try + { + var response = _authenticationSettingRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken); + var uri = _authenticationSettingRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new AuthenticationSettingResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleCollection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleCollection.cs new file mode 100644 index 000000000000..db9cf7e60aee --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleCollection.cs @@ -0,0 +1,499 @@ +// 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; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A class representing a collection of and their operations. + /// Each in the collection will belong to the same instance of . + /// To get a instance call the GetDiscoveryRules method from an instance of . + /// + public partial class DiscoveryRuleCollection : ArmCollection, IEnumerable, IAsyncEnumerable + { + private readonly ClientDiagnostics _discoveryRuleClientDiagnostics; + private readonly DiscoveryRulesRestOperations _discoveryRuleRestClient; + + /// Initializes a new instance of the class for mocking. + protected DiscoveryRuleCollection() + { + } + + /// 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 DiscoveryRuleCollection(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _discoveryRuleClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CloudHealth", DiscoveryRuleResource.ResourceType.Namespace, Diagnostics); + TryGetApiVersion(DiscoveryRuleResource.ResourceType, out string discoveryRuleApiVersion); + _discoveryRuleRestClient = new DiscoveryRulesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, discoveryRuleApiVersion); +#if DEBUG + ValidateResourceId(Id); +#endif + } + + internal static void ValidateResourceId(ResourceIdentifier id) + { + if (id.ResourceType != HealthModelResource.ResourceType) + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, HealthModelResource.ResourceType), nameof(id)); + } + + /// + /// Create a DiscoveryRule + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Name of the discovery rule. Must be unique within a health model. + /// 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 discoveryRuleName, DiscoveryRuleData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = await _discoveryRuleRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, discoveryRuleName, data, cancellationToken).ConfigureAwait(false); + var uri = _discoveryRuleRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, discoveryRuleName, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new DiscoveryRuleResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a DiscoveryRule + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Name of the discovery rule. Must be unique within a health model. + /// 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 discoveryRuleName, DiscoveryRuleData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = _discoveryRuleRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, discoveryRuleName, data, cancellationToken); + var uri = _discoveryRuleRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, discoveryRuleName, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new DiscoveryRuleResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a DiscoveryRule + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the discovery rule. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetAsync(string discoveryRuleName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + + using var scope = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleCollection.Get"); + scope.Start(); + try + { + var response = await _discoveryRuleRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, discoveryRuleName, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new DiscoveryRuleResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a DiscoveryRule + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the discovery rule. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Get(string discoveryRuleName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + + using var scope = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleCollection.Get"); + scope.Start(); + try + { + var response = _discoveryRuleRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, discoveryRuleName, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new DiscoveryRuleResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// List DiscoveryRule resources by HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules + /// + /// + /// Operation Id + /// DiscoveryRule_ListByHealthModel + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// An async collection of that may take multiple service requests to iterate over. + public virtual AsyncPageable GetAllAsync(DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => _discoveryRuleRestClient.CreateListByHealthModelRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _discoveryRuleRestClient.CreateListByHealthModelNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new DiscoveryRuleResource(Client, DiscoveryRuleData.DeserializeDiscoveryRuleData(e)), _discoveryRuleClientDiagnostics, Pipeline, "DiscoveryRuleCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// List DiscoveryRule resources by HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules + /// + /// + /// Operation Id + /// DiscoveryRule_ListByHealthModel + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// A collection of that may take multiple service requests to iterate over. + public virtual Pageable GetAll(DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => _discoveryRuleRestClient.CreateListByHealthModelRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _discoveryRuleRestClient.CreateListByHealthModelNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new DiscoveryRuleResource(Client, DiscoveryRuleData.DeserializeDiscoveryRuleData(e)), _discoveryRuleClientDiagnostics, Pipeline, "DiscoveryRuleCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// Checks to see if the resource exists in azure. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the discovery rule. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> ExistsAsync(string discoveryRuleName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + + using var scope = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleCollection.Exists"); + scope.Start(); + try + { + var response = await _discoveryRuleRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, discoveryRuleName, 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.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the discovery rule. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Exists(string discoveryRuleName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + + using var scope = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleCollection.Exists"); + scope.Start(); + try + { + var response = _discoveryRuleRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, discoveryRuleName, 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.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the discovery rule. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetIfExistsAsync(string discoveryRuleName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + + using var scope = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleCollection.GetIfExists"); + scope.Start(); + try + { + var response = await _discoveryRuleRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, discoveryRuleName, cancellationToken: cancellationToken).ConfigureAwait(false); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new DiscoveryRuleResource(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.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the discovery rule. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual NullableResponse GetIfExists(string discoveryRuleName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + + using var scope = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleCollection.GetIfExists"); + scope.Start(); + try + { + var response = _discoveryRuleRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, discoveryRuleName, cancellationToken: cancellationToken); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new DiscoveryRuleResource(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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleData.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleData.Serialization.cs new file mode 100644 index 000000000000..747836168ade --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleData.Serialization.cs @@ -0,0 +1,155 @@ +// 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.CloudHealth.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + public partial class DiscoveryRuleData : 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(DiscoveryRuleData)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Properties)) + { + writer.WritePropertyName("properties"u8); + writer.WriteObjectValue(Properties, options); + } + } + + DiscoveryRuleData 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(DiscoveryRuleData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDiscoveryRuleData(document.RootElement, options); + } + + internal static DiscoveryRuleData DeserializeDiscoveryRuleData(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + DiscoveryRuleProperties properties = 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 = DiscoveryRuleProperties.DeserializeDiscoveryRuleProperties(property.Value, options); + 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 DiscoveryRuleData( + id, + name, + type, + systemData, + 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(DiscoveryRuleData)} does not support writing '{options.Format}' format."); + } + } + + DiscoveryRuleData 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 DeserializeDiscoveryRuleData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DiscoveryRuleData)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleData.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleData.cs new file mode 100644 index 000000000000..b0a2040e717b --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleData.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; +using Azure.Core; +using Azure.ResourceManager.CloudHealth.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A class representing the DiscoveryRule data model. + /// A discovery rule which automatically finds entities and relationships in a health model based on an Azure Resource Graph query + /// + public partial class DiscoveryRuleData : ResourceData + { + /// + /// 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 DiscoveryRuleData() + { + } + + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// The resource-specific properties for this resource. + /// Keeps track of any properties unknown to the library. + internal DiscoveryRuleData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, DiscoveryRuleProperties properties, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) + { + Properties = properties; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The resource-specific properties for this resource. + public DiscoveryRuleProperties Properties { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleResource.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleResource.Serialization.cs new file mode 100644 index 000000000000..be81652e4cb2 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleResource.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.CloudHealth +{ + public partial class DiscoveryRuleResource : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); + + DiscoveryRuleData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)Data).Create(ref reader, options); + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options); + + DiscoveryRuleData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options); + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)Data).GetFormatFromOptions(options); + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleResource.cs new file mode 100644 index 000000000000..ba3a2c28f578 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/DiscoveryRuleResource.cs @@ -0,0 +1,355 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A Class representing a DiscoveryRule along with the instance operations that can be performed on it. + /// If you have a you can construct a + /// from an instance of using the GetDiscoveryRuleResource method. + /// Otherwise you can get one from its parent resource using the GetDiscoveryRule method. + /// + public partial class DiscoveryRuleResource : ArmResource + { + /// Generate the resource identifier of a instance. + /// The subscriptionId. + /// The resourceGroupName. + /// The healthModelName. + /// The discoveryRuleName. + public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string healthModelName, string discoveryRuleName) + { + var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName}"; + return new ResourceIdentifier(resourceId); + } + + private readonly ClientDiagnostics _discoveryRuleClientDiagnostics; + private readonly DiscoveryRulesRestOperations _discoveryRuleRestClient; + private readonly DiscoveryRuleData _data; + + /// Gets the resource type for the operations. + public static readonly ResourceType ResourceType = "Microsoft.CloudHealth/healthmodels/discoveryrules"; + + /// Initializes a new instance of the class for mocking. + protected DiscoveryRuleResource() + { + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The resource that is the target of operations. + internal DiscoveryRuleResource(ArmClient client, DiscoveryRuleData 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 DiscoveryRuleResource(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _discoveryRuleClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CloudHealth", ResourceType.Namespace, Diagnostics); + TryGetApiVersion(ResourceType, out string discoveryRuleApiVersion); + _discoveryRuleRestClient = new DiscoveryRulesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, discoveryRuleApiVersion); +#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 DiscoveryRuleData 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 DiscoveryRule + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual async Task> GetAsync(CancellationToken cancellationToken = default) + { + using var scope = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleResource.Get"); + scope.Start(); + try + { + var response = await _discoveryRuleRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new DiscoveryRuleResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a DiscoveryRule + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual Response Get(CancellationToken cancellationToken = default) + { + using var scope = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleResource.Get"); + scope.Start(); + try + { + var response = _discoveryRuleRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new DiscoveryRuleResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a DiscoveryRule + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_Delete + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleResource.Delete"); + scope.Start(); + try + { + var response = await _discoveryRuleRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); + var uri = _discoveryRuleRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(response, rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a DiscoveryRule + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_Delete + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleResource.Delete"); + scope.Start(); + try + { + var response = _discoveryRuleRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); + var uri = _discoveryRuleRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(response, rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletionResponse(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a DiscoveryRule + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Resource create parameters. + /// The cancellation token to use. + /// is null. + public virtual async Task> UpdateAsync(WaitUntil waitUntil, DiscoveryRuleData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleResource.Update"); + scope.Start(); + try + { + var response = await _discoveryRuleRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false); + var uri = _discoveryRuleRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new DiscoveryRuleResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a DiscoveryRule + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Resource create parameters. + /// The cancellation token to use. + /// is null. + public virtual ArmOperation Update(WaitUntil waitUntil, DiscoveryRuleData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _discoveryRuleClientDiagnostics.CreateScope("DiscoveryRuleResource.Update"); + scope.Start(); + try + { + var response = _discoveryRuleRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken); + var uri = _discoveryRuleRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new DiscoveryRuleResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityCollection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityCollection.cs new file mode 100644 index 000000000000..6330d96ed919 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityCollection.cs @@ -0,0 +1,499 @@ +// 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; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// 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 GetEntities method from an instance of . + /// + public partial class EntityCollection : ArmCollection, IEnumerable, IAsyncEnumerable + { + private readonly ClientDiagnostics _entityClientDiagnostics; + private readonly EntitiesRestOperations _entityRestClient; + + /// Initializes a new instance of the class for mocking. + protected EntityCollection() + { + } + + /// 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 EntityCollection(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _entityClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CloudHealth", EntityResource.ResourceType.Namespace, Diagnostics); + TryGetApiVersion(EntityResource.ResourceType, out string entityApiVersion); + _entityRestClient = new EntitiesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, entityApiVersion); +#if DEBUG + ValidateResourceId(Id); +#endif + } + + internal static void ValidateResourceId(ResourceIdentifier id) + { + if (id.ResourceType != HealthModelResource.ResourceType) + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, HealthModelResource.ResourceType), nameof(id)); + } + + /// + /// Create a Entity + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Name of the entity. Must be unique within a health model. + /// 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 entityName, EntityData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _entityClientDiagnostics.CreateScope("EntityCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = await _entityRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, entityName, data, cancellationToken).ConfigureAwait(false); + var uri = _entityRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, entityName, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new EntityResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a Entity + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Name of the entity. Must be unique within a health model. + /// 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 entityName, EntityData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _entityClientDiagnostics.CreateScope("EntityCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = _entityRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, entityName, data, cancellationToken); + var uri = _entityRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, entityName, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new EntityResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a Entity + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the entity. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetAsync(string entityName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + + using var scope = _entityClientDiagnostics.CreateScope("EntityCollection.Get"); + scope.Start(); + try + { + var response = await _entityRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, entityName, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new EntityResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a Entity + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the entity. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Get(string entityName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + + using var scope = _entityClientDiagnostics.CreateScope("EntityCollection.Get"); + scope.Start(); + try + { + var response = _entityRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, entityName, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new EntityResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// List Entity resources by HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities + /// + /// + /// Operation Id + /// Entity_ListByHealthModel + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// An async collection of that may take multiple service requests to iterate over. + public virtual AsyncPageable GetAllAsync(DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => _entityRestClient.CreateListByHealthModelRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _entityRestClient.CreateListByHealthModelNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new EntityResource(Client, EntityData.DeserializeEntityData(e)), _entityClientDiagnostics, Pipeline, "EntityCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// List Entity resources by HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities + /// + /// + /// Operation Id + /// Entity_ListByHealthModel + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// A collection of that may take multiple service requests to iterate over. + public virtual Pageable GetAll(DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => _entityRestClient.CreateListByHealthModelRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _entityRestClient.CreateListByHealthModelNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new EntityResource(Client, EntityData.DeserializeEntityData(e)), _entityClientDiagnostics, Pipeline, "EntityCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// Checks to see if the resource exists in azure. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the entity. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> ExistsAsync(string entityName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + + using var scope = _entityClientDiagnostics.CreateScope("EntityCollection.Exists"); + scope.Start(); + try + { + var response = await _entityRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, entityName, 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.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the entity. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Exists(string entityName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + + using var scope = _entityClientDiagnostics.CreateScope("EntityCollection.Exists"); + scope.Start(); + try + { + var response = _entityRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, entityName, 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.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the entity. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetIfExistsAsync(string entityName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + + using var scope = _entityClientDiagnostics.CreateScope("EntityCollection.GetIfExists"); + scope.Start(); + try + { + var response = await _entityRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, entityName, cancellationToken: cancellationToken).ConfigureAwait(false); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new EntityResource(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.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the entity. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual NullableResponse GetIfExists(string entityName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + + using var scope = _entityClientDiagnostics.CreateScope("EntityCollection.GetIfExists"); + scope.Start(); + try + { + var response = _entityRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, entityName, cancellationToken: cancellationToken); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new EntityResource(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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityData.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityData.Serialization.cs new file mode 100644 index 000000000000..2c8cb650b692 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityData.Serialization.cs @@ -0,0 +1,155 @@ +// 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.CloudHealth.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + public partial class EntityData : 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(EntityData)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Properties)) + { + writer.WritePropertyName("properties"u8); + writer.WriteObjectValue(Properties, options); + } + } + + EntityData 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(EntityData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEntityData(document.RootElement, options); + } + + internal static EntityData DeserializeEntityData(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + EntityProperties properties = 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 = EntityProperties.DeserializeEntityProperties(property.Value, options); + 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 EntityData( + id, + name, + type, + systemData, + 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(EntityData)} does not support writing '{options.Format}' format."); + } + } + + EntityData 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 DeserializeEntityData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EntityData)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityData.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityData.cs new file mode 100644 index 000000000000..dc328a4861fd --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityData.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; +using Azure.Core; +using Azure.ResourceManager.CloudHealth.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A class representing the Entity data model. + /// An entity (aka node) of a health model + /// + public partial class EntityData : ResourceData + { + /// + /// 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 EntityData() + { + } + + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// The resource-specific properties for this resource. + /// Keeps track of any properties unknown to the library. + internal EntityData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, EntityProperties properties, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) + { + Properties = properties; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The resource-specific properties for this resource. + public EntityProperties Properties { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityResource.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityResource.Serialization.cs new file mode 100644 index 000000000000..1da16070f480 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityResource.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.CloudHealth +{ + public partial class EntityResource : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); + + EntityData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)Data).Create(ref reader, options); + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options); + + EntityData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options); + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)Data).GetFormatFromOptions(options); + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityResource.cs new file mode 100644 index 000000000000..aa5f39b54e57 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/EntityResource.cs @@ -0,0 +1,355 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A Class representing an Entity 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 GetEntityResource method. + /// Otherwise you can get one from its parent resource using the GetEntity method. + /// + public partial class EntityResource : ArmResource + { + /// Generate the resource identifier of a instance. + /// The subscriptionId. + /// The resourceGroupName. + /// The healthModelName. + /// The entityName. + public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string healthModelName, string entityName) + { + var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName}"; + return new ResourceIdentifier(resourceId); + } + + private readonly ClientDiagnostics _entityClientDiagnostics; + private readonly EntitiesRestOperations _entityRestClient; + private readonly EntityData _data; + + /// Gets the resource type for the operations. + public static readonly ResourceType ResourceType = "Microsoft.CloudHealth/healthmodels/entities"; + + /// Initializes a new instance of the class for mocking. + protected EntityResource() + { + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The resource that is the target of operations. + internal EntityResource(ArmClient client, EntityData 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 EntityResource(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _entityClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CloudHealth", ResourceType.Namespace, Diagnostics); + TryGetApiVersion(ResourceType, out string entityApiVersion); + _entityRestClient = new EntitiesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, entityApiVersion); +#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 EntityData 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 Entity + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual async Task> GetAsync(CancellationToken cancellationToken = default) + { + using var scope = _entityClientDiagnostics.CreateScope("EntityResource.Get"); + scope.Start(); + try + { + var response = await _entityRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new EntityResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a Entity + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual Response Get(CancellationToken cancellationToken = default) + { + using var scope = _entityClientDiagnostics.CreateScope("EntityResource.Get"); + scope.Start(); + try + { + var response = _entityRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new EntityResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a Entity + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_Delete + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _entityClientDiagnostics.CreateScope("EntityResource.Delete"); + scope.Start(); + try + { + var response = await _entityRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); + var uri = _entityRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(response, rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a Entity + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_Delete + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _entityClientDiagnostics.CreateScope("EntityResource.Delete"); + scope.Start(); + try + { + var response = _entityRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); + var uri = _entityRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(response, rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletionResponse(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a Entity + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Resource create parameters. + /// The cancellation token to use. + /// is null. + public virtual async Task> UpdateAsync(WaitUntil waitUntil, EntityData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _entityClientDiagnostics.CreateScope("EntityResource.Update"); + scope.Start(); + try + { + var response = await _entityRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false); + var uri = _entityRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new EntityResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a Entity + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Resource create parameters. + /// The cancellation token to use. + /// is null. + public virtual ArmOperation Update(WaitUntil waitUntil, EntityData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _entityClientDiagnostics.CreateScope("EntityResource.Update"); + scope.Start(); + try + { + var response = _entityRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken); + var uri = _entityRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new EntityResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Extensions/CloudHealthExtensions.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Extensions/CloudHealthExtensions.cs new file mode 100644 index 000000000000..391dbf8fc728 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Extensions/CloudHealthExtensions.cs @@ -0,0 +1,314 @@ +// 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.CloudHealth.Mocking; +using Azure.ResourceManager.Resources; + +namespace Azure.ResourceManager.CloudHealth +{ + /// A class to add extension methods to Azure.ResourceManager.CloudHealth. + public static partial class CloudHealthExtensions + { + private static MockableCloudHealthArmClient GetMockableCloudHealthArmClient(ArmClient client) + { + return client.GetCachedClient(client0 => new MockableCloudHealthArmClient(client0)); + } + + private static MockableCloudHealthResourceGroupResource GetMockableCloudHealthResourceGroupResource(ArmResource resource) + { + return resource.GetCachedClient(client => new MockableCloudHealthResourceGroupResource(client, resource.Id)); + } + + private static MockableCloudHealthSubscriptionResource GetMockableCloudHealthSubscriptionResource(ArmResource resource) + { + return resource.GetCachedClient(client => new MockableCloudHealthSubscriptionResource(client, resource.Id)); + } + + /// + /// Gets an object representing a along with the instance operations that can be performed on it but with no data. + /// You can use to create a 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 HealthModelResource GetHealthModelResource(this ArmClient client, ResourceIdentifier id) + { + Argument.AssertNotNull(client, nameof(client)); + + return GetMockableCloudHealthArmClient(client).GetHealthModelResource(id); + } + + /// + /// Gets an object representing a along with the instance operations that can be performed on it but with no data. + /// You can use to create a 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 SignalDefinitionResource GetSignalDefinitionResource(this ArmClient client, ResourceIdentifier id) + { + Argument.AssertNotNull(client, nameof(client)); + + return GetMockableCloudHealthArmClient(client).GetSignalDefinitionResource(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 AuthenticationSettingResource GetAuthenticationSettingResource(this ArmClient client, ResourceIdentifier id) + { + Argument.AssertNotNull(client, nameof(client)); + + return GetMockableCloudHealthArmClient(client).GetAuthenticationSettingResource(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 EntityResource GetEntityResource(this ArmClient client, ResourceIdentifier id) + { + Argument.AssertNotNull(client, nameof(client)); + + return GetMockableCloudHealthArmClient(client).GetEntityResource(id); + } + + /// + /// Gets an object representing a along with the instance operations that can be performed on it but with no data. + /// You can use to create a 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 RelationshipResource GetRelationshipResource(this ArmClient client, ResourceIdentifier id) + { + Argument.AssertNotNull(client, nameof(client)); + + return GetMockableCloudHealthArmClient(client).GetRelationshipResource(id); + } + + /// + /// Gets an object representing a along with the instance operations that can be performed on it but with no data. + /// You can use to create a 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 DiscoveryRuleResource GetDiscoveryRuleResource(this ArmClient client, ResourceIdentifier id) + { + Argument.AssertNotNull(client, nameof(client)); + + return GetMockableCloudHealthArmClient(client).GetDiscoveryRuleResource(id); + } + + /// + /// Gets a collection of HealthModelResources 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 HealthModelResources and their operations over a HealthModelResource. + public static HealthModelCollection GetHealthModels(this ResourceGroupResource resourceGroupResource) + { + Argument.AssertNotNull(resourceGroupResource, nameof(resourceGroupResource)); + + return GetMockableCloudHealthResourceGroupResource(resourceGroupResource).GetHealthModels(); + } + + /// + /// Get a HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Mocking + /// To mock this method, please mock instead. + /// + /// + /// The instance the method will execute against. + /// Name of health model resource. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public static async Task> GetHealthModelAsync(this ResourceGroupResource resourceGroupResource, string healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(resourceGroupResource, nameof(resourceGroupResource)); + + return await GetMockableCloudHealthResourceGroupResource(resourceGroupResource).GetHealthModelAsync(healthModelName, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Mocking + /// To mock this method, please mock instead. + /// + /// + /// The instance the method will execute against. + /// Name of health model resource. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public static Response GetHealthModel(this ResourceGroupResource resourceGroupResource, string healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(resourceGroupResource, nameof(resourceGroupResource)); + + return GetMockableCloudHealthResourceGroupResource(resourceGroupResource).GetHealthModel(healthModelName, cancellationToken); + } + + /// + /// List HealthModel resources by subscription ID + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/providers/Microsoft.CloudHealth/healthmodels + /// + /// + /// Operation Id + /// HealthModel_ListBySubscription + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 GetHealthModelsAsync(this SubscriptionResource subscriptionResource, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(subscriptionResource, nameof(subscriptionResource)); + + return GetMockableCloudHealthSubscriptionResource(subscriptionResource).GetHealthModelsAsync(cancellationToken); + } + + /// + /// List HealthModel resources by subscription ID + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/providers/Microsoft.CloudHealth/healthmodels + /// + /// + /// Operation Id + /// HealthModel_ListBySubscription + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 GetHealthModels(this SubscriptionResource subscriptionResource, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(subscriptionResource, nameof(subscriptionResource)); + + return GetMockableCloudHealthSubscriptionResource(subscriptionResource).GetHealthModels(cancellationToken); + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Extensions/MockableCloudHealthArmClient.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Extensions/MockableCloudHealthArmClient.cs new file mode 100644 index 000000000000..7b0b19e900ae --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Extensions/MockableCloudHealthArmClient.cs @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using Azure.Core; + +namespace Azure.ResourceManager.CloudHealth.Mocking +{ + /// A class to add extension methods to ArmClient. + public partial class MockableCloudHealthArmClient : ArmResource + { + /// Initializes a new instance of the class for mocking. + protected MockableCloudHealthArmClient() + { + } + + /// 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 MockableCloudHealthArmClient(ArmClient client, ResourceIdentifier id) : base(client, id) + { + } + + internal MockableCloudHealthArmClient(ArmClient client) : this(client, ResourceIdentifier.Root) + { + } + + private string GetApiVersionOrNull(ResourceType resourceType) + { + TryGetApiVersion(resourceType, out string apiVersion); + return apiVersion; + } + + /// + /// Gets an object representing a along with the instance operations that can be performed on it but with no data. + /// You can use to create a from its components. + /// + /// The resource ID of the resource to get. + /// Returns a object. + public virtual HealthModelResource GetHealthModelResource(ResourceIdentifier id) + { + HealthModelResource.ValidateResourceId(id); + return new HealthModelResource(Client, id); + } + + /// + /// Gets an object representing a along with the instance operations that can be performed on it but with no data. + /// You can use to create a from its components. + /// + /// The resource ID of the resource to get. + /// Returns a object. + public virtual SignalDefinitionResource GetSignalDefinitionResource(ResourceIdentifier id) + { + SignalDefinitionResource.ValidateResourceId(id); + return new SignalDefinitionResource(Client, 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. + /// + /// The resource ID of the resource to get. + /// Returns a object. + public virtual AuthenticationSettingResource GetAuthenticationSettingResource(ResourceIdentifier id) + { + AuthenticationSettingResource.ValidateResourceId(id); + return new AuthenticationSettingResource(Client, 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. + /// + /// The resource ID of the resource to get. + /// Returns a object. + public virtual EntityResource GetEntityResource(ResourceIdentifier id) + { + EntityResource.ValidateResourceId(id); + return new EntityResource(Client, id); + } + + /// + /// Gets an object representing a along with the instance operations that can be performed on it but with no data. + /// You can use to create a from its components. + /// + /// The resource ID of the resource to get. + /// Returns a object. + public virtual RelationshipResource GetRelationshipResource(ResourceIdentifier id) + { + RelationshipResource.ValidateResourceId(id); + return new RelationshipResource(Client, id); + } + + /// + /// Gets an object representing a along with the instance operations that can be performed on it but with no data. + /// You can use to create a from its components. + /// + /// The resource ID of the resource to get. + /// Returns a object. + public virtual DiscoveryRuleResource GetDiscoveryRuleResource(ResourceIdentifier id) + { + DiscoveryRuleResource.ValidateResourceId(id); + return new DiscoveryRuleResource(Client, id); + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Extensions/MockableCloudHealthResourceGroupResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Extensions/MockableCloudHealthResourceGroupResource.cs new file mode 100644 index 000000000000..a822a8d14baf --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Extensions/MockableCloudHealthResourceGroupResource.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.CloudHealth.Mocking +{ + /// A class to add extension methods to ResourceGroupResource. + public partial class MockableCloudHealthResourceGroupResource : ArmResource + { + /// Initializes a new instance of the class for mocking. + protected MockableCloudHealthResourceGroupResource() + { + } + + /// 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 MockableCloudHealthResourceGroupResource(ArmClient client, ResourceIdentifier id) : base(client, id) + { + } + + private string GetApiVersionOrNull(ResourceType resourceType) + { + TryGetApiVersion(resourceType, out string apiVersion); + return apiVersion; + } + + /// Gets a collection of HealthModelResources in the ResourceGroupResource. + /// An object representing collection of HealthModelResources and their operations over a HealthModelResource. + public virtual HealthModelCollection GetHealthModels() + { + return GetCachedClient(client => new HealthModelCollection(client, Id)); + } + + /// + /// Get a HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of health model resource. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual async Task> GetHealthModelAsync(string healthModelName, CancellationToken cancellationToken = default) + { + return await GetHealthModels().GetAsync(healthModelName, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of health model resource. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual Response GetHealthModel(string healthModelName, CancellationToken cancellationToken = default) + { + return GetHealthModels().Get(healthModelName, cancellationToken); + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Extensions/MockableCloudHealthSubscriptionResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Extensions/MockableCloudHealthSubscriptionResource.cs new file mode 100644 index 000000000000..f6efa4e53d25 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Extensions/MockableCloudHealthSubscriptionResource.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.CloudHealth.Mocking +{ + /// A class to add extension methods to SubscriptionResource. + public partial class MockableCloudHealthSubscriptionResource : ArmResource + { + private ClientDiagnostics _healthModelClientDiagnostics; + private HealthModelsRestOperations _healthModelRestClient; + + /// Initializes a new instance of the class for mocking. + protected MockableCloudHealthSubscriptionResource() + { + } + + /// 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 MockableCloudHealthSubscriptionResource(ArmClient client, ResourceIdentifier id) : base(client, id) + { + } + + private ClientDiagnostics HealthModelClientDiagnostics => _healthModelClientDiagnostics ??= new ClientDiagnostics("Azure.ResourceManager.CloudHealth", HealthModelResource.ResourceType.Namespace, Diagnostics); + private HealthModelsRestOperations HealthModelRestClient => _healthModelRestClient ??= new HealthModelsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, GetApiVersionOrNull(HealthModelResource.ResourceType)); + + private string GetApiVersionOrNull(ResourceType resourceType) + { + TryGetApiVersion(resourceType, out string apiVersion); + return apiVersion; + } + + /// + /// List HealthModel resources by subscription ID + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/providers/Microsoft.CloudHealth/healthmodels + /// + /// + /// Operation Id + /// HealthModel_ListBySubscription + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + /// An async collection of that may take multiple service requests to iterate over. + public virtual AsyncPageable GetHealthModelsAsync(CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => HealthModelRestClient.CreateListBySubscriptionRequest(Id.SubscriptionId); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => HealthModelRestClient.CreateListBySubscriptionNextPageRequest(nextLink, Id.SubscriptionId); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new HealthModelResource(Client, HealthModelData.DeserializeHealthModelData(e)), HealthModelClientDiagnostics, Pipeline, "MockableCloudHealthSubscriptionResource.GetHealthModels", "value", "nextLink", cancellationToken); + } + + /// + /// List HealthModel resources by subscription ID + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/providers/Microsoft.CloudHealth/healthmodels + /// + /// + /// Operation Id + /// HealthModel_ListBySubscription + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + /// A collection of that may take multiple service requests to iterate over. + public virtual Pageable GetHealthModels(CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => HealthModelRestClient.CreateListBySubscriptionRequest(Id.SubscriptionId); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => HealthModelRestClient.CreateListBySubscriptionNextPageRequest(nextLink, Id.SubscriptionId); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new HealthModelResource(Client, HealthModelData.DeserializeHealthModelData(e)), HealthModelClientDiagnostics, Pipeline, "MockableCloudHealthSubscriptionResource.GetHealthModels", "value", "nextLink", cancellationToken); + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelCollection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelCollection.cs new file mode 100644 index 000000000000..afebbbfaea7f --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelCollection.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.CloudHealth +{ + /// + /// A class representing a collection of and their operations. + /// Each in the collection will belong to the same instance of . + /// To get a instance call the GetHealthModels method from an instance of . + /// + public partial class HealthModelCollection : ArmCollection, IEnumerable, IAsyncEnumerable + { + private readonly ClientDiagnostics _healthModelClientDiagnostics; + private readonly HealthModelsRestOperations _healthModelRestClient; + + /// Initializes a new instance of the class for mocking. + protected HealthModelCollection() + { + } + + /// 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 HealthModelCollection(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _healthModelClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CloudHealth", HealthModelResource.ResourceType.Namespace, Diagnostics); + TryGetApiVersion(HealthModelResource.ResourceType, out string healthModelApiVersion); + _healthModelRestClient = new HealthModelsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, healthModelApiVersion); +#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 HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Create + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Name of health model resource. + /// 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 healthModelName, HealthModelData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _healthModelClientDiagnostics.CreateScope("HealthModelCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = await _healthModelRestClient.CreateAsync(Id.SubscriptionId, Id.ResourceGroupName, healthModelName, data, cancellationToken).ConfigureAwait(false); + var operation = new CloudHealthArmOperation(new HealthModelOperationSource(Client), _healthModelClientDiagnostics, Pipeline, _healthModelRestClient.CreateCreateRequest(Id.SubscriptionId, Id.ResourceGroupName, healthModelName, 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 HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Create + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Name of health model resource. + /// 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 healthModelName, HealthModelData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _healthModelClientDiagnostics.CreateScope("HealthModelCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = _healthModelRestClient.Create(Id.SubscriptionId, Id.ResourceGroupName, healthModelName, data, cancellationToken); + var operation = new CloudHealthArmOperation(new HealthModelOperationSource(Client), _healthModelClientDiagnostics, Pipeline, _healthModelRestClient.CreateCreateRequest(Id.SubscriptionId, Id.ResourceGroupName, healthModelName, data).Request, response, OperationFinalStateVia.AzureAsyncOperation); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of health model resource. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetAsync(string healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var scope = _healthModelClientDiagnostics.CreateScope("HealthModelCollection.Get"); + scope.Start(); + try + { + var response = await _healthModelRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, healthModelName, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new HealthModelResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of health model resource. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Get(string healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var scope = _healthModelClientDiagnostics.CreateScope("HealthModelCollection.Get"); + scope.Start(); + try + { + var response = _healthModelRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, healthModelName, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new HealthModelResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// List HealthModel resources by resource group + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels + /// + /// + /// Operation Id + /// HealthModel_ListByResourceGroup + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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) => _healthModelRestClient.CreateListByResourceGroupRequest(Id.SubscriptionId, Id.ResourceGroupName); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _healthModelRestClient.CreateListByResourceGroupNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new HealthModelResource(Client, HealthModelData.DeserializeHealthModelData(e)), _healthModelClientDiagnostics, Pipeline, "HealthModelCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// List HealthModel resources by resource group + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels + /// + /// + /// Operation Id + /// HealthModel_ListByResourceGroup + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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) => _healthModelRestClient.CreateListByResourceGroupRequest(Id.SubscriptionId, Id.ResourceGroupName); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _healthModelRestClient.CreateListByResourceGroupNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new HealthModelResource(Client, HealthModelData.DeserializeHealthModelData(e)), _healthModelClientDiagnostics, Pipeline, "HealthModelCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// Checks to see if the resource exists in azure. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of health model resource. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> ExistsAsync(string healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var scope = _healthModelClientDiagnostics.CreateScope("HealthModelCollection.Exists"); + scope.Start(); + try + { + var response = await _healthModelRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, healthModelName, 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.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of health model resource. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Exists(string healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var scope = _healthModelClientDiagnostics.CreateScope("HealthModelCollection.Exists"); + scope.Start(); + try + { + var response = _healthModelRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, healthModelName, 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.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of health model resource. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetIfExistsAsync(string healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var scope = _healthModelClientDiagnostics.CreateScope("HealthModelCollection.GetIfExists"); + scope.Start(); + try + { + var response = await _healthModelRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, healthModelName, cancellationToken: cancellationToken).ConfigureAwait(false); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new HealthModelResource(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.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of health model resource. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual NullableResponse GetIfExists(string healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var scope = _healthModelClientDiagnostics.CreateScope("HealthModelCollection.GetIfExists"); + scope.Start(); + try + { + var response = _healthModelRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, healthModelName, cancellationToken: cancellationToken); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new HealthModelResource(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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelData.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelData.Serialization.cs new file mode 100644 index 000000000000..fa4e2ef3f18b --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelData.Serialization.cs @@ -0,0 +1,196 @@ +// 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.CloudHealth.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + public partial class HealthModelData : 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(HealthModelData)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Properties)) + { + writer.WritePropertyName("properties"u8); + writer.WriteObjectValue(Properties, options); + } + if (Optional.IsDefined(Identity)) + { + writer.WritePropertyName("identity"u8); + var serializeOptions = new JsonSerializerOptions { Converters = { new ManagedServiceIdentityTypeV3Converter() } }; + JsonSerializer.Serialize(writer, Identity, serializeOptions); + } + } + + HealthModelData 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(HealthModelData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeHealthModelData(document.RootElement, options); + } + + internal static HealthModelData DeserializeHealthModelData(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + HealthModelProperties properties = default; + ManagedServiceIdentity identity = 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 = HealthModelProperties.DeserializeHealthModelProperties(property.Value, options); + continue; + } + if (property.NameEquals("identity"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + var serializeOptions = new JsonSerializerOptions { Converters = { new ManagedServiceIdentityTypeV3Converter() } }; + identity = JsonSerializer.Deserialize(property.Value.GetRawText(), serializeOptions); + 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 HealthModelData( + id, + name, + type, + systemData, + tags ?? new ChangeTrackingDictionary(), + location, + properties, + identity, + 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(HealthModelData)} does not support writing '{options.Format}' format."); + } + } + + HealthModelData 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 DeserializeHealthModelData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(HealthModelData)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelData.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelData.cs new file mode 100644 index 000000000000..3032c1886d8d --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelData.cs @@ -0,0 +1,87 @@ +// 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.CloudHealth.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A class representing the HealthModel data model. + /// A HealthModel resource + /// + public partial class HealthModelData : 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 HealthModelData(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. + /// The managed service identities assigned to this resource. + /// Keeps track of any properties unknown to the library. + internal HealthModelData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary tags, AzureLocation location, HealthModelProperties properties, ManagedServiceIdentity identity, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData, tags, location) + { + Properties = properties; + Identity = identity; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal HealthModelData() + { + } + + /// The resource-specific properties for this resource. + public HealthModelProperties Properties { get; set; } + /// The managed service identities assigned to this resource. + public ManagedServiceIdentity Identity { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelResource.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelResource.Serialization.cs new file mode 100644 index 000000000000..c0f8ed4e2d67 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelResource.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.CloudHealth +{ + public partial class HealthModelResource : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); + + HealthModelData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)Data).Create(ref reader, options); + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options); + + HealthModelData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options); + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)Data).GetFormatFromOptions(options); + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelResource.cs new file mode 100644 index 000000000000..9ba31f9bbc3d --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/HealthModelResource.cs @@ -0,0 +1,1052 @@ +// 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.CloudHealth.Models; +using Azure.ResourceManager.Resources; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A Class representing a HealthModel along with the instance operations that can be performed on it. + /// If you have a you can construct a + /// from an instance of using the GetHealthModelResource method. + /// Otherwise you can get one from its parent resource using the GetHealthModel method. + /// + public partial class HealthModelResource : ArmResource + { + /// Generate the resource identifier of a instance. + /// The subscriptionId. + /// The resourceGroupName. + /// The healthModelName. + public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string healthModelName) + { + var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}"; + return new ResourceIdentifier(resourceId); + } + + private readonly ClientDiagnostics _healthModelClientDiagnostics; + private readonly HealthModelsRestOperations _healthModelRestClient; + private readonly HealthModelData _data; + + /// Gets the resource type for the operations. + public static readonly ResourceType ResourceType = "Microsoft.CloudHealth/healthmodels"; + + /// Initializes a new instance of the class for mocking. + protected HealthModelResource() + { + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The resource that is the target of operations. + internal HealthModelResource(ArmClient client, HealthModelData 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 HealthModelResource(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _healthModelClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CloudHealth", ResourceType.Namespace, Diagnostics); + TryGetApiVersion(ResourceType, out string healthModelApiVersion); + _healthModelRestClient = new HealthModelsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, healthModelApiVersion); +#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 HealthModelData 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)); + } + + /// Gets a collection of SignalDefinitionResources in the HealthModel. + /// An object representing collection of SignalDefinitionResources and their operations over a SignalDefinitionResource. + public virtual SignalDefinitionCollection GetSignalDefinitions() + { + return GetCachedClient(client => new SignalDefinitionCollection(client, Id)); + } + + /// + /// Get a SignalDefinition + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the signal definition. Must be unique within a health model. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual async Task> GetSignalDefinitionAsync(string signalDefinitionName, CancellationToken cancellationToken = default) + { + return await GetSignalDefinitions().GetAsync(signalDefinitionName, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a SignalDefinition + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the signal definition. Must be unique within a health model. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual Response GetSignalDefinition(string signalDefinitionName, CancellationToken cancellationToken = default) + { + return GetSignalDefinitions().Get(signalDefinitionName, cancellationToken); + } + + /// Gets a collection of AuthenticationSettingResources in the HealthModel. + /// An object representing collection of AuthenticationSettingResources and their operations over a AuthenticationSettingResource. + public virtual AuthenticationSettingCollection GetAuthenticationSettings() + { + return GetCachedClient(client => new AuthenticationSettingCollection(client, Id)); + } + + /// + /// Get a AuthenticationSetting + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the authentication setting. Must be unique within a health model. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual async Task> GetAuthenticationSettingAsync(string authenticationSettingName, CancellationToken cancellationToken = default) + { + return await GetAuthenticationSettings().GetAsync(authenticationSettingName, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a AuthenticationSetting + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/authenticationsettings/{authenticationSettingName} + /// + /// + /// Operation Id + /// AuthenticationSetting_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the authentication setting. Must be unique within a health model. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual Response GetAuthenticationSetting(string authenticationSettingName, CancellationToken cancellationToken = default) + { + return GetAuthenticationSettings().Get(authenticationSettingName, cancellationToken); + } + + /// Gets a collection of EntityResources in the HealthModel. + /// An object representing collection of EntityResources and their operations over a EntityResource. + public virtual EntityCollection GetEntities() + { + return GetCachedClient(client => new EntityCollection(client, Id)); + } + + /// + /// Get a Entity + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the entity. Must be unique within a health model. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual async Task> GetEntityAsync(string entityName, CancellationToken cancellationToken = default) + { + return await GetEntities().GetAsync(entityName, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a Entity + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/entities/{entityName} + /// + /// + /// Operation Id + /// Entity_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the entity. Must be unique within a health model. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual Response GetEntity(string entityName, CancellationToken cancellationToken = default) + { + return GetEntities().Get(entityName, cancellationToken); + } + + /// Gets a collection of RelationshipResources in the HealthModel. + /// An object representing collection of RelationshipResources and their operations over a RelationshipResource. + public virtual RelationshipCollection GetRelationships() + { + return GetCachedClient(client => new RelationshipCollection(client, Id)); + } + + /// + /// Get a Relationship + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual async Task> GetRelationshipAsync(string relationshipName, CancellationToken cancellationToken = default) + { + return await GetRelationships().GetAsync(relationshipName, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a Relationship + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual Response GetRelationship(string relationshipName, CancellationToken cancellationToken = default) + { + return GetRelationships().Get(relationshipName, cancellationToken); + } + + /// Gets a collection of DiscoveryRuleResources in the HealthModel. + /// An object representing collection of DiscoveryRuleResources and their operations over a DiscoveryRuleResource. + public virtual DiscoveryRuleCollection GetDiscoveryRules() + { + return GetCachedClient(client => new DiscoveryRuleCollection(client, Id)); + } + + /// + /// Get a DiscoveryRule + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the discovery rule. Must be unique within a health model. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual async Task> GetDiscoveryRuleAsync(string discoveryRuleName, CancellationToken cancellationToken = default) + { + return await GetDiscoveryRules().GetAsync(discoveryRuleName, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a DiscoveryRule + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/discoveryrules/{discoveryRuleName} + /// + /// + /// Operation Id + /// DiscoveryRule_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the discovery rule. Must be unique within a health model. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + [ForwardsClientCalls] + public virtual Response GetDiscoveryRule(string discoveryRuleName, CancellationToken cancellationToken = default) + { + return GetDiscoveryRules().Get(discoveryRuleName, cancellationToken); + } + + /// + /// Get a HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual async Task> GetAsync(CancellationToken cancellationToken = default) + { + using var scope = _healthModelClientDiagnostics.CreateScope("HealthModelResource.Get"); + scope.Start(); + try + { + var response = await _healthModelRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new HealthModelResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual Response Get(CancellationToken cancellationToken = default) + { + using var scope = _healthModelClientDiagnostics.CreateScope("HealthModelResource.Get"); + scope.Start(); + try + { + var response = _healthModelRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new HealthModelResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Delete + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _healthModelClientDiagnostics.CreateScope("HealthModelResource.Delete"); + scope.Start(); + try + { + var response = await _healthModelRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); + var operation = new CloudHealthArmOperation(_healthModelClientDiagnostics, Pipeline, _healthModelRestClient.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 HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Delete + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _healthModelClientDiagnostics.CreateScope("HealthModelResource.Delete"); + scope.Start(); + try + { + var response = _healthModelRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); + var operation = new CloudHealthArmOperation(_healthModelClientDiagnostics, Pipeline, _healthModelRestClient.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 HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Update + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 resource properties to be updated. + /// The cancellation token to use. + /// is null. + public virtual async Task> UpdateAsync(WaitUntil waitUntil, HealthModelPatch patch, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(patch, nameof(patch)); + + using var scope = _healthModelClientDiagnostics.CreateScope("HealthModelResource.Update"); + scope.Start(); + try + { + var response = await _healthModelRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch, cancellationToken).ConfigureAwait(false); + var operation = new CloudHealthArmOperation(new HealthModelOperationSource(Client), _healthModelClientDiagnostics, Pipeline, _healthModelRestClient.CreateUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch).Request, response, OperationFinalStateVia.Location); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Update a HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Update + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 resource properties to be updated. + /// The cancellation token to use. + /// is null. + public virtual ArmOperation Update(WaitUntil waitUntil, HealthModelPatch patch, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(patch, nameof(patch)); + + using var scope = _healthModelClientDiagnostics.CreateScope("HealthModelResource.Update"); + scope.Start(); + try + { + var response = _healthModelRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch, cancellationToken); + var operation = new CloudHealthArmOperation(new HealthModelOperationSource(Client), _healthModelClientDiagnostics, Pipeline, _healthModelRestClient.CreateUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch).Request, response, OperationFinalStateVia.Location); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Add a tag to the current resource. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _healthModelClientDiagnostics.CreateScope("HealthModelResource.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 _healthModelRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); + return Response.FromValue(new HealthModelResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); + } + else + { + var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; + var patch = new HealthModelPatch(); + foreach (var tag in current.Tags) + { + patch.Tags.Add(tag); + } + patch.Tags[key] = value; + var result = await UpdateAsync(WaitUntil.Completed, patch, cancellationToken: cancellationToken).ConfigureAwait(false); + return Response.FromValue(result.Value, result.GetRawResponse()); + } + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Add a tag to the current resource. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _healthModelClientDiagnostics.CreateScope("HealthModelResource.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 = _healthModelRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); + return Response.FromValue(new HealthModelResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); + } + else + { + var current = Get(cancellationToken: cancellationToken).Value.Data; + var patch = new HealthModelPatch(); + foreach (var tag in current.Tags) + { + patch.Tags.Add(tag); + } + patch.Tags[key] = value; + var result = Update(WaitUntil.Completed, patch, cancellationToken: cancellationToken); + return Response.FromValue(result.Value, result.GetRawResponse()); + } + } + 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.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _healthModelClientDiagnostics.CreateScope("HealthModelResource.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 _healthModelRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); + return Response.FromValue(new HealthModelResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); + } + else + { + var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; + var patch = new HealthModelPatch(); + patch.Tags.ReplaceWith(tags); + var result = await UpdateAsync(WaitUntil.Completed, patch, cancellationToken: cancellationToken).ConfigureAwait(false); + return Response.FromValue(result.Value, result.GetRawResponse()); + } + } + 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.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _healthModelClientDiagnostics.CreateScope("HealthModelResource.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 = _healthModelRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); + return Response.FromValue(new HealthModelResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); + } + else + { + var current = Get(cancellationToken: cancellationToken).Value.Data; + var patch = new HealthModelPatch(); + patch.Tags.ReplaceWith(tags); + var result = Update(WaitUntil.Completed, patch, cancellationToken: cancellationToken); + return Response.FromValue(result.Value, result.GetRawResponse()); + } + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Removes a tag by key from the resource. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _healthModelClientDiagnostics.CreateScope("HealthModelResource.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 _healthModelRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); + return Response.FromValue(new HealthModelResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); + } + else + { + var current = (await GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false)).Value.Data; + var patch = new HealthModelPatch(); + foreach (var tag in current.Tags) + { + patch.Tags.Add(tag); + } + patch.Tags.Remove(key); + var result = await UpdateAsync(WaitUntil.Completed, patch, cancellationToken: cancellationToken).ConfigureAwait(false); + return Response.FromValue(result.Value, result.GetRawResponse()); + } + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Removes a tag by key from the resource. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName} + /// + /// + /// Operation Id + /// HealthModel_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _healthModelClientDiagnostics.CreateScope("HealthModelResource.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 = _healthModelRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); + return Response.FromValue(new HealthModelResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); + } + else + { + var current = Get(cancellationToken: cancellationToken).Value.Data; + var patch = new HealthModelPatch(); + foreach (var tag in current.Tags) + { + patch.Tags.Add(tag); + } + patch.Tags.Remove(key); + var result = Update(WaitUntil.Completed, patch, cancellationToken: cancellationToken); + return Response.FromValue(result.Value, result.GetRawResponse()); + } + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Internal/Argument.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Internal/Argument.cs new file mode 100644 index 000000000000..4d8bad4d919d --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/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.CloudHealth +{ + 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 000000000000..91e0538b29e7 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/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.CloudHealth +{ + 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Internal/ChangeTrackingList.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 000000000000..f6508831391e --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/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.CloudHealth +{ + 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 000000000000..17d6b270d305 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/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.CloudHealth +{ + 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Internal/Optional.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Internal/Optional.cs new file mode 100644 index 000000000000..b0b9ae29722f --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/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.CloudHealth +{ + 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 000000000000..45f0ed4fe1cc --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/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.CloudHealth +{ + 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/LongRunningOperation/CloudHealthArmOperation.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/LongRunningOperation/CloudHealthArmOperation.cs new file mode 100644 index 000000000000..00bbff257543 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/LongRunningOperation/CloudHealthArmOperation.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.CloudHealth +{ +#pragma warning disable SA1649 // File name should match first type name + internal class CloudHealthArmOperation : 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 CloudHealthArmOperation for mocking. + protected CloudHealthArmOperation() + { + } + + internal CloudHealthArmOperation(Response response, RehydrationToken? rehydrationToken = null) + { + _operation = OperationInternal.Succeeded(response); + _completeRehydrationToken = rehydrationToken; + _operationId = GetOperationId(rehydrationToken); + } + + internal CloudHealthArmOperation(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, "CloudHealthArmOperation", 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/LongRunningOperation/CloudHealthArmOperationOfT.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/LongRunningOperation/CloudHealthArmOperationOfT.cs new file mode 100644 index 000000000000..41836328da3a --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/LongRunningOperation/CloudHealthArmOperationOfT.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.CloudHealth +{ +#pragma warning disable SA1649 // File name should match first type name + internal class CloudHealthArmOperation : 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 CloudHealthArmOperation for mocking. + protected CloudHealthArmOperation() + { + } + + internal CloudHealthArmOperation(Response response, RehydrationToken? rehydrationToken = null) + { + _operation = OperationInternal.Succeeded(response.GetRawResponse(), response.Value); + _completeRehydrationToken = rehydrationToken; + _operationId = GetOperationId(rehydrationToken); + } + + internal CloudHealthArmOperation(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, "CloudHealthArmOperation", 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/LongRunningOperation/HealthModelOperationSource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/LongRunningOperation/HealthModelOperationSource.cs new file mode 100644 index 000000000000..0ff104720533 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/LongRunningOperation/HealthModelOperationSource.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.CloudHealth +{ + internal class HealthModelOperationSource : IOperationSource + { + private readonly ArmClient _client; + + internal HealthModelOperationSource(ArmClient client) + { + _client = client; + } + + HealthModelResource IOperationSource.CreateResult(Response response, CancellationToken cancellationToken) + { + var data = ModelReaderWriter.Read(response.Content); + return new HealthModelResource(_client, data); + } + + async ValueTask IOperationSource.CreateResultAsync(Response response, CancellationToken cancellationToken) + { + var data = ModelReaderWriter.Read(response.Content); + return await Task.FromResult(new HealthModelResource(_client, data)).ConfigureAwait(false); + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AlertConfiguration.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AlertConfiguration.Serialization.cs new file mode 100644 index 000000000000..e6b11b967056 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AlertConfiguration.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.CloudHealth.Models +{ + public partial class AlertConfiguration : 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(AlertConfiguration)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("severity"u8); + writer.WriteStringValue(Severity.ToString()); + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + if (Optional.IsCollectionDefined(ActionGroupIds)) + { + writer.WritePropertyName("actionGroupIds"u8); + writer.WriteStartArray(); + foreach (var item in ActionGroupIds) + { + if (item == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteStringValue(item); + } + 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 + } + } + } + + AlertConfiguration 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(AlertConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAlertConfiguration(document.RootElement, options); + } + + internal static AlertConfiguration DeserializeAlertConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AlertSeverity severity = default; + string description = default; + IList actionGroupIds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("severity"u8)) + { + severity = new AlertSeverity(property.Value.GetString()); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("actionGroupIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(new ResourceIdentifier(item.GetString())); + } + } + actionGroupIds = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AlertConfiguration(severity, description, actionGroupIds ?? new ChangeTrackingList(), 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(AlertConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AlertConfiguration 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 DeserializeAlertConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AlertConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AlertConfiguration.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AlertConfiguration.cs new file mode 100644 index 000000000000..082537eb6f59 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AlertConfiguration.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Alert configuration details. + public partial class AlertConfiguration + { + /// + /// 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 severity of triggered alert. + public AlertConfiguration(AlertSeverity severity) + { + Severity = severity; + ActionGroupIds = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The severity of triggered alert. + /// The alert rule description. + /// Optional list of action group resource IDs to be notified when the alert is triggered. + /// Keeps track of any properties unknown to the library. + internal AlertConfiguration(AlertSeverity severity, string description, IList actionGroupIds, IDictionary serializedAdditionalRawData) + { + Severity = severity; + Description = description; + ActionGroupIds = actionGroupIds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AlertConfiguration() + { + } + + /// The severity of triggered alert. + public AlertSeverity Severity { get; set; } + /// The alert rule description. + public string Description { get; set; } + /// Optional list of action group resource IDs to be notified when the alert is triggered. + public IList ActionGroupIds { get; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AlertSeverity.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AlertSeverity.cs new file mode 100644 index 000000000000..05d3079dfbee --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AlertSeverity.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.ResourceManager.CloudHealth.Models +{ + /// Severity of an alert. + public readonly partial struct AlertSeverity : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AlertSeverity(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string Sev0Value = "Sev0"; + private const string Sev1Value = "Sev1"; + private const string Sev2Value = "Sev2"; + private const string Sev3Value = "Sev3"; + private const string Sev4Value = "Sev4"; + + /// Critical. + public static AlertSeverity Sev0 { get; } = new AlertSeverity(Sev0Value); + /// Error. + public static AlertSeverity Sev1 { get; } = new AlertSeverity(Sev1Value); + /// Warning. + public static AlertSeverity Sev2 { get; } = new AlertSeverity(Sev2Value); + /// Informational. + public static AlertSeverity Sev3 { get; } = new AlertSeverity(Sev3Value); + /// Verbose. + public static AlertSeverity Sev4 { get; } = new AlertSeverity(Sev4Value); + /// Determines if two values are the same. + public static bool operator ==(AlertSeverity left, AlertSeverity right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AlertSeverity left, AlertSeverity right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AlertSeverity(string value) => new AlertSeverity(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AlertSeverity other && Equals(other); + /// + public bool Equals(AlertSeverity 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationKind.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationKind.cs new file mode 100644 index 000000000000..eb9393767ef4 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationKind.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Supported kinds of authentication settings as discriminator. + internal readonly partial struct AuthenticationKind : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AuthenticationKind(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ManagedIdentityValue = "ManagedIdentity"; + + /// ManagedIdentity. + public static AuthenticationKind ManagedIdentity { get; } = new AuthenticationKind(ManagedIdentityValue); + /// Determines if two values are the same. + public static bool operator ==(AuthenticationKind left, AuthenticationKind right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AuthenticationKind left, AuthenticationKind right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AuthenticationKind(string value) => new AuthenticationKind(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AuthenticationKind other && Equals(other); + /// + public bool Equals(AuthenticationKind 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationSettingListResult.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationSettingListResult.Serialization.cs new file mode 100644 index 000000000000..b74f9054133a --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationSettingListResult.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.CloudHealth.Models +{ + internal partial class AuthenticationSettingListResult : 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(AuthenticationSettingListResult)} 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 + } + } + } + + AuthenticationSettingListResult 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(AuthenticationSettingListResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAuthenticationSettingListResult(document.RootElement, options); + } + + internal static AuthenticationSettingListResult DeserializeAuthenticationSettingListResult(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(AuthenticationSettingData.DeserializeAuthenticationSettingData(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 AuthenticationSettingListResult(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(AuthenticationSettingListResult)} does not support writing '{options.Format}' format."); + } + } + + AuthenticationSettingListResult 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 DeserializeAuthenticationSettingListResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AuthenticationSettingListResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationSettingListResult.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationSettingListResult.cs new file mode 100644 index 000000000000..728b21da19da --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationSettingListResult.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.CloudHealth.Models +{ + /// The response of a AuthenticationSetting list operation. + internal partial class AuthenticationSettingListResult + { + /// + /// 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 AuthenticationSetting items on this page. + /// is null. + internal AuthenticationSettingListResult(IEnumerable value) + { + Argument.AssertNotNull(value, nameof(value)); + + Value = value.ToList(); + } + + /// Initializes a new instance of . + /// The AuthenticationSetting items on this page. + /// The link to the next page of items. + /// Keeps track of any properties unknown to the library. + internal AuthenticationSettingListResult(IReadOnlyList value, Uri nextLink, IDictionary serializedAdditionalRawData) + { + Value = value; + NextLink = nextLink; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AuthenticationSettingListResult() + { + } + + /// The AuthenticationSetting items on this page. + public IReadOnlyList Value { get; } + /// The link to the next page of items. + public Uri NextLink { get; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationSettingProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationSettingProperties.Serialization.cs new file mode 100644 index 000000000000..7e7ba17c45de --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationSettingProperties.Serialization.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + [PersistableModelProxy(typeof(UnknownAuthenticationSettingProperties))] + public partial class AuthenticationSettingProperties : 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(AuthenticationSettingProperties)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(ProvisioningState)) + { + writer.WritePropertyName("provisioningState"u8); + writer.WriteStringValue(ProvisioningState.Value.ToString()); + } + if (Optional.IsDefined(DisplayName)) + { + writer.WritePropertyName("displayName"u8); + writer.WriteStringValue(DisplayName); + } + writer.WritePropertyName("authenticationKind"u8); + writer.WriteStringValue(AuthenticationKind.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 + } + } + } + + AuthenticationSettingProperties 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(AuthenticationSettingProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAuthenticationSettingProperties(document.RootElement, options); + } + + internal static AuthenticationSettingProperties DeserializeAuthenticationSettingProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("authenticationKind", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "ManagedIdentity": return ManagedIdentityAuthenticationSettingProperties.DeserializeManagedIdentityAuthenticationSettingProperties(element, options); + } + } + return UnknownAuthenticationSettingProperties.DeserializeUnknownAuthenticationSettingProperties(element, options); + } + + 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(AuthenticationSettingProperties)} does not support writing '{options.Format}' format."); + } + } + + AuthenticationSettingProperties 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 DeserializeAuthenticationSettingProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AuthenticationSettingProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationSettingProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationSettingProperties.cs new file mode 100644 index 000000000000..f6d514fa30f9 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AuthenticationSettingProperties.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.CloudHealth.Models +{ + /// + /// Authentication setting properties + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public abstract partial class AuthenticationSettingProperties + { + /// + /// 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 protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected AuthenticationSettingProperties() + { + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Kind of the authentication setting. + /// Keeps track of any properties unknown to the library. + internal AuthenticationSettingProperties(HealthModelProvisioningState? provisioningState, string displayName, AuthenticationKind authenticationKind, IDictionary serializedAdditionalRawData) + { + ProvisioningState = provisioningState; + DisplayName = displayName; + AuthenticationKind = authenticationKind; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The status of the last operation. + public HealthModelProvisioningState? ProvisioningState { get; } + /// Display name. + public string DisplayName { get; set; } + /// Kind of the authentication setting. + internal AuthenticationKind AuthenticationKind { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AzureMonitorWorkspaceSignalGroup.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AzureMonitorWorkspaceSignalGroup.Serialization.cs new file mode 100644 index 000000000000..512feee26ada --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AzureMonitorWorkspaceSignalGroup.Serialization.cs @@ -0,0 +1,159 @@ +// 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.CloudHealth.Models +{ + public partial class AzureMonitorWorkspaceSignalGroup : 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(AzureMonitorWorkspaceSignalGroup)} does not support writing '{format}' format."); + } + + if (Optional.IsCollectionDefined(SignalAssignments)) + { + writer.WritePropertyName("signalAssignments"u8); + writer.WriteStartArray(); + foreach (var item in SignalAssignments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + writer.WritePropertyName("authenticationSetting"u8); + writer.WriteStringValue(AuthenticationSetting); + writer.WritePropertyName("azureMonitorWorkspaceResourceId"u8); + writer.WriteStringValue(AzureMonitorWorkspaceResourceId); + 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 + } + } + } + + AzureMonitorWorkspaceSignalGroup 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(AzureMonitorWorkspaceSignalGroup)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureMonitorWorkspaceSignalGroup(document.RootElement, options); + } + + internal static AzureMonitorWorkspaceSignalGroup DeserializeAzureMonitorWorkspaceSignalGroup(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList signalAssignments = default; + string authenticationSetting = default; + ResourceIdentifier azureMonitorWorkspaceResourceId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("signalAssignments"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(SignalAssignment.DeserializeSignalAssignment(item, options)); + } + signalAssignments = array; + continue; + } + if (property.NameEquals("authenticationSetting"u8)) + { + authenticationSetting = property.Value.GetString(); + continue; + } + if (property.NameEquals("azureMonitorWorkspaceResourceId"u8)) + { + azureMonitorWorkspaceResourceId = new ResourceIdentifier(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureMonitorWorkspaceSignalGroup(signalAssignments ?? new ChangeTrackingList(), authenticationSetting, azureMonitorWorkspaceResourceId, 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(AzureMonitorWorkspaceSignalGroup)} does not support writing '{options.Format}' format."); + } + } + + AzureMonitorWorkspaceSignalGroup 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 DeserializeAzureMonitorWorkspaceSignalGroup(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureMonitorWorkspaceSignalGroup)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AzureMonitorWorkspaceSignalGroup.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AzureMonitorWorkspaceSignalGroup.cs new file mode 100644 index 000000000000..bb6e3954f1cc --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AzureMonitorWorkspaceSignalGroup.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// A grouping of signal assignments for a Azure Monitor Workspace. + public partial class AzureMonitorWorkspaceSignalGroup + { + /// + /// 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 . + /// Reference to the name of the authentication setting which is used for querying the data source. + /// Azure Monitor workspace resource ID. + /// or is null. + public AzureMonitorWorkspaceSignalGroup(string authenticationSetting, ResourceIdentifier azureMonitorWorkspaceResourceId) + { + Argument.AssertNotNull(authenticationSetting, nameof(authenticationSetting)); + Argument.AssertNotNull(azureMonitorWorkspaceResourceId, nameof(azureMonitorWorkspaceResourceId)); + + SignalAssignments = new ChangeTrackingList(); + AuthenticationSetting = authenticationSetting; + AzureMonitorWorkspaceResourceId = azureMonitorWorkspaceResourceId; + } + + /// Initializes a new instance of . + /// Signal definitions which are assigned to this signal group. All assignments are combined with an OR operator. + /// Reference to the name of the authentication setting which is used for querying the data source. + /// Azure Monitor workspace resource ID. + /// Keeps track of any properties unknown to the library. + internal AzureMonitorWorkspaceSignalGroup(IList signalAssignments, string authenticationSetting, ResourceIdentifier azureMonitorWorkspaceResourceId, IDictionary serializedAdditionalRawData) + { + SignalAssignments = signalAssignments; + AuthenticationSetting = authenticationSetting; + AzureMonitorWorkspaceResourceId = azureMonitorWorkspaceResourceId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureMonitorWorkspaceSignalGroup() + { + } + + /// Signal definitions which are assigned to this signal group. All assignments are combined with an OR operator. + public IList SignalAssignments { get; } + /// Reference to the name of the authentication setting which is used for querying the data source. + public string AuthenticationSetting { get; set; } + /// Azure Monitor workspace resource ID. + public ResourceIdentifier AzureMonitorWorkspaceResourceId { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AzureResourceSignalGroup.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AzureResourceSignalGroup.Serialization.cs new file mode 100644 index 000000000000..8fe0a614c85e --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AzureResourceSignalGroup.Serialization.cs @@ -0,0 +1,159 @@ +// 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.CloudHealth.Models +{ + public partial class AzureResourceSignalGroup : 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(AzureResourceSignalGroup)} does not support writing '{format}' format."); + } + + if (Optional.IsCollectionDefined(SignalAssignments)) + { + writer.WritePropertyName("signalAssignments"u8); + writer.WriteStartArray(); + foreach (var item in SignalAssignments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + writer.WritePropertyName("authenticationSetting"u8); + writer.WriteStringValue(AuthenticationSetting); + writer.WritePropertyName("azureResourceId"u8); + writer.WriteStringValue(AzureResourceId); + 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 + } + } + } + + AzureResourceSignalGroup 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(AzureResourceSignalGroup)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureResourceSignalGroup(document.RootElement, options); + } + + internal static AzureResourceSignalGroup DeserializeAzureResourceSignalGroup(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList signalAssignments = default; + string authenticationSetting = default; + ResourceIdentifier azureResourceId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("signalAssignments"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(SignalAssignment.DeserializeSignalAssignment(item, options)); + } + signalAssignments = array; + continue; + } + if (property.NameEquals("authenticationSetting"u8)) + { + authenticationSetting = property.Value.GetString(); + continue; + } + if (property.NameEquals("azureResourceId"u8)) + { + azureResourceId = new ResourceIdentifier(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureResourceSignalGroup(signalAssignments ?? new ChangeTrackingList(), authenticationSetting, azureResourceId, 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(AzureResourceSignalGroup)} does not support writing '{options.Format}' format."); + } + } + + AzureResourceSignalGroup 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 DeserializeAzureResourceSignalGroup(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureResourceSignalGroup)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AzureResourceSignalGroup.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AzureResourceSignalGroup.cs new file mode 100644 index 000000000000..3bd3db0a9d0d --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/AzureResourceSignalGroup.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// A grouping of signal assignments for an Azure resource. + public partial class AzureResourceSignalGroup + { + /// + /// 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 . + /// Reference to the name of the authentication setting which is used for querying the data source. + /// Azure resource ID. + /// or is null. + public AzureResourceSignalGroup(string authenticationSetting, ResourceIdentifier azureResourceId) + { + Argument.AssertNotNull(authenticationSetting, nameof(authenticationSetting)); + Argument.AssertNotNull(azureResourceId, nameof(azureResourceId)); + + SignalAssignments = new ChangeTrackingList(); + AuthenticationSetting = authenticationSetting; + AzureResourceId = azureResourceId; + } + + /// Initializes a new instance of . + /// Signal definitions which are assigned to this signal group. All assignments are combined with an OR operator. + /// Reference to the name of the authentication setting which is used for querying the data source. + /// Azure resource ID. + /// Keeps track of any properties unknown to the library. + internal AzureResourceSignalGroup(IList signalAssignments, string authenticationSetting, ResourceIdentifier azureResourceId, IDictionary serializedAdditionalRawData) + { + SignalAssignments = signalAssignments; + AuthenticationSetting = authenticationSetting; + AzureResourceId = azureResourceId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureResourceSignalGroup() + { + } + + /// Signal definitions which are assigned to this signal group. All assignments are combined with an OR operator. + public IList SignalAssignments { get; } + /// Reference to the name of the authentication setting which is used for querying the data source. + public string AuthenticationSetting { get; set; } + /// Azure resource ID. + public ResourceIdentifier AzureResourceId { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DependenciesAggregationType.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DependenciesAggregationType.cs new file mode 100644 index 000000000000..874025b4ae21 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DependenciesAggregationType.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Aggregation type for child dependencies. + public readonly partial struct DependenciesAggregationType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DependenciesAggregationType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string WorstOfValue = "WorstOf"; + private const string ThresholdsValue = "Thresholds"; + + /// Default behavior: Worst child health state is propagated. + public static DependenciesAggregationType WorstOf { get; } = new DependenciesAggregationType(WorstOfValue); + /// Based on configurable thresholds. + public static DependenciesAggregationType Thresholds { get; } = new DependenciesAggregationType(ThresholdsValue); + /// Determines if two values are the same. + public static bool operator ==(DependenciesAggregationType left, DependenciesAggregationType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DependenciesAggregationType left, DependenciesAggregationType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DependenciesAggregationType(string value) => new DependenciesAggregationType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DependenciesAggregationType other && Equals(other); + /// + public bool Equals(DependenciesAggregationType 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DependenciesSignalGroup.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DependenciesSignalGroup.Serialization.cs new file mode 100644 index 000000000000..2f15703e5720 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DependenciesSignalGroup.Serialization.cs @@ -0,0 +1,148 @@ +// 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.CloudHealth.Models +{ + public partial class DependenciesSignalGroup : 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(DependenciesSignalGroup)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("aggregationType"u8); + writer.WriteStringValue(AggregationType.ToString()); + if (Optional.IsDefined(DegradedThreshold)) + { + writer.WritePropertyName("degradedThreshold"u8); + writer.WriteStringValue(DegradedThreshold); + } + if (Optional.IsDefined(UnhealthyThreshold)) + { + writer.WritePropertyName("unhealthyThreshold"u8); + writer.WriteStringValue(UnhealthyThreshold); + } + 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 + } + } + } + + DependenciesSignalGroup 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(DependenciesSignalGroup)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDependenciesSignalGroup(document.RootElement, options); + } + + internal static DependenciesSignalGroup DeserializeDependenciesSignalGroup(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + DependenciesAggregationType aggregationType = default; + string degradedThreshold = default; + string unhealthyThreshold = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("aggregationType"u8)) + { + aggregationType = new DependenciesAggregationType(property.Value.GetString()); + continue; + } + if (property.NameEquals("degradedThreshold"u8)) + { + degradedThreshold = property.Value.GetString(); + continue; + } + if (property.NameEquals("unhealthyThreshold"u8)) + { + unhealthyThreshold = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new DependenciesSignalGroup(aggregationType, degradedThreshold, unhealthyThreshold, 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(DependenciesSignalGroup)} does not support writing '{options.Format}' format."); + } + } + + DependenciesSignalGroup 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 DeserializeDependenciesSignalGroup(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DependenciesSignalGroup)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DependenciesSignalGroup.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DependenciesSignalGroup.cs new file mode 100644 index 000000000000..d7cb03549538 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DependenciesSignalGroup.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; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Properties for dependent entities, i.e. child entities. + public partial class DependenciesSignalGroup + { + /// + /// 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 . + /// Aggregation type for child dependencies. + public DependenciesSignalGroup(DependenciesAggregationType aggregationType) + { + AggregationType = aggregationType; + } + + /// Initializes a new instance of . + /// Aggregation type for child dependencies. + /// Degraded threshold for aggregating the propagated health state of child dependencies. Can be either an absolute number that is greater than 0, or a percentage between 1-100%. The entity will be considered degraded when the number of not healthy child dependents (unhealthy, degraded, unknown) is equal to or above the threshold value. Must only be set when AggregationType is 'Thresholds'. + /// Unhealthy threshold for aggregating the propagated health state of child dependencies. Can be either an absolute number that is greater than 0, or a percentage between 1-100%. The entity will be considered unhealthy when the number of not healthy child dependents (unhealthy, degraded, unknown) is equal to or above the threshold value. Must only be set when AggregationType is 'Thresholds'. + /// Keeps track of any properties unknown to the library. + internal DependenciesSignalGroup(DependenciesAggregationType aggregationType, string degradedThreshold, string unhealthyThreshold, IDictionary serializedAdditionalRawData) + { + AggregationType = aggregationType; + DegradedThreshold = degradedThreshold; + UnhealthyThreshold = unhealthyThreshold; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DependenciesSignalGroup() + { + } + + /// Aggregation type for child dependencies. + public DependenciesAggregationType AggregationType { get; set; } + /// Degraded threshold for aggregating the propagated health state of child dependencies. Can be either an absolute number that is greater than 0, or a percentage between 1-100%. The entity will be considered degraded when the number of not healthy child dependents (unhealthy, degraded, unknown) is equal to or above the threshold value. Must only be set when AggregationType is 'Thresholds'. + public string DegradedThreshold { get; set; } + /// Unhealthy threshold for aggregating the propagated health state of child dependencies. Can be either an absolute number that is greater than 0, or a percentage between 1-100%. The entity will be considered unhealthy when the number of not healthy child dependents (unhealthy, degraded, unknown) is equal to or above the threshold value. Must only be set when AggregationType is 'Thresholds'. + public string UnhealthyThreshold { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleListResult.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleListResult.Serialization.cs new file mode 100644 index 000000000000..74327bab3c4c --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleListResult.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.CloudHealth.Models +{ + internal partial class DiscoveryRuleListResult : 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(DiscoveryRuleListResult)} 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 + } + } + } + + DiscoveryRuleListResult 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(DiscoveryRuleListResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDiscoveryRuleListResult(document.RootElement, options); + } + + internal static DiscoveryRuleListResult DeserializeDiscoveryRuleListResult(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(DiscoveryRuleData.DeserializeDiscoveryRuleData(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 DiscoveryRuleListResult(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(DiscoveryRuleListResult)} does not support writing '{options.Format}' format."); + } + } + + DiscoveryRuleListResult 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 DeserializeDiscoveryRuleListResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DiscoveryRuleListResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleListResult.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleListResult.cs new file mode 100644 index 000000000000..b386a0975b7a --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleListResult.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.CloudHealth.Models +{ + /// The response of a DiscoveryRule list operation. + internal partial class DiscoveryRuleListResult + { + /// + /// 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 DiscoveryRule items on this page. + /// is null. + internal DiscoveryRuleListResult(IEnumerable value) + { + Argument.AssertNotNull(value, nameof(value)); + + Value = value.ToList(); + } + + /// Initializes a new instance of . + /// The DiscoveryRule items on this page. + /// The link to the next page of items. + /// Keeps track of any properties unknown to the library. + internal DiscoveryRuleListResult(IReadOnlyList value, Uri nextLink, IDictionary serializedAdditionalRawData) + { + Value = value; + NextLink = nextLink; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DiscoveryRuleListResult() + { + } + + /// The DiscoveryRule items on this page. + public IReadOnlyList Value { get; } + /// The link to the next page of items. + public Uri NextLink { get; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleProperties.Serialization.cs new file mode 100644 index 000000000000..6447630c8d21 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleProperties.Serialization.cs @@ -0,0 +1,239 @@ +// 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.CloudHealth.Models +{ + public partial class DiscoveryRuleProperties : 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(DiscoveryRuleProperties)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(ProvisioningState)) + { + writer.WritePropertyName("provisioningState"u8); + writer.WriteStringValue(ProvisioningState.Value.ToString()); + } + if (Optional.IsDefined(DisplayName)) + { + writer.WritePropertyName("displayName"u8); + writer.WriteStringValue(DisplayName); + } + writer.WritePropertyName("resourceGraphQuery"u8); + writer.WriteStringValue(ResourceGraphQuery); + writer.WritePropertyName("authenticationSetting"u8); + writer.WriteStringValue(AuthenticationSetting); + writer.WritePropertyName("discoverRelationships"u8); + writer.WriteStringValue(DiscoverRelationships.ToString()); + writer.WritePropertyName("addRecommendedSignals"u8); + writer.WriteStringValue(AddRecommendedSignals.ToString()); + if (options.Format != "W" && Optional.IsDefined(DeletedOn)) + { + writer.WritePropertyName("deletionDate"u8); + writer.WriteStringValue(DeletedOn.Value, "O"); + } + if (options.Format != "W" && Optional.IsDefined(ErrorMessage)) + { + writer.WritePropertyName("errorMessage"u8); + writer.WriteStringValue(ErrorMessage); + } + if (options.Format != "W" && Optional.IsDefined(NumberOfDiscoveredEntities)) + { + writer.WritePropertyName("numberOfDiscoveredEntities"u8); + writer.WriteNumberValue(NumberOfDiscoveredEntities.Value); + } + if (options.Format != "W") + { + writer.WritePropertyName("entityName"u8); + writer.WriteStringValue(EntityName); + } + 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 + } + } + } + + DiscoveryRuleProperties 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(DiscoveryRuleProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDiscoveryRuleProperties(document.RootElement, options); + } + + internal static DiscoveryRuleProperties DeserializeDiscoveryRuleProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + HealthModelProvisioningState? provisioningState = default; + string displayName = default; + string resourceGraphQuery = default; + string authenticationSetting = default; + DiscoveryRuleRelationshipDiscoveryBehavior discoverRelationships = default; + DiscoveryRuleRecommendedSignalsBehavior addRecommendedSignals = default; + DateTimeOffset? deletionDate = default; + string errorMessage = default; + int? numberOfDiscoveredEntities = default; + string entityName = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("provisioningState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + provisioningState = new HealthModelProvisioningState(property.Value.GetString()); + continue; + } + if (property.NameEquals("displayName"u8)) + { + displayName = property.Value.GetString(); + continue; + } + if (property.NameEquals("resourceGraphQuery"u8)) + { + resourceGraphQuery = property.Value.GetString(); + continue; + } + if (property.NameEquals("authenticationSetting"u8)) + { + authenticationSetting = property.Value.GetString(); + continue; + } + if (property.NameEquals("discoverRelationships"u8)) + { + discoverRelationships = new DiscoveryRuleRelationshipDiscoveryBehavior(property.Value.GetString()); + continue; + } + if (property.NameEquals("addRecommendedSignals"u8)) + { + addRecommendedSignals = new DiscoveryRuleRecommendedSignalsBehavior(property.Value.GetString()); + continue; + } + if (property.NameEquals("deletionDate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + deletionDate = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("errorMessage"u8)) + { + errorMessage = property.Value.GetString(); + continue; + } + if (property.NameEquals("numberOfDiscoveredEntities"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + numberOfDiscoveredEntities = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("entityName"u8)) + { + entityName = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new DiscoveryRuleProperties( + provisioningState, + displayName, + resourceGraphQuery, + authenticationSetting, + discoverRelationships, + addRecommendedSignals, + deletionDate, + errorMessage, + numberOfDiscoveredEntities, + entityName, + 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(DiscoveryRuleProperties)} does not support writing '{options.Format}' format."); + } + } + + DiscoveryRuleProperties 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 DeserializeDiscoveryRuleProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DiscoveryRuleProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleProperties.cs new file mode 100644 index 000000000000..a4f1dc40bafd --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleProperties.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Discovery rule properties. + public partial class DiscoveryRuleProperties + { + /// + /// 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 . + /// Azure Resource Graph query text in KQL syntax. The query must return at least a column named 'id' which contains the resource ID of the discovered resources. + /// Reference to the name of the authentication setting which is used for querying Azure Resource Graph. The same authentication setting will also be assigned to any discovered entities. + /// Whether to create relationships between the discovered entities based on a set of built-in rules. These relationships cannot be manually deleted. + /// Whether to add all recommended signals to the discovered entities. + /// Name of the entity which represents the discovery rule. Note: It might take a few minutes after creating the discovery rule until the entity is created. + /// or is null. + public DiscoveryRuleProperties(string resourceGraphQuery, string authenticationSetting, DiscoveryRuleRelationshipDiscoveryBehavior discoverRelationships, DiscoveryRuleRecommendedSignalsBehavior addRecommendedSignals, string entityName) + { + Argument.AssertNotNull(resourceGraphQuery, nameof(resourceGraphQuery)); + Argument.AssertNotNull(authenticationSetting, nameof(authenticationSetting)); + + ResourceGraphQuery = resourceGraphQuery; + AuthenticationSetting = authenticationSetting; + DiscoverRelationships = discoverRelationships; + AddRecommendedSignals = addRecommendedSignals; + EntityName = entityName; + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Azure Resource Graph query text in KQL syntax. The query must return at least a column named 'id' which contains the resource ID of the discovered resources. + /// Reference to the name of the authentication setting which is used for querying Azure Resource Graph. The same authentication setting will also be assigned to any discovered entities. + /// Whether to create relationships between the discovered entities based on a set of built-in rules. These relationships cannot be manually deleted. + /// Whether to add all recommended signals to the discovered entities. + /// Date when the discovery rule was (soft-)deleted. + /// Error message if the last discovery operation failed. + /// Number of discovered entities in the last discovery operation. + /// Name of the entity which represents the discovery rule. Note: It might take a few minutes after creating the discovery rule until the entity is created. + /// Keeps track of any properties unknown to the library. + internal DiscoveryRuleProperties(HealthModelProvisioningState? provisioningState, string displayName, string resourceGraphQuery, string authenticationSetting, DiscoveryRuleRelationshipDiscoveryBehavior discoverRelationships, DiscoveryRuleRecommendedSignalsBehavior addRecommendedSignals, DateTimeOffset? deletedOn, string errorMessage, int? numberOfDiscoveredEntities, string entityName, IDictionary serializedAdditionalRawData) + { + ProvisioningState = provisioningState; + DisplayName = displayName; + ResourceGraphQuery = resourceGraphQuery; + AuthenticationSetting = authenticationSetting; + DiscoverRelationships = discoverRelationships; + AddRecommendedSignals = addRecommendedSignals; + DeletedOn = deletedOn; + ErrorMessage = errorMessage; + NumberOfDiscoveredEntities = numberOfDiscoveredEntities; + EntityName = entityName; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DiscoveryRuleProperties() + { + } + + /// The status of the last operation. + public HealthModelProvisioningState? ProvisioningState { get; } + /// Display name. + public string DisplayName { get; set; } + /// Azure Resource Graph query text in KQL syntax. The query must return at least a column named 'id' which contains the resource ID of the discovered resources. + public string ResourceGraphQuery { get; set; } + /// Reference to the name of the authentication setting which is used for querying Azure Resource Graph. The same authentication setting will also be assigned to any discovered entities. + public string AuthenticationSetting { get; set; } + /// Whether to create relationships between the discovered entities based on a set of built-in rules. These relationships cannot be manually deleted. + public DiscoveryRuleRelationshipDiscoveryBehavior DiscoverRelationships { get; set; } + /// Whether to add all recommended signals to the discovered entities. + public DiscoveryRuleRecommendedSignalsBehavior AddRecommendedSignals { get; set; } + /// Date when the discovery rule was (soft-)deleted. + public DateTimeOffset? DeletedOn { get; } + /// Error message if the last discovery operation failed. + public string ErrorMessage { get; } + /// Number of discovered entities in the last discovery operation. + public int? NumberOfDiscoveredEntities { get; } + /// Name of the entity which represents the discovery rule. Note: It might take a few minutes after creating the discovery rule until the entity is created. + public string EntityName { get; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleRecommendedSignalsBehavior.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleRecommendedSignalsBehavior.cs new file mode 100644 index 000000000000..51d8f53875ca --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleRecommendedSignalsBehavior.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Discovery rule recommended signal behavior. + public readonly partial struct DiscoveryRuleRecommendedSignalsBehavior : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DiscoveryRuleRecommendedSignalsBehavior(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string EnabledValue = "Enabled"; + private const string DisabledValue = "Disabled"; + + /// Automatically add recommended signals. + public static DiscoveryRuleRecommendedSignalsBehavior Enabled { get; } = new DiscoveryRuleRecommendedSignalsBehavior(EnabledValue); + /// Do not automatically add recommended signals. + public static DiscoveryRuleRecommendedSignalsBehavior Disabled { get; } = new DiscoveryRuleRecommendedSignalsBehavior(DisabledValue); + /// Determines if two values are the same. + public static bool operator ==(DiscoveryRuleRecommendedSignalsBehavior left, DiscoveryRuleRecommendedSignalsBehavior right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DiscoveryRuleRecommendedSignalsBehavior left, DiscoveryRuleRecommendedSignalsBehavior right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DiscoveryRuleRecommendedSignalsBehavior(string value) => new DiscoveryRuleRecommendedSignalsBehavior(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DiscoveryRuleRecommendedSignalsBehavior other && Equals(other); + /// + public bool Equals(DiscoveryRuleRecommendedSignalsBehavior 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleRelationshipDiscoveryBehavior.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleRelationshipDiscoveryBehavior.cs new file mode 100644 index 000000000000..a8c81d6bda97 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DiscoveryRuleRelationshipDiscoveryBehavior.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Discovery rule relationship discovery behavior. + public readonly partial struct DiscoveryRuleRelationshipDiscoveryBehavior : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DiscoveryRuleRelationshipDiscoveryBehavior(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string EnabledValue = "Enabled"; + private const string DisabledValue = "Disabled"; + + /// Automatically attempt to discover relationships. + public static DiscoveryRuleRelationshipDiscoveryBehavior Enabled { get; } = new DiscoveryRuleRelationshipDiscoveryBehavior(EnabledValue); + /// Do not automatically attempt to discover relationships. + public static DiscoveryRuleRelationshipDiscoveryBehavior Disabled { get; } = new DiscoveryRuleRelationshipDiscoveryBehavior(DisabledValue); + /// Determines if two values are the same. + public static bool operator ==(DiscoveryRuleRelationshipDiscoveryBehavior left, DiscoveryRuleRelationshipDiscoveryBehavior right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DiscoveryRuleRelationshipDiscoveryBehavior left, DiscoveryRuleRelationshipDiscoveryBehavior right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DiscoveryRuleRelationshipDiscoveryBehavior(string value) => new DiscoveryRuleRelationshipDiscoveryBehavior(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DiscoveryRuleRelationshipDiscoveryBehavior other && Equals(other); + /// + public bool Equals(DiscoveryRuleRelationshipDiscoveryBehavior 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DynamicDetectionRule.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DynamicDetectionRule.Serialization.cs new file mode 100644 index 000000000000..3d9519e14a6f --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DynamicDetectionRule.Serialization.cs @@ -0,0 +1,157 @@ +// 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.CloudHealth.Models +{ + public partial class DynamicDetectionRule : 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(DynamicDetectionRule)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("dynamicThresholdModel"u8); + writer.WriteStringValue(DynamicThresholdModel.ToString()); + writer.WritePropertyName("modelSensitivity"u8); + writer.WriteNumberValue(ModelSensitivity); + writer.WritePropertyName("dynamicThresholdDirection"u8); + writer.WriteStringValue(DynamicThresholdDirection.ToString()); + if (Optional.IsDefined(TrainingStartOn)) + { + writer.WritePropertyName("trainingStartTime"u8); + writer.WriteStringValue(TrainingStartOn.Value, "O"); + } + 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 + } + } + } + + DynamicDetectionRule 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(DynamicDetectionRule)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDynamicDetectionRule(document.RootElement, options); + } + + internal static DynamicDetectionRule DeserializeDynamicDetectionRule(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + DynamicThresholdModel dynamicThresholdModel = default; + float modelSensitivity = default; + DynamicThresholdDirection dynamicThresholdDirection = default; + DateTimeOffset? trainingStartTime = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("dynamicThresholdModel"u8)) + { + dynamicThresholdModel = new DynamicThresholdModel(property.Value.GetString()); + continue; + } + if (property.NameEquals("modelSensitivity"u8)) + { + modelSensitivity = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("dynamicThresholdDirection"u8)) + { + dynamicThresholdDirection = new DynamicThresholdDirection(property.Value.GetString()); + continue; + } + if (property.NameEquals("trainingStartTime"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + trainingStartTime = property.Value.GetDateTimeOffset("O"); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new DynamicDetectionRule(dynamicThresholdModel, modelSensitivity, dynamicThresholdDirection, trainingStartTime, 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(DynamicDetectionRule)} does not support writing '{options.Format}' format."); + } + } + + DynamicDetectionRule 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 DeserializeDynamicDetectionRule(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DynamicDetectionRule)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DynamicDetectionRule.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DynamicDetectionRule.cs new file mode 100644 index 000000000000..7a487d1bb4aa --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DynamicDetectionRule.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// ML-based evaluation rule for a signal definition. + public partial class DynamicDetectionRule + { + /// + /// 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 . + /// ML model to use for dynamic thresholds. + /// ML model sensitivity. Lowest value = high sensitivity. Supported step size = 0.5. + /// Threshold direction. + public DynamicDetectionRule(DynamicThresholdModel dynamicThresholdModel, float modelSensitivity, DynamicThresholdDirection dynamicThresholdDirection) + { + DynamicThresholdModel = dynamicThresholdModel; + ModelSensitivity = modelSensitivity; + DynamicThresholdDirection = dynamicThresholdDirection; + } + + /// Initializes a new instance of . + /// ML model to use for dynamic thresholds. + /// ML model sensitivity. Lowest value = high sensitivity. Supported step size = 0.5. + /// Threshold direction. + /// Start time of the training in UTC. + /// Keeps track of any properties unknown to the library. + internal DynamicDetectionRule(DynamicThresholdModel dynamicThresholdModel, float modelSensitivity, DynamicThresholdDirection dynamicThresholdDirection, DateTimeOffset? trainingStartOn, IDictionary serializedAdditionalRawData) + { + DynamicThresholdModel = dynamicThresholdModel; + ModelSensitivity = modelSensitivity; + DynamicThresholdDirection = dynamicThresholdDirection; + TrainingStartOn = trainingStartOn; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DynamicDetectionRule() + { + } + + /// ML model to use for dynamic thresholds. + public DynamicThresholdModel DynamicThresholdModel { get; set; } + /// ML model sensitivity. Lowest value = high sensitivity. Supported step size = 0.5. + public float ModelSensitivity { get; set; } + /// Threshold direction. + public DynamicThresholdDirection DynamicThresholdDirection { get; set; } + /// Start time of the training in UTC. + public DateTimeOffset? TrainingStartOn { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DynamicThresholdDirection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DynamicThresholdDirection.cs new file mode 100644 index 000000000000..4ff4ce8faac9 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DynamicThresholdDirection.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Threshold direction for dynamic thresholds. + public readonly partial struct DynamicThresholdDirection : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DynamicThresholdDirection(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string LowerThanValue = "LowerThan"; + private const string GreaterThanValue = "GreaterThan"; + private const string GreaterOrLowerThanValue = "GreaterOrLowerThan"; + + /// Lower than. + public static DynamicThresholdDirection LowerThan { get; } = new DynamicThresholdDirection(LowerThanValue); + /// Greater than. + public static DynamicThresholdDirection GreaterThan { get; } = new DynamicThresholdDirection(GreaterThanValue); + /// Greater or Lower Than. + public static DynamicThresholdDirection GreaterOrLowerThan { get; } = new DynamicThresholdDirection(GreaterOrLowerThanValue); + /// Determines if two values are the same. + public static bool operator ==(DynamicThresholdDirection left, DynamicThresholdDirection right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DynamicThresholdDirection left, DynamicThresholdDirection right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DynamicThresholdDirection(string value) => new DynamicThresholdDirection(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DynamicThresholdDirection other && Equals(other); + /// + public bool Equals(DynamicThresholdDirection 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DynamicThresholdModel.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DynamicThresholdModel.cs new file mode 100644 index 000000000000..37eb68e1519e --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/DynamicThresholdModel.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// ML-based model variants. + public readonly partial struct DynamicThresholdModel : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DynamicThresholdModel(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AnomalyDetectionValue = "AnomalyDetection"; + + /// Anomaly detection model. + public static DynamicThresholdModel AnomalyDetection { get; } = new DynamicThresholdModel(AnomalyDetectionValue); + /// Determines if two values are the same. + public static bool operator ==(DynamicThresholdModel left, DynamicThresholdModel right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DynamicThresholdModel left, DynamicThresholdModel right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DynamicThresholdModel(string value) => new DynamicThresholdModel(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DynamicThresholdModel other && Equals(other); + /// + public bool Equals(DynamicThresholdModel 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityAlerts.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityAlerts.Serialization.cs new file mode 100644 index 000000000000..71f01b909831 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityAlerts.Serialization.cs @@ -0,0 +1,148 @@ +// 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.CloudHealth.Models +{ + public partial class EntityAlerts : 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(EntityAlerts)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Unhealthy)) + { + writer.WritePropertyName("unhealthy"u8); + writer.WriteObjectValue(Unhealthy, options); + } + if (Optional.IsDefined(Degraded)) + { + writer.WritePropertyName("degraded"u8); + writer.WriteObjectValue(Degraded, 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 + } + } + } + + EntityAlerts 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(EntityAlerts)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEntityAlerts(document.RootElement, options); + } + + internal static EntityAlerts DeserializeEntityAlerts(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AlertConfiguration unhealthy = default; + AlertConfiguration degraded = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("unhealthy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + unhealthy = AlertConfiguration.DeserializeAlertConfiguration(property.Value, options); + continue; + } + if (property.NameEquals("degraded"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + degraded = AlertConfiguration.DeserializeAlertConfiguration(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EntityAlerts(unhealthy, degraded, 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(EntityAlerts)} does not support writing '{options.Format}' format."); + } + } + + EntityAlerts 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 DeserializeEntityAlerts(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EntityAlerts)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityAlerts.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityAlerts.cs new file mode 100644 index 000000000000..b5dee8b0988e --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityAlerts.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Alert configuration for an entity. + public partial class EntityAlerts + { + /// + /// 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 EntityAlerts() + { + } + + /// Initializes a new instance of . + /// Alert to be triggered on state change to unhealthy. + /// Alert to be triggered on state change to degraded. + /// Keeps track of any properties unknown to the library. + internal EntityAlerts(AlertConfiguration unhealthy, AlertConfiguration degraded, IDictionary serializedAdditionalRawData) + { + Unhealthy = unhealthy; + Degraded = degraded; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Alert to be triggered on state change to unhealthy. + public AlertConfiguration Unhealthy { get; set; } + /// Alert to be triggered on state change to degraded. + public AlertConfiguration Degraded { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityCoordinates.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityCoordinates.Serialization.cs new file mode 100644 index 000000000000..4e5ff49b9961 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityCoordinates.Serialization.cs @@ -0,0 +1,134 @@ +// 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.CloudHealth.Models +{ + public partial class EntityCoordinates : 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(EntityCoordinates)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("x"u8); + writer.WriteNumberValue(X); + writer.WritePropertyName("y"u8); + writer.WriteNumberValue(Y); + 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 + } + } + } + + EntityCoordinates 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(EntityCoordinates)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEntityCoordinates(document.RootElement, options); + } + + internal static EntityCoordinates DeserializeEntityCoordinates(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + float x = default; + float y = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("x"u8)) + { + x = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("y"u8)) + { + y = property.Value.GetSingle(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EntityCoordinates(x, y, 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(EntityCoordinates)} does not support writing '{options.Format}' format."); + } + } + + EntityCoordinates 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 DeserializeEntityCoordinates(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EntityCoordinates)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityCoordinates.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityCoordinates.cs new file mode 100644 index 000000000000..d1f51d0da4bb --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityCoordinates.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Visual position of the entity. + public partial class EntityCoordinates + { + /// + /// 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 . + /// X Coordinate. + /// Y Coordinate. + public EntityCoordinates(float x, float y) + { + X = x; + Y = y; + } + + /// Initializes a new instance of . + /// X Coordinate. + /// Y Coordinate. + /// Keeps track of any properties unknown to the library. + internal EntityCoordinates(float x, float y, IDictionary serializedAdditionalRawData) + { + X = x; + Y = y; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal EntityCoordinates() + { + } + + /// X Coordinate. + public float X { get; set; } + /// Y Coordinate. + public float Y { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityImpact.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityImpact.cs new file mode 100644 index 000000000000..79e486764f99 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityImpact.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Type of impact an entity has on health state propagation. + public readonly partial struct EntityImpact : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public EntityImpact(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string StandardValue = "Standard"; + private const string LimitedValue = "Limited"; + private const string SuppressedValue = "Suppressed"; + + /// Standard impact. + public static EntityImpact Standard { get; } = new EntityImpact(StandardValue); + /// Limited impact. + public static EntityImpact Limited { get; } = new EntityImpact(LimitedValue); + /// Suppressed impact. + public static EntityImpact Suppressed { get; } = new EntityImpact(SuppressedValue); + /// Determines if two values are the same. + public static bool operator ==(EntityImpact left, EntityImpact right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(EntityImpact left, EntityImpact right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator EntityImpact(string value) => new EntityImpact(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is EntityImpact other && Equals(other); + /// + public bool Equals(EntityImpact 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityListResult.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityListResult.Serialization.cs new file mode 100644 index 000000000000..d61c7a3a8610 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityListResult.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.CloudHealth.Models +{ + internal partial class EntityListResult : 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(EntityListResult)} 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 + } + } + } + + EntityListResult 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(EntityListResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEntityListResult(document.RootElement, options); + } + + internal static EntityListResult DeserializeEntityListResult(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(EntityData.DeserializeEntityData(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 EntityListResult(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(EntityListResult)} does not support writing '{options.Format}' format."); + } + } + + EntityListResult 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 DeserializeEntityListResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EntityListResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityListResult.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityListResult.cs new file mode 100644 index 000000000000..ca2e332ced28 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityListResult.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.CloudHealth.Models +{ + /// The response of a Entity list operation. + internal partial class EntityListResult + { + /// + /// 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 Entity items on this page. + /// is null. + internal EntityListResult(IEnumerable value) + { + Argument.AssertNotNull(value, nameof(value)); + + Value = value.ToList(); + } + + /// Initializes a new instance of . + /// The Entity items on this page. + /// The link to the next page of items. + /// Keeps track of any properties unknown to the library. + internal EntityListResult(IReadOnlyList value, Uri nextLink, IDictionary serializedAdditionalRawData) + { + Value = value; + NextLink = nextLink; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal EntityListResult() + { + } + + /// The Entity items on this page. + public IReadOnlyList Value { get; } + /// The link to the next page of items. + public Uri NextLink { get; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityProperties.Serialization.cs new file mode 100644 index 000000000000..a66c46c690f4 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityProperties.Serialization.cs @@ -0,0 +1,326 @@ +// 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.CloudHealth.Models +{ + public partial class EntityProperties : 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(EntityProperties)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(ProvisioningState)) + { + writer.WritePropertyName("provisioningState"u8); + writer.WriteStringValue(ProvisioningState.Value.ToString()); + } + if (Optional.IsDefined(DisplayName)) + { + writer.WritePropertyName("displayName"u8); + writer.WriteStringValue(DisplayName); + } + if (Optional.IsDefined(Kind)) + { + writer.WritePropertyName("kind"u8); + writer.WriteStringValue(Kind); + } + if (Optional.IsDefined(CanvasPosition)) + { + writer.WritePropertyName("canvasPosition"u8); + writer.WriteObjectValue(CanvasPosition, options); + } + if (Optional.IsDefined(Icon)) + { + writer.WritePropertyName("icon"u8); + writer.WriteObjectValue(Icon, options); + } + if (Optional.IsDefined(HealthObjective)) + { + writer.WritePropertyName("healthObjective"u8); + writer.WriteNumberValue(HealthObjective.Value); + } + if (Optional.IsDefined(Impact)) + { + writer.WritePropertyName("impact"u8); + writer.WriteStringValue(Impact.Value.ToString()); + } + if (Optional.IsCollectionDefined(Labels)) + { + writer.WritePropertyName("labels"u8); + writer.WriteStartObject(); + foreach (var item in Labels) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsDefined(Signals)) + { + writer.WritePropertyName("signals"u8); + writer.WriteObjectValue(Signals, options); + } + if (options.Format != "W" && Optional.IsDefined(DiscoveredBy)) + { + writer.WritePropertyName("discoveredBy"u8); + writer.WriteStringValue(DiscoveredBy); + } + if (options.Format != "W" && Optional.IsDefined(DeletedOn)) + { + writer.WritePropertyName("deletionDate"u8); + writer.WriteStringValue(DeletedOn.Value, "O"); + } + if (options.Format != "W" && Optional.IsDefined(HealthState)) + { + writer.WritePropertyName("healthState"u8); + writer.WriteStringValue(HealthState.Value.ToString()); + } + if (Optional.IsDefined(Alerts)) + { + writer.WritePropertyName("alerts"u8); + writer.WriteObjectValue(Alerts, 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 + } + } + } + + EntityProperties 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(EntityProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEntityProperties(document.RootElement, options); + } + + internal static EntityProperties DeserializeEntityProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + HealthModelProvisioningState? provisioningState = default; + string displayName = default; + string kind = default; + EntityCoordinates canvasPosition = default; + IconDefinition icon = default; + float? healthObjective = default; + EntityImpact? impact = default; + IDictionary labels = default; + SignalGroup signals = default; + string discoveredBy = default; + DateTimeOffset? deletionDate = default; + HealthState? healthState = default; + EntityAlerts alerts = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("provisioningState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + provisioningState = new HealthModelProvisioningState(property.Value.GetString()); + continue; + } + if (property.NameEquals("displayName"u8)) + { + displayName = property.Value.GetString(); + continue; + } + if (property.NameEquals("kind"u8)) + { + kind = property.Value.GetString(); + continue; + } + if (property.NameEquals("canvasPosition"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + canvasPosition = EntityCoordinates.DeserializeEntityCoordinates(property.Value, options); + continue; + } + if (property.NameEquals("icon"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + icon = IconDefinition.DeserializeIconDefinition(property.Value, options); + continue; + } + if (property.NameEquals("healthObjective"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + healthObjective = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("impact"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + impact = new EntityImpact(property.Value.GetString()); + continue; + } + if (property.NameEquals("labels"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()); + } + labels = dictionary; + continue; + } + if (property.NameEquals("signals"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + signals = SignalGroup.DeserializeSignalGroup(property.Value, options); + continue; + } + if (property.NameEquals("discoveredBy"u8)) + { + discoveredBy = property.Value.GetString(); + continue; + } + if (property.NameEquals("deletionDate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + deletionDate = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("healthState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + healthState = new HealthState(property.Value.GetString()); + continue; + } + if (property.NameEquals("alerts"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + alerts = EntityAlerts.DeserializeEntityAlerts(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EntityProperties( + provisioningState, + displayName, + kind, + canvasPosition, + icon, + healthObjective, + impact, + labels ?? new ChangeTrackingDictionary(), + signals, + discoveredBy, + deletionDate, + healthState, + alerts, + 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(EntityProperties)} does not support writing '{options.Format}' format."); + } + } + + EntityProperties 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 DeserializeEntityProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EntityProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityProperties.cs new file mode 100644 index 000000000000..4dfddba4c9fe --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EntityProperties.cs @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Properties which are common across all kinds of entities. + public partial class EntityProperties + { + /// + /// 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 EntityProperties() + { + Labels = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Entity kind. + /// Positioning of the entity on the model canvas. + /// Visual icon definition. If not set, a default icon is used. + /// Health objective as a percentage of time the entity should be healthy. + /// Impact of the entity in health state propagation. + /// Optional set of labels (key-value pairs). + /// Signal groups which are assigned to this entity. + /// Discovered by which discovery rule. If set, the entity cannot be deleted manually. + /// Date when the entity was (soft-)deleted. + /// Health state of this entity. + /// Alert configuration for this entity. + /// Keeps track of any properties unknown to the library. + internal EntityProperties(HealthModelProvisioningState? provisioningState, string displayName, string kind, EntityCoordinates canvasPosition, IconDefinition icon, float? healthObjective, EntityImpact? impact, IDictionary labels, SignalGroup signals, string discoveredBy, DateTimeOffset? deletedOn, HealthState? healthState, EntityAlerts alerts, IDictionary serializedAdditionalRawData) + { + ProvisioningState = provisioningState; + DisplayName = displayName; + Kind = kind; + CanvasPosition = canvasPosition; + Icon = icon; + HealthObjective = healthObjective; + Impact = impact; + Labels = labels; + Signals = signals; + DiscoveredBy = discoveredBy; + DeletedOn = deletedOn; + HealthState = healthState; + Alerts = alerts; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The status of the last operation. + public HealthModelProvisioningState? ProvisioningState { get; } + /// Display name. + public string DisplayName { get; set; } + /// Entity kind. + public string Kind { get; set; } + /// Positioning of the entity on the model canvas. + public EntityCoordinates CanvasPosition { get; set; } + /// Visual icon definition. If not set, a default icon is used. + public IconDefinition Icon { get; set; } + /// Health objective as a percentage of time the entity should be healthy. + public float? HealthObjective { get; set; } + /// Impact of the entity in health state propagation. + public EntityImpact? Impact { get; set; } + /// Optional set of labels (key-value pairs). + public IDictionary Labels { get; } + /// Signal groups which are assigned to this entity. + public SignalGroup Signals { get; set; } + /// Discovered by which discovery rule. If set, the entity cannot be deleted manually. + public string DiscoveredBy { get; } + /// Date when the entity was (soft-)deleted. + public DateTimeOffset? DeletedOn { get; } + /// Health state of this entity. + public HealthState? HealthState { get; } + /// Alert configuration for this entity. + public EntityAlerts Alerts { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EvaluationRule.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EvaluationRule.Serialization.cs new file mode 100644 index 000000000000..16a3309664e5 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EvaluationRule.Serialization.cs @@ -0,0 +1,163 @@ +// 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.CloudHealth.Models +{ + public partial class EvaluationRule : 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(EvaluationRule)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(DynamicDetectionRule)) + { + writer.WritePropertyName("dynamicDetectionRule"u8); + writer.WriteObjectValue(DynamicDetectionRule, options); + } + if (Optional.IsDefined(DegradedRule)) + { + writer.WritePropertyName("degradedRule"u8); + writer.WriteObjectValue(DegradedRule, options); + } + if (Optional.IsDefined(UnhealthyRule)) + { + writer.WritePropertyName("unhealthyRule"u8); + writer.WriteObjectValue(UnhealthyRule, 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 + } + } + } + + EvaluationRule 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(EvaluationRule)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEvaluationRule(document.RootElement, options); + } + + internal static EvaluationRule DeserializeEvaluationRule(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + DynamicDetectionRule dynamicDetectionRule = default; + ThresholdRule degradedRule = default; + ThresholdRule unhealthyRule = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("dynamicDetectionRule"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + dynamicDetectionRule = DynamicDetectionRule.DeserializeDynamicDetectionRule(property.Value, options); + continue; + } + if (property.NameEquals("degradedRule"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + degradedRule = ThresholdRule.DeserializeThresholdRule(property.Value, options); + continue; + } + if (property.NameEquals("unhealthyRule"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + unhealthyRule = ThresholdRule.DeserializeThresholdRule(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EvaluationRule(dynamicDetectionRule, degradedRule, unhealthyRule, 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(EvaluationRule)} does not support writing '{options.Format}' format."); + } + } + + EvaluationRule 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 DeserializeEvaluationRule(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EvaluationRule)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EvaluationRule.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EvaluationRule.cs new file mode 100644 index 000000000000..f06f0106e544 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/EvaluationRule.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Evaluation rule for a signal definition. + public partial class EvaluationRule + { + /// + /// 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 EvaluationRule() + { + } + + /// Initializes a new instance of . + /// Configure to use ML-based dynamic thresholds. When used, degradedRule and unhealthyRule must not be set. + /// Degraded rule with static threshold. When used, dynamicDetectionRule must not be set. + /// Unhealthy rule with static threshold. When used, dynamicDetectionRule must not be set. + /// Keeps track of any properties unknown to the library. + internal EvaluationRule(DynamicDetectionRule dynamicDetectionRule, ThresholdRule degradedRule, ThresholdRule unhealthyRule, IDictionary serializedAdditionalRawData) + { + DynamicDetectionRule = dynamicDetectionRule; + DegradedRule = degradedRule; + UnhealthyRule = unhealthyRule; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Configure to use ML-based dynamic thresholds. When used, degradedRule and unhealthyRule must not be set. + public DynamicDetectionRule DynamicDetectionRule { get; set; } + /// Degraded rule with static threshold. When used, dynamicDetectionRule must not be set. + public ThresholdRule DegradedRule { get; set; } + /// Unhealthy rule with static threshold. When used, dynamicDetectionRule must not be set. + public ThresholdRule UnhealthyRule { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelListResult.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelListResult.Serialization.cs new file mode 100644 index 000000000000..a765554263d7 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelListResult.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.CloudHealth.Models +{ + internal partial class HealthModelListResult : 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(HealthModelListResult)} 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 + } + } + } + + HealthModelListResult 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(HealthModelListResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeHealthModelListResult(document.RootElement, options); + } + + internal static HealthModelListResult DeserializeHealthModelListResult(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(HealthModelData.DeserializeHealthModelData(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 HealthModelListResult(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(HealthModelListResult)} does not support writing '{options.Format}' format."); + } + } + + HealthModelListResult 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 DeserializeHealthModelListResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(HealthModelListResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelListResult.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelListResult.cs new file mode 100644 index 000000000000..dd5fc2c88909 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelListResult.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.CloudHealth.Models +{ + /// The response of a HealthModel list operation. + internal partial class HealthModelListResult + { + /// + /// 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 HealthModel items on this page. + /// is null. + internal HealthModelListResult(IEnumerable value) + { + Argument.AssertNotNull(value, nameof(value)); + + Value = value.ToList(); + } + + /// Initializes a new instance of . + /// The HealthModel items on this page. + /// The link to the next page of items. + /// Keeps track of any properties unknown to the library. + internal HealthModelListResult(IReadOnlyList value, Uri nextLink, IDictionary serializedAdditionalRawData) + { + Value = value; + NextLink = nextLink; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal HealthModelListResult() + { + } + + /// The HealthModel items on this page. + public IReadOnlyList Value { get; } + /// The link to the next page of items. + public Uri NextLink { get; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelPatch.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelPatch.Serialization.cs new file mode 100644 index 000000000000..070206cc226d --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelPatch.Serialization.cs @@ -0,0 +1,177 @@ +// 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.Models; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + public partial class HealthModelPatch : 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(HealthModelPatch)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Identity)) + { + writer.WritePropertyName("identity"u8); + var serializeOptions = new JsonSerializerOptions { Converters = { new ManagedServiceIdentityTypeV3Converter() } }; + JsonSerializer.Serialize(writer, Identity, serializeOptions); + } + if (Optional.IsCollectionDefined(Tags)) + { + writer.WritePropertyName("tags"u8); + writer.WriteStartObject(); + foreach (var item in Tags) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsDefined(Properties)) + { + writer.WritePropertyName("properties"u8); + writer.WriteObjectValue(Properties, 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 + } + } + } + + HealthModelPatch 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(HealthModelPatch)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeHealthModelPatch(document.RootElement, options); + } + + internal static HealthModelPatch DeserializeHealthModelPatch(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ManagedServiceIdentity identity = default; + IDictionary tags = default; + HealthModelUpdateProperties properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("identity"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + var serializeOptions = new JsonSerializerOptions { Converters = { new ManagedServiceIdentityTypeV3Converter() } }; + identity = JsonSerializer.Deserialize(property.Value.GetRawText(), serializeOptions); + 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("properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + properties = HealthModelUpdateProperties.DeserializeHealthModelUpdateProperties(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new HealthModelPatch(identity, tags ?? new ChangeTrackingDictionary(), 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(HealthModelPatch)} does not support writing '{options.Format}' format."); + } + } + + HealthModelPatch 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 DeserializeHealthModelPatch(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(HealthModelPatch)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelPatch.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelPatch.cs new file mode 100644 index 000000000000..166f0afecca7 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelPatch.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; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// The type used for update operations of the HealthModel. + public partial class HealthModelPatch + { + /// + /// 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 HealthModelPatch() + { + Tags = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// The managed service identities assigned to this resource. + /// Resource tags. + /// The resource-specific properties for this resource. + /// Keeps track of any properties unknown to the library. + internal HealthModelPatch(ManagedServiceIdentity identity, IDictionary tags, HealthModelUpdateProperties properties, IDictionary serializedAdditionalRawData) + { + Identity = identity; + Tags = tags; + Properties = properties; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The managed service identities assigned to this resource. + public ManagedServiceIdentity Identity { get; set; } + /// Resource tags. + public IDictionary Tags { get; } + /// The resource-specific properties for this resource. + internal HealthModelUpdateProperties Properties { get; set; } + /// Configure to automatically discover entities from a given scope, such as a Service Group. The discovered entities will be linked to the root entity of the health model. + public ModelDiscoverySettings HealthModelUpdateDiscovery + { + get => Properties is null ? default : Properties.Discovery; + set + { + if (Properties is null) + Properties = new HealthModelUpdateProperties(); + Properties.Discovery = value; + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelProperties.Serialization.cs new file mode 100644 index 000000000000..3ce084e36de4 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelProperties.Serialization.cs @@ -0,0 +1,159 @@ +// 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.CloudHealth.Models +{ + public partial class HealthModelProperties : 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(HealthModelProperties)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(DataplaneEndpoint)) + { + writer.WritePropertyName("dataplaneEndpoint"u8); + writer.WriteStringValue(DataplaneEndpoint); + } + if (options.Format != "W" && Optional.IsDefined(ProvisioningState)) + { + writer.WritePropertyName("provisioningState"u8); + writer.WriteStringValue(ProvisioningState.Value.ToString()); + } + if (Optional.IsDefined(Discovery)) + { + writer.WritePropertyName("discovery"u8); + writer.WriteObjectValue(Discovery, 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 + } + } + } + + HealthModelProperties 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(HealthModelProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeHealthModelProperties(document.RootElement, options); + } + + internal static HealthModelProperties DeserializeHealthModelProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string dataplaneEndpoint = default; + HealthModelProvisioningState? provisioningState = default; + ModelDiscoverySettings discovery = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("dataplaneEndpoint"u8)) + { + dataplaneEndpoint = property.Value.GetString(); + continue; + } + if (property.NameEquals("provisioningState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + provisioningState = new HealthModelProvisioningState(property.Value.GetString()); + continue; + } + if (property.NameEquals("discovery"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + discovery = ModelDiscoverySettings.DeserializeModelDiscoverySettings(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new HealthModelProperties(dataplaneEndpoint, provisioningState, discovery, 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(HealthModelProperties)} does not support writing '{options.Format}' format."); + } + } + + HealthModelProperties 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 DeserializeHealthModelProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(HealthModelProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelProperties.cs new file mode 100644 index 000000000000..5e150fc748d8 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelProperties.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// HealthModel properties. + public partial class HealthModelProperties + { + /// + /// 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 HealthModelProperties() + { + } + + /// Initializes a new instance of . + /// The data plane endpoint for interacting with health data. + /// The status of the last operation. + /// Configure to automatically discover entities from a given scope, such as a Service Group. The discovered entities will be linked to the root entity of the health model. + /// Keeps track of any properties unknown to the library. + internal HealthModelProperties(string dataplaneEndpoint, HealthModelProvisioningState? provisioningState, ModelDiscoverySettings discovery, IDictionary serializedAdditionalRawData) + { + DataplaneEndpoint = dataplaneEndpoint; + ProvisioningState = provisioningState; + Discovery = discovery; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The data plane endpoint for interacting with health data. + public string DataplaneEndpoint { get; } + /// The status of the last operation. + public HealthModelProvisioningState? ProvisioningState { get; } + /// Configure to automatically discover entities from a given scope, such as a Service Group. The discovered entities will be linked to the root entity of the health model. + public ModelDiscoverySettings Discovery { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelProvisioningState.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelProvisioningState.cs new file mode 100644 index 000000000000..03ec412b6307 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelProvisioningState.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.ResourceManager.CloudHealth.Models +{ + /// Health Model provisioning states. + public readonly partial struct HealthModelProvisioningState : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public HealthModelProvisioningState(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 CreatingValue = "Creating"; + private const string DeletingValue = "Deleting"; + + /// Resource has been created. + public static HealthModelProvisioningState Succeeded { get; } = new HealthModelProvisioningState(SucceededValue); + /// Resource creation failed. + public static HealthModelProvisioningState Failed { get; } = new HealthModelProvisioningState(FailedValue); + /// Resource creation was canceled. + public static HealthModelProvisioningState Canceled { get; } = new HealthModelProvisioningState(CanceledValue); + /// Creating. + public static HealthModelProvisioningState Creating { get; } = new HealthModelProvisioningState(CreatingValue); + /// Deleting. + public static HealthModelProvisioningState Deleting { get; } = new HealthModelProvisioningState(DeletingValue); + /// Determines if two values are the same. + public static bool operator ==(HealthModelProvisioningState left, HealthModelProvisioningState right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(HealthModelProvisioningState left, HealthModelProvisioningState right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator HealthModelProvisioningState(string value) => new HealthModelProvisioningState(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is HealthModelProvisioningState other && Equals(other); + /// + public bool Equals(HealthModelProvisioningState 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelUpdateProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelUpdateProperties.Serialization.cs new file mode 100644 index 000000000000..eaa4b46d78ec --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelUpdateProperties.Serialization.cs @@ -0,0 +1,133 @@ +// 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.CloudHealth.Models +{ + internal partial class HealthModelUpdateProperties : 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(HealthModelUpdateProperties)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Discovery)) + { + writer.WritePropertyName("discovery"u8); + writer.WriteObjectValue(Discovery, 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 + } + } + } + + HealthModelUpdateProperties 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(HealthModelUpdateProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeHealthModelUpdateProperties(document.RootElement, options); + } + + internal static HealthModelUpdateProperties DeserializeHealthModelUpdateProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ModelDiscoverySettings discovery = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("discovery"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + discovery = ModelDiscoverySettings.DeserializeModelDiscoverySettings(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new HealthModelUpdateProperties(discovery, 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(HealthModelUpdateProperties)} does not support writing '{options.Format}' format."); + } + } + + HealthModelUpdateProperties 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 DeserializeHealthModelUpdateProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(HealthModelUpdateProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelUpdateProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelUpdateProperties.cs new file mode 100644 index 000000000000..2119fa88daa0 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthModelUpdateProperties.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// The updatable properties of the HealthModel. + internal partial class HealthModelUpdateProperties + { + /// + /// 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 HealthModelUpdateProperties() + { + } + + /// Initializes a new instance of . + /// Configure to automatically discover entities from a given scope, such as a Service Group. The discovered entities will be linked to the root entity of the health model. + /// Keeps track of any properties unknown to the library. + internal HealthModelUpdateProperties(ModelDiscoverySettings discovery, IDictionary serializedAdditionalRawData) + { + Discovery = discovery; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Configure to automatically discover entities from a given scope, such as a Service Group. The discovered entities will be linked to the root entity of the health model. + public ModelDiscoverySettings Discovery { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthState.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthState.cs new file mode 100644 index 000000000000..307c28b9fefd --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/HealthState.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.ResourceManager.CloudHealth.Models +{ + /// Health state of an entity. + public readonly partial struct HealthState : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public HealthState(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string HealthyValue = "Healthy"; + private const string DegradedValue = "Degraded"; + private const string ErrorValue = "Error"; + private const string UnknownValue = "Unknown"; + private const string DeletedValue = "Deleted"; + + /// Healthy status. + public static HealthState Healthy { get; } = new HealthState(HealthyValue); + /// Degraded status. + public static HealthState Degraded { get; } = new HealthState(DegradedValue); + /// Error status (Unhealthy). + public static HealthState Error { get; } = new HealthState(ErrorValue); + /// Unknown status. + public static HealthState Unknown { get; } = new HealthState(UnknownValue); + /// Deleted status. + public static HealthState Deleted { get; } = new HealthState(DeletedValue); + /// Determines if two values are the same. + public static bool operator ==(HealthState left, HealthState right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(HealthState left, HealthState right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator HealthState(string value) => new HealthState(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is HealthState other && Equals(other); + /// + public bool Equals(HealthState 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/IconDefinition.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/IconDefinition.Serialization.cs new file mode 100644 index 000000000000..7ac259e036ec --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/IconDefinition.Serialization.cs @@ -0,0 +1,137 @@ +// 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.CloudHealth.Models +{ + public partial class IconDefinition : 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(IconDefinition)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("iconName"u8); + writer.WriteStringValue(IconName); + if (Optional.IsDefined(CustomData)) + { + writer.WritePropertyName("customData"u8); + writer.WriteStringValue(CustomData); + } + 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 + } + } + } + + IconDefinition 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(IconDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeIconDefinition(document.RootElement, options); + } + + internal static IconDefinition DeserializeIconDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string iconName = default; + string customData = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("iconName"u8)) + { + iconName = property.Value.GetString(); + continue; + } + if (property.NameEquals("customData"u8)) + { + customData = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new IconDefinition(iconName, customData, 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(IconDefinition)} does not support writing '{options.Format}' format."); + } + } + + IconDefinition 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 DeserializeIconDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(IconDefinition)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/IconDefinition.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/IconDefinition.cs new file mode 100644 index 000000000000..2abcc6a0f399 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/IconDefinition.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Visual icon definition of an entity. + public partial class IconDefinition + { + /// + /// 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 . + /// Name of the built-in icon, or 'Custom' to use customData. + /// is null. + public IconDefinition(string iconName) + { + Argument.AssertNotNull(iconName, nameof(iconName)); + + IconName = iconName; + } + + /// Initializes a new instance of . + /// Name of the built-in icon, or 'Custom' to use customData. + /// Custom data. Base64-encoded SVG data. If set, this overrides the built-in icon. + /// Keeps track of any properties unknown to the library. + internal IconDefinition(string iconName, string customData, IDictionary serializedAdditionalRawData) + { + IconName = iconName; + CustomData = customData; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal IconDefinition() + { + } + + /// Name of the built-in icon, or 'Custom' to use customData. + public string IconName { get; set; } + /// Custom data. Base64-encoded SVG data. If set, this overrides the built-in icon. + public string CustomData { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/LogAnalyticsQuerySignalDefinitionProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/LogAnalyticsQuerySignalDefinitionProperties.Serialization.cs new file mode 100644 index 000000000000..c62dd6bd0d13 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/LogAnalyticsQuerySignalDefinitionProperties.Serialization.cs @@ -0,0 +1,215 @@ +// 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.CloudHealth.Models +{ + public partial class LogAnalyticsQuerySignalDefinitionProperties : 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(LogAnalyticsQuerySignalDefinitionProperties)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("queryText"u8); + writer.WriteStringValue(QueryText); + if (Optional.IsDefined(TimeGrain)) + { + writer.WritePropertyName("timeGrain"u8); + writer.WriteStringValue(TimeGrain); + } + if (Optional.IsDefined(ValueColumnName)) + { + writer.WritePropertyName("valueColumnName"u8); + writer.WriteStringValue(ValueColumnName); + } + } + + LogAnalyticsQuerySignalDefinitionProperties 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(LogAnalyticsQuerySignalDefinitionProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLogAnalyticsQuerySignalDefinitionProperties(document.RootElement, options); + } + + internal static LogAnalyticsQuerySignalDefinitionProperties DeserializeLogAnalyticsQuerySignalDefinitionProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string queryText = default; + string timeGrain = default; + string valueColumnName = default; + HealthModelProvisioningState? provisioningState = default; + string displayName = default; + SignalKind signalKind = default; + RefreshInterval? refreshInterval = default; + IDictionary labels = default; + string dataUnit = default; + EvaluationRule evaluationRules = default; + DateTimeOffset? deletionDate = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("queryText"u8)) + { + queryText = property.Value.GetString(); + continue; + } + if (property.NameEquals("timeGrain"u8)) + { + timeGrain = property.Value.GetString(); + continue; + } + if (property.NameEquals("valueColumnName"u8)) + { + valueColumnName = property.Value.GetString(); + continue; + } + if (property.NameEquals("provisioningState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + provisioningState = new HealthModelProvisioningState(property.Value.GetString()); + continue; + } + if (property.NameEquals("displayName"u8)) + { + displayName = property.Value.GetString(); + continue; + } + if (property.NameEquals("signalKind"u8)) + { + signalKind = new SignalKind(property.Value.GetString()); + continue; + } + if (property.NameEquals("refreshInterval"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + refreshInterval = new RefreshInterval(property.Value.GetString()); + continue; + } + if (property.NameEquals("labels"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()); + } + labels = dictionary; + continue; + } + if (property.NameEquals("dataUnit"u8)) + { + dataUnit = property.Value.GetString(); + continue; + } + if (property.NameEquals("evaluationRules"u8)) + { + evaluationRules = EvaluationRule.DeserializeEvaluationRule(property.Value, options); + continue; + } + if (property.NameEquals("deletionDate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + deletionDate = property.Value.GetDateTimeOffset("O"); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LogAnalyticsQuerySignalDefinitionProperties( + provisioningState, + displayName, + signalKind, + refreshInterval, + labels ?? new ChangeTrackingDictionary(), + dataUnit, + evaluationRules, + deletionDate, + serializedAdditionalRawData, + queryText, + timeGrain, + valueColumnName); + } + + 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(LogAnalyticsQuerySignalDefinitionProperties)} does not support writing '{options.Format}' format."); + } + } + + LogAnalyticsQuerySignalDefinitionProperties 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 DeserializeLogAnalyticsQuerySignalDefinitionProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LogAnalyticsQuerySignalDefinitionProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/LogAnalyticsQuerySignalDefinitionProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/LogAnalyticsQuerySignalDefinitionProperties.cs new file mode 100644 index 000000000000..3a1f72371b84 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/LogAnalyticsQuerySignalDefinitionProperties.cs @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Log Analytics Query Signal Definition properties. + public partial class LogAnalyticsQuerySignalDefinitionProperties : SignalDefinitionProperties + { + /// Initializes a new instance of . + /// Evaluation rules for the signal definition. + /// Query text in KQL syntax. + /// or is null. + public LogAnalyticsQuerySignalDefinitionProperties(EvaluationRule evaluationRules, string queryText) : base(evaluationRules) + { + Argument.AssertNotNull(evaluationRules, nameof(evaluationRules)); + Argument.AssertNotNull(queryText, nameof(queryText)); + + QueryText = queryText; + SignalKind = SignalKind.LogAnalyticsQuery; + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Kind of the signal definition. + /// Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + /// Optional set of labels (key-value pairs). + /// Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)). + /// Evaluation rules for the signal definition. + /// Date when the signal definition was (soft-)deleted. + /// Keeps track of any properties unknown to the library. + /// Query text in KQL syntax. + /// Time range of signal. ISO duration format like PT10M. If not specified, the KQL query must define a time range. + /// Name of the column in the result set to evaluate against the thresholds. Defaults to the first column in the result set if not specified. The column must be numeric. + internal LogAnalyticsQuerySignalDefinitionProperties(HealthModelProvisioningState? provisioningState, string displayName, SignalKind signalKind, RefreshInterval? refreshInterval, IDictionary labels, string dataUnit, EvaluationRule evaluationRules, DateTimeOffset? deletedOn, IDictionary serializedAdditionalRawData, string queryText, string timeGrain, string valueColumnName) : base(provisioningState, displayName, signalKind, refreshInterval, labels, dataUnit, evaluationRules, deletedOn, serializedAdditionalRawData) + { + QueryText = queryText; + TimeGrain = timeGrain; + ValueColumnName = valueColumnName; + SignalKind = signalKind; + } + + /// Initializes a new instance of for deserialization. + internal LogAnalyticsQuerySignalDefinitionProperties() + { + } + + /// Query text in KQL syntax. + public string QueryText { get; set; } + /// Time range of signal. ISO duration format like PT10M. If not specified, the KQL query must define a time range. + public string TimeGrain { get; set; } + /// Name of the column in the result set to evaluate against the thresholds. Defaults to the first column in the result set if not specified. The column must be numeric. + public string ValueColumnName { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/LogAnalyticsSignalGroup.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/LogAnalyticsSignalGroup.Serialization.cs new file mode 100644 index 000000000000..f157cb1f51f6 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/LogAnalyticsSignalGroup.Serialization.cs @@ -0,0 +1,159 @@ +// 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.CloudHealth.Models +{ + public partial class LogAnalyticsSignalGroup : 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(LogAnalyticsSignalGroup)} does not support writing '{format}' format."); + } + + if (Optional.IsCollectionDefined(SignalAssignments)) + { + writer.WritePropertyName("signalAssignments"u8); + writer.WriteStartArray(); + foreach (var item in SignalAssignments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + writer.WritePropertyName("authenticationSetting"u8); + writer.WriteStringValue(AuthenticationSetting); + writer.WritePropertyName("logAnalyticsWorkspaceResourceId"u8); + writer.WriteStringValue(LogAnalyticsWorkspaceResourceId); + 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 + } + } + } + + LogAnalyticsSignalGroup 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(LogAnalyticsSignalGroup)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLogAnalyticsSignalGroup(document.RootElement, options); + } + + internal static LogAnalyticsSignalGroup DeserializeLogAnalyticsSignalGroup(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList signalAssignments = default; + string authenticationSetting = default; + ResourceIdentifier logAnalyticsWorkspaceResourceId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("signalAssignments"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(SignalAssignment.DeserializeSignalAssignment(item, options)); + } + signalAssignments = array; + continue; + } + if (property.NameEquals("authenticationSetting"u8)) + { + authenticationSetting = property.Value.GetString(); + continue; + } + if (property.NameEquals("logAnalyticsWorkspaceResourceId"u8)) + { + logAnalyticsWorkspaceResourceId = new ResourceIdentifier(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LogAnalyticsSignalGroup(signalAssignments ?? new ChangeTrackingList(), authenticationSetting, logAnalyticsWorkspaceResourceId, 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(LogAnalyticsSignalGroup)} does not support writing '{options.Format}' format."); + } + } + + LogAnalyticsSignalGroup 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 DeserializeLogAnalyticsSignalGroup(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LogAnalyticsSignalGroup)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/LogAnalyticsSignalGroup.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/LogAnalyticsSignalGroup.cs new file mode 100644 index 000000000000..14d80d5e2d34 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/LogAnalyticsSignalGroup.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure.Core; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// A grouping of signal assignments for a Log Analytics Workspace. + public partial class LogAnalyticsSignalGroup + { + /// + /// 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 . + /// Reference to the name of the authentication setting which is used for querying the data source. + /// Log Analytics Workspace resource ID. + /// or is null. + public LogAnalyticsSignalGroup(string authenticationSetting, ResourceIdentifier logAnalyticsWorkspaceResourceId) + { + Argument.AssertNotNull(authenticationSetting, nameof(authenticationSetting)); + Argument.AssertNotNull(logAnalyticsWorkspaceResourceId, nameof(logAnalyticsWorkspaceResourceId)); + + SignalAssignments = new ChangeTrackingList(); + AuthenticationSetting = authenticationSetting; + LogAnalyticsWorkspaceResourceId = logAnalyticsWorkspaceResourceId; + } + + /// Initializes a new instance of . + /// Signal definitions which are assigned to this signal group. All assignments are combined with an OR operator. + /// Reference to the name of the authentication setting which is used for querying the data source. + /// Log Analytics Workspace resource ID. + /// Keeps track of any properties unknown to the library. + internal LogAnalyticsSignalGroup(IList signalAssignments, string authenticationSetting, ResourceIdentifier logAnalyticsWorkspaceResourceId, IDictionary serializedAdditionalRawData) + { + SignalAssignments = signalAssignments; + AuthenticationSetting = authenticationSetting; + LogAnalyticsWorkspaceResourceId = logAnalyticsWorkspaceResourceId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LogAnalyticsSignalGroup() + { + } + + /// Signal definitions which are assigned to this signal group. All assignments are combined with an OR operator. + public IList SignalAssignments { get; } + /// Reference to the name of the authentication setting which is used for querying the data source. + public string AuthenticationSetting { get; set; } + /// Log Analytics Workspace resource ID. + public ResourceIdentifier LogAnalyticsWorkspaceResourceId { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ManagedIdentityAuthenticationSettingProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ManagedIdentityAuthenticationSettingProperties.Serialization.cs new file mode 100644 index 000000000000..f0982d8f287b --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ManagedIdentityAuthenticationSettingProperties.Serialization.cs @@ -0,0 +1,134 @@ +// 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.CloudHealth.Models +{ + public partial class ManagedIdentityAuthenticationSettingProperties : 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(ManagedIdentityAuthenticationSettingProperties)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("managedIdentityName"u8); + writer.WriteStringValue(ManagedIdentityName); + } + + ManagedIdentityAuthenticationSettingProperties 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(ManagedIdentityAuthenticationSettingProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeManagedIdentityAuthenticationSettingProperties(document.RootElement, options); + } + + internal static ManagedIdentityAuthenticationSettingProperties DeserializeManagedIdentityAuthenticationSettingProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string managedIdentityName = default; + HealthModelProvisioningState? provisioningState = default; + string displayName = default; + AuthenticationKind authenticationKind = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("managedIdentityName"u8)) + { + managedIdentityName = property.Value.GetString(); + continue; + } + if (property.NameEquals("provisioningState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + provisioningState = new HealthModelProvisioningState(property.Value.GetString()); + continue; + } + if (property.NameEquals("displayName"u8)) + { + displayName = property.Value.GetString(); + continue; + } + if (property.NameEquals("authenticationKind"u8)) + { + authenticationKind = new AuthenticationKind(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ManagedIdentityAuthenticationSettingProperties(provisioningState, displayName, authenticationKind, serializedAdditionalRawData, managedIdentityName); + } + + 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(ManagedIdentityAuthenticationSettingProperties)} does not support writing '{options.Format}' format."); + } + } + + ManagedIdentityAuthenticationSettingProperties 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 DeserializeManagedIdentityAuthenticationSettingProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ManagedIdentityAuthenticationSettingProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ManagedIdentityAuthenticationSettingProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ManagedIdentityAuthenticationSettingProperties.cs new file mode 100644 index 000000000000..ea9781a4461c --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ManagedIdentityAuthenticationSettingProperties.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Authentication setting properties for Azure Managed Identity. + public partial class ManagedIdentityAuthenticationSettingProperties : AuthenticationSettingProperties + { + /// Initializes a new instance of . + /// Name of the managed identity to use. Either 'SystemAssigned' or the resourceId of a user-assigned identity. + /// is null. + public ManagedIdentityAuthenticationSettingProperties(string managedIdentityName) + { + Argument.AssertNotNull(managedIdentityName, nameof(managedIdentityName)); + + ManagedIdentityName = managedIdentityName; + AuthenticationKind = AuthenticationKind.ManagedIdentity; + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Kind of the authentication setting. + /// Keeps track of any properties unknown to the library. + /// Name of the managed identity to use. Either 'SystemAssigned' or the resourceId of a user-assigned identity. + internal ManagedIdentityAuthenticationSettingProperties(HealthModelProvisioningState? provisioningState, string displayName, AuthenticationKind authenticationKind, IDictionary serializedAdditionalRawData, string managedIdentityName) : base(provisioningState, displayName, authenticationKind, serializedAdditionalRawData) + { + ManagedIdentityName = managedIdentityName; + AuthenticationKind = authenticationKind; + } + + /// Initializes a new instance of for deserialization. + internal ManagedIdentityAuthenticationSettingProperties() + { + } + + /// Name of the managed identity to use. Either 'SystemAssigned' or the resourceId of a user-assigned identity. + public string ManagedIdentityName { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/MetricAggregationType.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/MetricAggregationType.cs new file mode 100644 index 000000000000..31d3127d3759 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/MetricAggregationType.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Metric aggregation type. + public readonly partial struct MetricAggregationType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public MetricAggregationType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string NoneValue = "None"; + private const string AverageValue = "Average"; + private const string CountValue = "Count"; + private const string MinimumValue = "Minimum"; + private const string MaximumValue = "Maximum"; + private const string TotalValue = "Total"; + + /// None. + public static MetricAggregationType None { get; } = new MetricAggregationType(NoneValue); + /// Average. + public static MetricAggregationType Average { get; } = new MetricAggregationType(AverageValue); + /// Count. + public static MetricAggregationType Count { get; } = new MetricAggregationType(CountValue); + /// Minimum. + public static MetricAggregationType Minimum { get; } = new MetricAggregationType(MinimumValue); + /// Maximum. + public static MetricAggregationType Maximum { get; } = new MetricAggregationType(MaximumValue); + /// Total. + public static MetricAggregationType Total { get; } = new MetricAggregationType(TotalValue); + /// Determines if two values are the same. + public static bool operator ==(MetricAggregationType left, MetricAggregationType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(MetricAggregationType left, MetricAggregationType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator MetricAggregationType(string value) => new MetricAggregationType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is MetricAggregationType other && Equals(other); + /// + public bool Equals(MetricAggregationType 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ModelDiscoverySettings.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ModelDiscoverySettings.Serialization.cs new file mode 100644 index 000000000000..fef4d5bcb75e --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ModelDiscoverySettings.Serialization.cs @@ -0,0 +1,145 @@ +// 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.CloudHealth.Models +{ + public partial class ModelDiscoverySettings : 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(ModelDiscoverySettings)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("scope"u8); + writer.WriteStringValue(Scope); + writer.WritePropertyName("addRecommendedSignals"u8); + writer.WriteStringValue(AddRecommendedSignals.ToString()); + if (Optional.IsDefined(Identity)) + { + writer.WritePropertyName("identity"u8); + writer.WriteStringValue(Identity); + } + 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 + } + } + } + + ModelDiscoverySettings 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(ModelDiscoverySettings)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeModelDiscoverySettings(document.RootElement, options); + } + + internal static ModelDiscoverySettings DeserializeModelDiscoverySettings(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string scope = default; + DiscoveryRuleRecommendedSignalsBehavior addRecommendedSignals = default; + string identity = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("scope"u8)) + { + scope = property.Value.GetString(); + continue; + } + if (property.NameEquals("addRecommendedSignals"u8)) + { + addRecommendedSignals = new DiscoveryRuleRecommendedSignalsBehavior(property.Value.GetString()); + continue; + } + if (property.NameEquals("identity"u8)) + { + identity = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ModelDiscoverySettings(scope, addRecommendedSignals, identity, 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(ModelDiscoverySettings)} does not support writing '{options.Format}' format."); + } + } + + ModelDiscoverySettings 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 DeserializeModelDiscoverySettings(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ModelDiscoverySettings)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ModelDiscoverySettings.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ModelDiscoverySettings.cs new file mode 100644 index 000000000000..f8885e5132ea --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ModelDiscoverySettings.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Settings for automatically discovering entities for the health model. + public partial class ModelDiscoverySettings + { + /// + /// 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 scope from which entities should be automatically discovered. For example, the resource id of a Service Group. + /// Whether to add all recommended signals to the discovered entities. + /// is null. + public ModelDiscoverySettings(string scope, DiscoveryRuleRecommendedSignalsBehavior addRecommendedSignals) + { + Argument.AssertNotNull(scope, nameof(scope)); + + Scope = scope; + AddRecommendedSignals = addRecommendedSignals; + } + + /// Initializes a new instance of . + /// The scope from which entities should be automatically discovered. For example, the resource id of a Service Group. + /// Whether to add all recommended signals to the discovered entities. + /// Which Managed Identity of the health model to use for discovery. Defaults to SystemAssigned, if not set. Can be set to 'SystemAssigned' or to the resource id of a user-assigned managed identity which is linked to the health model. + /// Keeps track of any properties unknown to the library. + internal ModelDiscoverySettings(string scope, DiscoveryRuleRecommendedSignalsBehavior addRecommendedSignals, string identity, IDictionary serializedAdditionalRawData) + { + Scope = scope; + AddRecommendedSignals = addRecommendedSignals; + Identity = identity; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ModelDiscoverySettings() + { + } + + /// The scope from which entities should be automatically discovered. For example, the resource id of a Service Group. + public string Scope { get; set; } + /// Whether to add all recommended signals to the discovered entities. + public DiscoveryRuleRecommendedSignalsBehavior AddRecommendedSignals { get; set; } + /// Which Managed Identity of the health model to use for discovery. Defaults to SystemAssigned, if not set. Can be set to 'SystemAssigned' or to the resource id of a user-assigned managed identity which is linked to the health model. + public string Identity { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/PrometheusMetricsSignalDefinitionProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/PrometheusMetricsSignalDefinitionProperties.Serialization.cs new file mode 100644 index 000000000000..3cfac26b200d --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/PrometheusMetricsSignalDefinitionProperties.Serialization.cs @@ -0,0 +1,203 @@ +// 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.CloudHealth.Models +{ + public partial class PrometheusMetricsSignalDefinitionProperties : 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(PrometheusMetricsSignalDefinitionProperties)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("queryText"u8); + writer.WriteStringValue(QueryText); + if (Optional.IsDefined(TimeGrain)) + { + writer.WritePropertyName("timeGrain"u8); + writer.WriteStringValue(TimeGrain); + } + } + + PrometheusMetricsSignalDefinitionProperties 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(PrometheusMetricsSignalDefinitionProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePrometheusMetricsSignalDefinitionProperties(document.RootElement, options); + } + + internal static PrometheusMetricsSignalDefinitionProperties DeserializePrometheusMetricsSignalDefinitionProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string queryText = default; + string timeGrain = default; + HealthModelProvisioningState? provisioningState = default; + string displayName = default; + SignalKind signalKind = default; + RefreshInterval? refreshInterval = default; + IDictionary labels = default; + string dataUnit = default; + EvaluationRule evaluationRules = default; + DateTimeOffset? deletionDate = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("queryText"u8)) + { + queryText = property.Value.GetString(); + continue; + } + if (property.NameEquals("timeGrain"u8)) + { + timeGrain = property.Value.GetString(); + continue; + } + if (property.NameEquals("provisioningState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + provisioningState = new HealthModelProvisioningState(property.Value.GetString()); + continue; + } + if (property.NameEquals("displayName"u8)) + { + displayName = property.Value.GetString(); + continue; + } + if (property.NameEquals("signalKind"u8)) + { + signalKind = new SignalKind(property.Value.GetString()); + continue; + } + if (property.NameEquals("refreshInterval"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + refreshInterval = new RefreshInterval(property.Value.GetString()); + continue; + } + if (property.NameEquals("labels"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()); + } + labels = dictionary; + continue; + } + if (property.NameEquals("dataUnit"u8)) + { + dataUnit = property.Value.GetString(); + continue; + } + if (property.NameEquals("evaluationRules"u8)) + { + evaluationRules = EvaluationRule.DeserializeEvaluationRule(property.Value, options); + continue; + } + if (property.NameEquals("deletionDate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + deletionDate = property.Value.GetDateTimeOffset("O"); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new PrometheusMetricsSignalDefinitionProperties( + provisioningState, + displayName, + signalKind, + refreshInterval, + labels ?? new ChangeTrackingDictionary(), + dataUnit, + evaluationRules, + deletionDate, + serializedAdditionalRawData, + queryText, + timeGrain); + } + + 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(PrometheusMetricsSignalDefinitionProperties)} does not support writing '{options.Format}' format."); + } + } + + PrometheusMetricsSignalDefinitionProperties 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 DeserializePrometheusMetricsSignalDefinitionProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PrometheusMetricsSignalDefinitionProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/PrometheusMetricsSignalDefinitionProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/PrometheusMetricsSignalDefinitionProperties.cs new file mode 100644 index 000000000000..225db91336c7 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/PrometheusMetricsSignalDefinitionProperties.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Prometheus Metrics Signal Definition properties. + public partial class PrometheusMetricsSignalDefinitionProperties : SignalDefinitionProperties + { + /// Initializes a new instance of . + /// Evaluation rules for the signal definition. + /// Query text in PromQL syntax. + /// or is null. + public PrometheusMetricsSignalDefinitionProperties(EvaluationRule evaluationRules, string queryText) : base(evaluationRules) + { + Argument.AssertNotNull(evaluationRules, nameof(evaluationRules)); + Argument.AssertNotNull(queryText, nameof(queryText)); + + QueryText = queryText; + SignalKind = SignalKind.PrometheusMetricsQuery; + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Kind of the signal definition. + /// Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + /// Optional set of labels (key-value pairs). + /// Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)). + /// Evaluation rules for the signal definition. + /// Date when the signal definition was (soft-)deleted. + /// Keeps track of any properties unknown to the library. + /// Query text in PromQL syntax. + /// Time range of signal. ISO duration format like PT10M. + internal PrometheusMetricsSignalDefinitionProperties(HealthModelProvisioningState? provisioningState, string displayName, SignalKind signalKind, RefreshInterval? refreshInterval, IDictionary labels, string dataUnit, EvaluationRule evaluationRules, DateTimeOffset? deletedOn, IDictionary serializedAdditionalRawData, string queryText, string timeGrain) : base(provisioningState, displayName, signalKind, refreshInterval, labels, dataUnit, evaluationRules, deletedOn, serializedAdditionalRawData) + { + QueryText = queryText; + TimeGrain = timeGrain; + SignalKind = signalKind; + } + + /// Initializes a new instance of for deserialization. + internal PrometheusMetricsSignalDefinitionProperties() + { + } + + /// Query text in PromQL syntax. + public string QueryText { get; set; } + /// Time range of signal. ISO duration format like PT10M. + public string TimeGrain { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RefreshInterval.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RefreshInterval.cs new file mode 100644 index 000000000000..ec73cb82eae1 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RefreshInterval.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Refresh interval in ISO duration format. + public readonly partial struct RefreshInterval : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public RefreshInterval(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string PT1MValue = "PT1M"; + private const string PT5MValue = "PT5M"; + private const string PT10MValue = "PT10M"; + private const string PT30MValue = "PT30M"; + private const string PT1HValue = "PT1H"; + private const string PT2HValue = "PT2H"; + + /// One Minute. + public static RefreshInterval PT1M { get; } = new RefreshInterval(PT1MValue); + /// Five Minutes. + public static RefreshInterval PT5M { get; } = new RefreshInterval(PT5MValue); + /// Ten Minutes. + public static RefreshInterval PT10M { get; } = new RefreshInterval(PT10MValue); + /// Thirty Minutes. + public static RefreshInterval PT30M { get; } = new RefreshInterval(PT30MValue); + /// One Hour. + public static RefreshInterval PT1H { get; } = new RefreshInterval(PT1HValue); + /// Two Hours. + public static RefreshInterval PT2H { get; } = new RefreshInterval(PT2HValue); + /// Determines if two values are the same. + public static bool operator ==(RefreshInterval left, RefreshInterval right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(RefreshInterval left, RefreshInterval right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator RefreshInterval(string value) => new RefreshInterval(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is RefreshInterval other && Equals(other); + /// + public bool Equals(RefreshInterval 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RelationshipListResult.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RelationshipListResult.Serialization.cs new file mode 100644 index 000000000000..960a80cf2133 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RelationshipListResult.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.CloudHealth.Models +{ + internal partial class RelationshipListResult : 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(RelationshipListResult)} 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 + } + } + } + + RelationshipListResult 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(RelationshipListResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRelationshipListResult(document.RootElement, options); + } + + internal static RelationshipListResult DeserializeRelationshipListResult(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(RelationshipData.DeserializeRelationshipData(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 RelationshipListResult(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(RelationshipListResult)} does not support writing '{options.Format}' format."); + } + } + + RelationshipListResult 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 DeserializeRelationshipListResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RelationshipListResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RelationshipListResult.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RelationshipListResult.cs new file mode 100644 index 000000000000..5b4ed302d883 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RelationshipListResult.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.CloudHealth.Models +{ + /// The response of a Relationship list operation. + internal partial class RelationshipListResult + { + /// + /// 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 Relationship items on this page. + /// is null. + internal RelationshipListResult(IEnumerable value) + { + Argument.AssertNotNull(value, nameof(value)); + + Value = value.ToList(); + } + + /// Initializes a new instance of . + /// The Relationship items on this page. + /// The link to the next page of items. + /// Keeps track of any properties unknown to the library. + internal RelationshipListResult(IReadOnlyList value, Uri nextLink, IDictionary serializedAdditionalRawData) + { + Value = value; + NextLink = nextLink; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RelationshipListResult() + { + } + + /// The Relationship items on this page. + public IReadOnlyList Value { get; } + /// The link to the next page of items. + public Uri NextLink { get; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RelationshipProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RelationshipProperties.Serialization.cs new file mode 100644 index 000000000000..1b5c1945887e --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RelationshipProperties.Serialization.cs @@ -0,0 +1,220 @@ +// 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.CloudHealth.Models +{ + public partial class RelationshipProperties : 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(RelationshipProperties)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(ProvisioningState)) + { + writer.WritePropertyName("provisioningState"u8); + writer.WriteStringValue(ProvisioningState.Value.ToString()); + } + if (Optional.IsDefined(DisplayName)) + { + writer.WritePropertyName("displayName"u8); + writer.WriteStringValue(DisplayName); + } + writer.WritePropertyName("parentEntityName"u8); + writer.WriteStringValue(ParentEntityName); + writer.WritePropertyName("childEntityName"u8); + writer.WriteStringValue(ChildEntityName); + if (Optional.IsCollectionDefined(Labels)) + { + writer.WritePropertyName("labels"u8); + writer.WriteStartObject(); + foreach (var item in Labels) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (options.Format != "W" && Optional.IsDefined(DiscoveredBy)) + { + writer.WritePropertyName("discoveredBy"u8); + writer.WriteStringValue(DiscoveredBy); + } + if (options.Format != "W" && Optional.IsDefined(DeletedOn)) + { + writer.WritePropertyName("deletionDate"u8); + writer.WriteStringValue(DeletedOn.Value, "O"); + } + 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 + } + } + } + + RelationshipProperties 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(RelationshipProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRelationshipProperties(document.RootElement, options); + } + + internal static RelationshipProperties DeserializeRelationshipProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + HealthModelProvisioningState? provisioningState = default; + string displayName = default; + string parentEntityName = default; + string childEntityName = default; + IDictionary labels = default; + string discoveredBy = default; + DateTimeOffset? deletionDate = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("provisioningState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + provisioningState = new HealthModelProvisioningState(property.Value.GetString()); + continue; + } + if (property.NameEquals("displayName"u8)) + { + displayName = property.Value.GetString(); + continue; + } + if (property.NameEquals("parentEntityName"u8)) + { + parentEntityName = property.Value.GetString(); + continue; + } + if (property.NameEquals("childEntityName"u8)) + { + childEntityName = property.Value.GetString(); + continue; + } + if (property.NameEquals("labels"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()); + } + labels = dictionary; + continue; + } + if (property.NameEquals("discoveredBy"u8)) + { + discoveredBy = property.Value.GetString(); + continue; + } + if (property.NameEquals("deletionDate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + deletionDate = property.Value.GetDateTimeOffset("O"); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RelationshipProperties( + provisioningState, + displayName, + parentEntityName, + childEntityName, + labels ?? new ChangeTrackingDictionary(), + discoveredBy, + deletionDate, + 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(RelationshipProperties)} does not support writing '{options.Format}' format."); + } + } + + RelationshipProperties 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 DeserializeRelationshipProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RelationshipProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RelationshipProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RelationshipProperties.cs new file mode 100644 index 000000000000..3b5f3461ee20 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/RelationshipProperties.cs @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Relationship properties. + public partial class RelationshipProperties + { + /// + /// 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 . + /// Resource name of the parent entity. + /// Resource name of the child entity. + /// or is null. + public RelationshipProperties(string parentEntityName, string childEntityName) + { + Argument.AssertNotNull(parentEntityName, nameof(parentEntityName)); + Argument.AssertNotNull(childEntityName, nameof(childEntityName)); + + ParentEntityName = parentEntityName; + ChildEntityName = childEntityName; + Labels = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Resource name of the parent entity. + /// Resource name of the child entity. + /// Optional set of labels (key-value pairs). + /// Discovered by which discovery rule. If set, the relationship cannot be deleted manually. + /// Date when the relationship was (soft-)deleted. + /// Keeps track of any properties unknown to the library. + internal RelationshipProperties(HealthModelProvisioningState? provisioningState, string displayName, string parentEntityName, string childEntityName, IDictionary labels, string discoveredBy, DateTimeOffset? deletedOn, IDictionary serializedAdditionalRawData) + { + ProvisioningState = provisioningState; + DisplayName = displayName; + ParentEntityName = parentEntityName; + ChildEntityName = childEntityName; + Labels = labels; + DiscoveredBy = discoveredBy; + DeletedOn = deletedOn; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RelationshipProperties() + { + } + + /// The status of the last operation. + public HealthModelProvisioningState? ProvisioningState { get; } + /// Display name. + public string DisplayName { get; set; } + /// Resource name of the parent entity. + public string ParentEntityName { get; set; } + /// Resource name of the child entity. + public string ChildEntityName { get; set; } + /// Optional set of labels (key-value pairs). + public IDictionary Labels { get; } + /// Discovered by which discovery rule. If set, the relationship cannot be deleted manually. + public string DiscoveredBy { get; } + /// Date when the relationship was (soft-)deleted. + public DateTimeOffset? DeletedOn { get; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ResourceMetricSignalDefinitionProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ResourceMetricSignalDefinitionProperties.Serialization.cs new file mode 100644 index 000000000000..892a898c5311 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ResourceMetricSignalDefinitionProperties.Serialization.cs @@ -0,0 +1,242 @@ +// 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.CloudHealth.Models +{ + public partial class ResourceMetricSignalDefinitionProperties : 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(ResourceMetricSignalDefinitionProperties)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("metricNamespace"u8); + writer.WriteStringValue(MetricNamespace); + writer.WritePropertyName("metricName"u8); + writer.WriteStringValue(MetricName); + writer.WritePropertyName("timeGrain"u8); + writer.WriteStringValue(TimeGrain); + writer.WritePropertyName("aggregationType"u8); + writer.WriteStringValue(AggregationType.ToString()); + if (Optional.IsDefined(Dimension)) + { + writer.WritePropertyName("dimension"u8); + writer.WriteStringValue(Dimension); + } + if (Optional.IsDefined(DimensionFilter)) + { + writer.WritePropertyName("dimensionFilter"u8); + writer.WriteStringValue(DimensionFilter); + } + } + + ResourceMetricSignalDefinitionProperties 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(ResourceMetricSignalDefinitionProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeResourceMetricSignalDefinitionProperties(document.RootElement, options); + } + + internal static ResourceMetricSignalDefinitionProperties DeserializeResourceMetricSignalDefinitionProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string metricNamespace = default; + string metricName = default; + string timeGrain = default; + MetricAggregationType aggregationType = default; + string dimension = default; + string dimensionFilter = default; + HealthModelProvisioningState? provisioningState = default; + string displayName = default; + SignalKind signalKind = default; + RefreshInterval? refreshInterval = default; + IDictionary labels = default; + string dataUnit = default; + EvaluationRule evaluationRules = default; + DateTimeOffset? deletionDate = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("metricNamespace"u8)) + { + metricNamespace = property.Value.GetString(); + continue; + } + if (property.NameEquals("metricName"u8)) + { + metricName = property.Value.GetString(); + continue; + } + if (property.NameEquals("timeGrain"u8)) + { + timeGrain = property.Value.GetString(); + continue; + } + if (property.NameEquals("aggregationType"u8)) + { + aggregationType = new MetricAggregationType(property.Value.GetString()); + continue; + } + if (property.NameEquals("dimension"u8)) + { + dimension = property.Value.GetString(); + continue; + } + if (property.NameEquals("dimensionFilter"u8)) + { + dimensionFilter = property.Value.GetString(); + continue; + } + if (property.NameEquals("provisioningState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + provisioningState = new HealthModelProvisioningState(property.Value.GetString()); + continue; + } + if (property.NameEquals("displayName"u8)) + { + displayName = property.Value.GetString(); + continue; + } + if (property.NameEquals("signalKind"u8)) + { + signalKind = new SignalKind(property.Value.GetString()); + continue; + } + if (property.NameEquals("refreshInterval"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + refreshInterval = new RefreshInterval(property.Value.GetString()); + continue; + } + if (property.NameEquals("labels"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()); + } + labels = dictionary; + continue; + } + if (property.NameEquals("dataUnit"u8)) + { + dataUnit = property.Value.GetString(); + continue; + } + if (property.NameEquals("evaluationRules"u8)) + { + evaluationRules = EvaluationRule.DeserializeEvaluationRule(property.Value, options); + continue; + } + if (property.NameEquals("deletionDate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + deletionDate = property.Value.GetDateTimeOffset("O"); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ResourceMetricSignalDefinitionProperties( + provisioningState, + displayName, + signalKind, + refreshInterval, + labels ?? new ChangeTrackingDictionary(), + dataUnit, + evaluationRules, + deletionDate, + serializedAdditionalRawData, + metricNamespace, + metricName, + timeGrain, + aggregationType, + dimension, + dimensionFilter); + } + + 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(ResourceMetricSignalDefinitionProperties)} does not support writing '{options.Format}' format."); + } + } + + ResourceMetricSignalDefinitionProperties 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 DeserializeResourceMetricSignalDefinitionProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ResourceMetricSignalDefinitionProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ResourceMetricSignalDefinitionProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ResourceMetricSignalDefinitionProperties.cs new file mode 100644 index 000000000000..6aebd5233564 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ResourceMetricSignalDefinitionProperties.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Azure Resource Metric Signal Definition properties. + public partial class ResourceMetricSignalDefinitionProperties : SignalDefinitionProperties + { + /// Initializes a new instance of . + /// Evaluation rules for the signal definition. + /// Metric namespace. + /// Name of the metric. + /// Time range of signal. ISO duration format like PT10M. + /// Type of aggregation to apply to the metric. + /// , , or is null. + public ResourceMetricSignalDefinitionProperties(EvaluationRule evaluationRules, string metricNamespace, string metricName, string timeGrain, MetricAggregationType aggregationType) : base(evaluationRules) + { + Argument.AssertNotNull(evaluationRules, nameof(evaluationRules)); + Argument.AssertNotNull(metricNamespace, nameof(metricNamespace)); + Argument.AssertNotNull(metricName, nameof(metricName)); + Argument.AssertNotNull(timeGrain, nameof(timeGrain)); + + MetricNamespace = metricNamespace; + MetricName = metricName; + TimeGrain = timeGrain; + AggregationType = aggregationType; + SignalKind = SignalKind.AzureResourceMetric; + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Kind of the signal definition. + /// Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + /// Optional set of labels (key-value pairs). + /// Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)). + /// Evaluation rules for the signal definition. + /// Date when the signal definition was (soft-)deleted. + /// Keeps track of any properties unknown to the library. + /// Metric namespace. + /// Name of the metric. + /// Time range of signal. ISO duration format like PT10M. + /// Type of aggregation to apply to the metric. + /// Optional: Dimension to split by. + /// Optional: Dimension filter to apply to the dimension. Must only be set if also Dimension is set. + internal ResourceMetricSignalDefinitionProperties(HealthModelProvisioningState? provisioningState, string displayName, SignalKind signalKind, RefreshInterval? refreshInterval, IDictionary labels, string dataUnit, EvaluationRule evaluationRules, DateTimeOffset? deletedOn, IDictionary serializedAdditionalRawData, string metricNamespace, string metricName, string timeGrain, MetricAggregationType aggregationType, string dimension, string dimensionFilter) : base(provisioningState, displayName, signalKind, refreshInterval, labels, dataUnit, evaluationRules, deletedOn, serializedAdditionalRawData) + { + MetricNamespace = metricNamespace; + MetricName = metricName; + TimeGrain = timeGrain; + AggregationType = aggregationType; + Dimension = dimension; + DimensionFilter = dimensionFilter; + SignalKind = signalKind; + } + + /// Initializes a new instance of for deserialization. + internal ResourceMetricSignalDefinitionProperties() + { + } + + /// Metric namespace. + public string MetricNamespace { get; set; } + /// Name of the metric. + public string MetricName { get; set; } + /// Time range of signal. ISO duration format like PT10M. + public string TimeGrain { get; set; } + /// Type of aggregation to apply to the metric. + public MetricAggregationType AggregationType { get; set; } + /// Optional: Dimension to split by. + public string Dimension { get; set; } + /// Optional: Dimension filter to apply to the dimension. Must only be set if also Dimension is set. + public string DimensionFilter { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalAssignment.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalAssignment.Serialization.cs new file mode 100644 index 000000000000..7d005589a6ba --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalAssignment.Serialization.cs @@ -0,0 +1,136 @@ +// 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.CloudHealth.Models +{ + public partial class SignalAssignment : 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(SignalAssignment)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("signalDefinitions"u8); + writer.WriteStartArray(); + foreach (var item in SignalDefinitions) + { + writer.WriteStringValue(item); + } + 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 + } + } + } + + SignalAssignment 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(SignalAssignment)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSignalAssignment(document.RootElement, options); + } + + internal static SignalAssignment DeserializeSignalAssignment(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList signalDefinitions = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("signalDefinitions"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + signalDefinitions = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SignalAssignment(signalDefinitions, 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(SignalAssignment)} does not support writing '{options.Format}' format."); + } + } + + SignalAssignment 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 DeserializeSignalAssignment(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SignalAssignment)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalAssignment.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalAssignment.cs new file mode 100644 index 000000000000..ad35d8459097 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalAssignment.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.ResourceManager.CloudHealth.Models +{ + /// Group of signal definition assignments. + public partial class SignalAssignment + { + /// + /// 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 . + /// Signal definitions referenced by their names. All definitions are combined with an AND operator. + /// is null. + public SignalAssignment(IEnumerable signalDefinitions) + { + Argument.AssertNotNull(signalDefinitions, nameof(signalDefinitions)); + + SignalDefinitions = signalDefinitions.ToList(); + } + + /// Initializes a new instance of . + /// Signal definitions referenced by their names. All definitions are combined with an AND operator. + /// Keeps track of any properties unknown to the library. + internal SignalAssignment(IList signalDefinitions, IDictionary serializedAdditionalRawData) + { + SignalDefinitions = signalDefinitions; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SignalAssignment() + { + } + + /// Signal definitions referenced by their names. All definitions are combined with an AND operator. + public IList SignalDefinitions { get; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalDefinitionListResult.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalDefinitionListResult.Serialization.cs new file mode 100644 index 000000000000..a49fdbdcdbd0 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalDefinitionListResult.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.CloudHealth.Models +{ + internal partial class SignalDefinitionListResult : 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(SignalDefinitionListResult)} 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 + } + } + } + + SignalDefinitionListResult 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(SignalDefinitionListResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSignalDefinitionListResult(document.RootElement, options); + } + + internal static SignalDefinitionListResult DeserializeSignalDefinitionListResult(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(SignalDefinitionData.DeserializeSignalDefinitionData(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 SignalDefinitionListResult(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(SignalDefinitionListResult)} does not support writing '{options.Format}' format."); + } + } + + SignalDefinitionListResult 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 DeserializeSignalDefinitionListResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SignalDefinitionListResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalDefinitionListResult.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalDefinitionListResult.cs new file mode 100644 index 000000000000..2198ae75cb21 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalDefinitionListResult.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.CloudHealth.Models +{ + /// The response of a SignalDefinition list operation. + internal partial class SignalDefinitionListResult + { + /// + /// 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 SignalDefinition items on this page. + /// is null. + internal SignalDefinitionListResult(IEnumerable value) + { + Argument.AssertNotNull(value, nameof(value)); + + Value = value.ToList(); + } + + /// Initializes a new instance of . + /// The SignalDefinition items on this page. + /// The link to the next page of items. + /// Keeps track of any properties unknown to the library. + internal SignalDefinitionListResult(IReadOnlyList value, Uri nextLink, IDictionary serializedAdditionalRawData) + { + Value = value; + NextLink = nextLink; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SignalDefinitionListResult() + { + } + + /// The SignalDefinition items on this page. + public IReadOnlyList Value { get; } + /// The link to the next page of items. + public Uri NextLink { get; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalDefinitionProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalDefinitionProperties.Serialization.cs new file mode 100644 index 000000000000..ad5ac7dab839 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalDefinitionProperties.Serialization.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + [PersistableModelProxy(typeof(UnknownSignalDefinitionProperties))] + public partial class SignalDefinitionProperties : 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(SignalDefinitionProperties)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(ProvisioningState)) + { + writer.WritePropertyName("provisioningState"u8); + writer.WriteStringValue(ProvisioningState.Value.ToString()); + } + if (Optional.IsDefined(DisplayName)) + { + writer.WritePropertyName("displayName"u8); + writer.WriteStringValue(DisplayName); + } + writer.WritePropertyName("signalKind"u8); + writer.WriteStringValue(SignalKind.ToString()); + if (Optional.IsDefined(RefreshInterval)) + { + writer.WritePropertyName("refreshInterval"u8); + writer.WriteStringValue(RefreshInterval.Value.ToString()); + } + if (Optional.IsCollectionDefined(Labels)) + { + writer.WritePropertyName("labels"u8); + writer.WriteStartObject(); + foreach (var item in Labels) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsDefined(DataUnit)) + { + writer.WritePropertyName("dataUnit"u8); + writer.WriteStringValue(DataUnit); + } + writer.WritePropertyName("evaluationRules"u8); + writer.WriteObjectValue(EvaluationRules, options); + if (options.Format != "W" && Optional.IsDefined(DeletedOn)) + { + writer.WritePropertyName("deletionDate"u8); + writer.WriteStringValue(DeletedOn.Value, "O"); + } + 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 + } + } + } + + SignalDefinitionProperties 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(SignalDefinitionProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSignalDefinitionProperties(document.RootElement, options); + } + + internal static SignalDefinitionProperties DeserializeSignalDefinitionProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("signalKind", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "AzureResourceMetric": return ResourceMetricSignalDefinitionProperties.DeserializeResourceMetricSignalDefinitionProperties(element, options); + case "LogAnalyticsQuery": return LogAnalyticsQuerySignalDefinitionProperties.DeserializeLogAnalyticsQuerySignalDefinitionProperties(element, options); + case "PrometheusMetricsQuery": return PrometheusMetricsSignalDefinitionProperties.DeserializePrometheusMetricsSignalDefinitionProperties(element, options); + } + } + return UnknownSignalDefinitionProperties.DeserializeUnknownSignalDefinitionProperties(element, options); + } + + 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(SignalDefinitionProperties)} does not support writing '{options.Format}' format."); + } + } + + SignalDefinitionProperties 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 DeserializeSignalDefinitionProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SignalDefinitionProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalDefinitionProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalDefinitionProperties.cs new file mode 100644 index 000000000000..8a6e6c7771e0 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalDefinitionProperties.cs @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// + /// SignalDefinition properties + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public abstract partial class SignalDefinitionProperties + { + /// + /// 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 protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Evaluation rules for the signal definition. + /// is null. + protected SignalDefinitionProperties(EvaluationRule evaluationRules) + { + Argument.AssertNotNull(evaluationRules, nameof(evaluationRules)); + + Labels = new ChangeTrackingDictionary(); + EvaluationRules = evaluationRules; + } + + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Kind of the signal definition. + /// Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + /// Optional set of labels (key-value pairs). + /// Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)). + /// Evaluation rules for the signal definition. + /// Date when the signal definition was (soft-)deleted. + /// Keeps track of any properties unknown to the library. + internal SignalDefinitionProperties(HealthModelProvisioningState? provisioningState, string displayName, SignalKind signalKind, RefreshInterval? refreshInterval, IDictionary labels, string dataUnit, EvaluationRule evaluationRules, DateTimeOffset? deletedOn, IDictionary serializedAdditionalRawData) + { + ProvisioningState = provisioningState; + DisplayName = displayName; + SignalKind = signalKind; + RefreshInterval = refreshInterval; + Labels = labels; + DataUnit = dataUnit; + EvaluationRules = evaluationRules; + DeletedOn = deletedOn; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SignalDefinitionProperties() + { + } + + /// The status of the last operation. + public HealthModelProvisioningState? ProvisioningState { get; } + /// Display name. + public string DisplayName { get; set; } + /// Kind of the signal definition. + internal SignalKind SignalKind { get; set; } + /// Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + public RefreshInterval? RefreshInterval { get; set; } + /// Optional set of labels (key-value pairs). + public IDictionary Labels { get; } + /// Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)). + public string DataUnit { get; set; } + /// Evaluation rules for the signal definition. + public EvaluationRule EvaluationRules { get; set; } + /// Date when the signal definition was (soft-)deleted. + public DateTimeOffset? DeletedOn { get; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalGroup.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalGroup.Serialization.cs new file mode 100644 index 000000000000..3280d1d9bc6f --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalGroup.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; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + public partial class SignalGroup : 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(SignalGroup)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(AzureResource)) + { + writer.WritePropertyName("azureResource"u8); + writer.WriteObjectValue(AzureResource, options); + } + if (Optional.IsDefined(AzureLogAnalytics)) + { + writer.WritePropertyName("azureLogAnalytics"u8); + writer.WriteObjectValue(AzureLogAnalytics, options); + } + if (Optional.IsDefined(AzureMonitorWorkspace)) + { + writer.WritePropertyName("azureMonitorWorkspace"u8); + writer.WriteObjectValue(AzureMonitorWorkspace, options); + } + if (Optional.IsDefined(Dependencies)) + { + writer.WritePropertyName("dependencies"u8); + writer.WriteObjectValue(Dependencies, 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 + } + } + } + + SignalGroup 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(SignalGroup)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSignalGroup(document.RootElement, options); + } + + internal static SignalGroup DeserializeSignalGroup(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AzureResourceSignalGroup azureResource = default; + LogAnalyticsSignalGroup azureLogAnalytics = default; + AzureMonitorWorkspaceSignalGroup azureMonitorWorkspace = default; + DependenciesSignalGroup dependencies = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("azureResource"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + azureResource = AzureResourceSignalGroup.DeserializeAzureResourceSignalGroup(property.Value, options); + continue; + } + if (property.NameEquals("azureLogAnalytics"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + azureLogAnalytics = LogAnalyticsSignalGroup.DeserializeLogAnalyticsSignalGroup(property.Value, options); + continue; + } + if (property.NameEquals("azureMonitorWorkspace"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + azureMonitorWorkspace = AzureMonitorWorkspaceSignalGroup.DeserializeAzureMonitorWorkspaceSignalGroup(property.Value, options); + continue; + } + if (property.NameEquals("dependencies"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + dependencies = DependenciesSignalGroup.DeserializeDependenciesSignalGroup(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SignalGroup(azureResource, azureLogAnalytics, azureMonitorWorkspace, dependencies, 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(SignalGroup)} does not support writing '{options.Format}' format."); + } + } + + SignalGroup 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 DeserializeSignalGroup(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SignalGroup)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalGroup.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalGroup.cs new file mode 100644 index 000000000000..b8cb1f6d1e3b --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalGroup.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.CloudHealth.Models +{ + /// Contains various signal groups that can be assigned to an entity. + public partial class SignalGroup + { + /// + /// 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 SignalGroup() + { + } + + /// Initializes a new instance of . + /// Azure Resource Signal Group. + /// Log Analytics Signal Group. + /// Azure Monitor Workspace Signal Group. + /// Settings for dependency signals to control how the health state of child entities influences the health state of the parent entity. + /// Keeps track of any properties unknown to the library. + internal SignalGroup(AzureResourceSignalGroup azureResource, LogAnalyticsSignalGroup azureLogAnalytics, AzureMonitorWorkspaceSignalGroup azureMonitorWorkspace, DependenciesSignalGroup dependencies, IDictionary serializedAdditionalRawData) + { + AzureResource = azureResource; + AzureLogAnalytics = azureLogAnalytics; + AzureMonitorWorkspace = azureMonitorWorkspace; + Dependencies = dependencies; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Azure Resource Signal Group. + public AzureResourceSignalGroup AzureResource { get; set; } + /// Log Analytics Signal Group. + public LogAnalyticsSignalGroup AzureLogAnalytics { get; set; } + /// Azure Monitor Workspace Signal Group. + public AzureMonitorWorkspaceSignalGroup AzureMonitorWorkspace { get; set; } + /// Settings for dependency signals to control how the health state of child entities influences the health state of the parent entity. + public DependenciesSignalGroup Dependencies { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalKind.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalKind.cs new file mode 100644 index 000000000000..720760422456 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalKind.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Supported signal kinds as discriminator. + internal readonly partial struct SignalKind : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public SignalKind(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AzureResourceMetricValue = "AzureResourceMetric"; + private const string LogAnalyticsQueryValue = "LogAnalyticsQuery"; + private const string PrometheusMetricsQueryValue = "PrometheusMetricsQuery"; + + /// AzureResourceMetric. + public static SignalKind AzureResourceMetric { get; } = new SignalKind(AzureResourceMetricValue); + /// LogAnalyticsQuery. + public static SignalKind LogAnalyticsQuery { get; } = new SignalKind(LogAnalyticsQueryValue); + /// PrometheusMetricsQuery. + public static SignalKind PrometheusMetricsQuery { get; } = new SignalKind(PrometheusMetricsQueryValue); + /// Determines if two values are the same. + public static bool operator ==(SignalKind left, SignalKind right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(SignalKind left, SignalKind right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator SignalKind(string value) => new SignalKind(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is SignalKind other && Equals(other); + /// + public bool Equals(SignalKind 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalOperator.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalOperator.cs new file mode 100644 index 000000000000..d09a50cdbbae --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/SignalOperator.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.ResourceManager.CloudHealth.Models +{ + /// Signal operator. + public readonly partial struct SignalOperator : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public SignalOperator(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string LowerThanValue = "LowerThan"; + private const string LowerOrEqualsValue = "LowerOrEquals"; + private const string GreaterThanValue = "GreaterThan"; + private const string GreaterOrEqualsValue = "GreaterOrEquals"; + private const string EqualsValueValue = "Equals"; + + /// Lower than. + public static SignalOperator LowerThan { get; } = new SignalOperator(LowerThanValue); + /// Lower than or equal to. + public static SignalOperator LowerOrEquals { get; } = new SignalOperator(LowerOrEqualsValue); + /// Greater than. + public static SignalOperator GreaterThan { get; } = new SignalOperator(GreaterThanValue); + /// Greater than or equal to. + public static SignalOperator GreaterOrEquals { get; } = new SignalOperator(GreaterOrEqualsValue); + /// Equal to. + public static SignalOperator EqualsValue { get; } = new SignalOperator(EqualsValueValue); + /// Determines if two values are the same. + public static bool operator ==(SignalOperator left, SignalOperator right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(SignalOperator left, SignalOperator right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator SignalOperator(string value) => new SignalOperator(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is SignalOperator other && Equals(other); + /// + public bool Equals(SignalOperator 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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ThresholdRule.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ThresholdRule.Serialization.cs new file mode 100644 index 000000000000..544a2753479b --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ThresholdRule.Serialization.cs @@ -0,0 +1,134 @@ +// 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.CloudHealth.Models +{ + public partial class ThresholdRule : 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(ThresholdRule)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("operator"u8); + writer.WriteStringValue(Operator.ToString()); + writer.WritePropertyName("threshold"u8); + writer.WriteStringValue(Threshold); + 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 + } + } + } + + ThresholdRule 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(ThresholdRule)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeThresholdRule(document.RootElement, options); + } + + internal static ThresholdRule DeserializeThresholdRule(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + SignalOperator @operator = default; + string threshold = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("operator"u8)) + { + @operator = new SignalOperator(property.Value.GetString()); + continue; + } + if (property.NameEquals("threshold"u8)) + { + threshold = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ThresholdRule(@operator, threshold, 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(ThresholdRule)} does not support writing '{options.Format}' format."); + } + } + + ThresholdRule 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 DeserializeThresholdRule(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ThresholdRule)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ThresholdRule.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ThresholdRule.cs new file mode 100644 index 000000000000..93557ef6ffe0 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/ThresholdRule.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.ResourceManager.CloudHealth.Models +{ + /// Threshold-based evaluation rule for a signal definition. + public partial class ThresholdRule + { + /// + /// 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 . + /// Operator how to compare the signal value with the threshold. + /// Threshold value. + /// is null. + public ThresholdRule(SignalOperator @operator, string threshold) + { + Argument.AssertNotNull(threshold, nameof(threshold)); + + Operator = @operator; + Threshold = threshold; + } + + /// Initializes a new instance of . + /// Operator how to compare the signal value with the threshold. + /// Threshold value. + /// Keeps track of any properties unknown to the library. + internal ThresholdRule(SignalOperator @operator, string threshold, IDictionary serializedAdditionalRawData) + { + Operator = @operator; + Threshold = threshold; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ThresholdRule() + { + } + + /// Operator how to compare the signal value with the threshold. + public SignalOperator Operator { get; set; } + /// Threshold value. + public string Threshold { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/UnknownAuthenticationSettingProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/UnknownAuthenticationSettingProperties.Serialization.cs new file mode 100644 index 000000000000..bfae3049242d --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/UnknownAuthenticationSettingProperties.Serialization.cs @@ -0,0 +1,126 @@ +// 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.CloudHealth.Models +{ + internal partial class UnknownAuthenticationSettingProperties : 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(AuthenticationSettingProperties)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + AuthenticationSettingProperties 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(AuthenticationSettingProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAuthenticationSettingProperties(document.RootElement, options); + } + + internal static UnknownAuthenticationSettingProperties DeserializeUnknownAuthenticationSettingProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + HealthModelProvisioningState? provisioningState = default; + string displayName = default; + AuthenticationKind authenticationKind = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("provisioningState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + provisioningState = new HealthModelProvisioningState(property.Value.GetString()); + continue; + } + if (property.NameEquals("displayName"u8)) + { + displayName = property.Value.GetString(); + continue; + } + if (property.NameEquals("authenticationKind"u8)) + { + authenticationKind = new AuthenticationKind(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownAuthenticationSettingProperties(provisioningState, displayName, authenticationKind, 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(AuthenticationSettingProperties)} does not support writing '{options.Format}' format."); + } + } + + AuthenticationSettingProperties 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 DeserializeAuthenticationSettingProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AuthenticationSettingProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/UnknownAuthenticationSettingProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/UnknownAuthenticationSettingProperties.cs new file mode 100644 index 000000000000..8ef3d1d1501e --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/UnknownAuthenticationSettingProperties.cs @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Unknown version of AuthenticationSettingProperties. + internal partial class UnknownAuthenticationSettingProperties : AuthenticationSettingProperties + { + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Kind of the authentication setting. + /// Keeps track of any properties unknown to the library. + internal UnknownAuthenticationSettingProperties(HealthModelProvisioningState? provisioningState, string displayName, AuthenticationKind authenticationKind, IDictionary serializedAdditionalRawData) : base(provisioningState, displayName, authenticationKind, serializedAdditionalRawData) + { + AuthenticationKind = authenticationKind; + } + + /// Initializes a new instance of for deserialization. + internal UnknownAuthenticationSettingProperties() + { + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/UnknownSignalDefinitionProperties.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/UnknownSignalDefinitionProperties.Serialization.cs new file mode 100644 index 000000000000..07c7760ac534 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/UnknownSignalDefinitionProperties.Serialization.cs @@ -0,0 +1,182 @@ +// 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.CloudHealth.Models +{ + internal partial class UnknownSignalDefinitionProperties : 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(SignalDefinitionProperties)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + SignalDefinitionProperties 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(SignalDefinitionProperties)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSignalDefinitionProperties(document.RootElement, options); + } + + internal static UnknownSignalDefinitionProperties DeserializeUnknownSignalDefinitionProperties(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + HealthModelProvisioningState? provisioningState = default; + string displayName = default; + SignalKind signalKind = "Unknown"; + RefreshInterval? refreshInterval = default; + IDictionary labels = default; + string dataUnit = default; + EvaluationRule evaluationRules = default; + DateTimeOffset? deletionDate = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("provisioningState"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + provisioningState = new HealthModelProvisioningState(property.Value.GetString()); + continue; + } + if (property.NameEquals("displayName"u8)) + { + displayName = property.Value.GetString(); + continue; + } + if (property.NameEquals("signalKind"u8)) + { + signalKind = new SignalKind(property.Value.GetString()); + continue; + } + if (property.NameEquals("refreshInterval"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + refreshInterval = new RefreshInterval(property.Value.GetString()); + continue; + } + if (property.NameEquals("labels"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()); + } + labels = dictionary; + continue; + } + if (property.NameEquals("dataUnit"u8)) + { + dataUnit = property.Value.GetString(); + continue; + } + if (property.NameEquals("evaluationRules"u8)) + { + evaluationRules = EvaluationRule.DeserializeEvaluationRule(property.Value, options); + continue; + } + if (property.NameEquals("deletionDate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + deletionDate = property.Value.GetDateTimeOffset("O"); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownSignalDefinitionProperties( + provisioningState, + displayName, + signalKind, + refreshInterval, + labels ?? new ChangeTrackingDictionary(), + dataUnit, + evaluationRules, + deletionDate, + 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(SignalDefinitionProperties)} does not support writing '{options.Format}' format."); + } + } + + SignalDefinitionProperties 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 DeserializeSignalDefinitionProperties(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SignalDefinitionProperties)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/UnknownSignalDefinitionProperties.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/UnknownSignalDefinitionProperties.cs new file mode 100644 index 000000000000..14c0de4a3ea8 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/Models/UnknownSignalDefinitionProperties.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.ResourceManager.CloudHealth.Models +{ + /// Unknown version of SignalDefinitionProperties. + internal partial class UnknownSignalDefinitionProperties : SignalDefinitionProperties + { + /// Initializes a new instance of . + /// The status of the last operation. + /// Display name. + /// Kind of the signal definition. + /// Interval in which the signal is being evaluated. Defaults to PT1M (1 minute). + /// Optional set of labels (key-value pairs). + /// Unit of the signal result (e.g. Bytes, MilliSeconds, Percent, Count)). + /// Evaluation rules for the signal definition. + /// Date when the signal definition was (soft-)deleted. + /// Keeps track of any properties unknown to the library. + internal UnknownSignalDefinitionProperties(HealthModelProvisioningState? provisioningState, string displayName, SignalKind signalKind, RefreshInterval? refreshInterval, IDictionary labels, string dataUnit, EvaluationRule evaluationRules, DateTimeOffset? deletedOn, IDictionary serializedAdditionalRawData) : base(provisioningState, displayName, signalKind, refreshInterval, labels, dataUnit, evaluationRules, deletedOn, serializedAdditionalRawData) + { + SignalKind = signalKind; + } + + /// Initializes a new instance of for deserialization. + internal UnknownSignalDefinitionProperties() + { + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/ProviderConstants.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/ProviderConstants.cs new file mode 100644 index 000000000000..e50ae6661902 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/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.CloudHealth +{ + internal static class ProviderConstants + { + public static string DefaultProviderNamespace { get; } = ClientDiagnostics.GetResourceProviderNamespace(typeof(ProviderConstants).Assembly); + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipCollection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipCollection.cs new file mode 100644 index 000000000000..559e07e0cae7 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipCollection.cs @@ -0,0 +1,499 @@ +// 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; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A class representing a collection of and their operations. + /// Each in the collection will belong to the same instance of . + /// To get a instance call the GetRelationships method from an instance of . + /// + public partial class RelationshipCollection : ArmCollection, IEnumerable, IAsyncEnumerable + { + private readonly ClientDiagnostics _relationshipClientDiagnostics; + private readonly RelationshipsRestOperations _relationshipRestClient; + + /// Initializes a new instance of the class for mocking. + protected RelationshipCollection() + { + } + + /// 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 RelationshipCollection(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _relationshipClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CloudHealth", RelationshipResource.ResourceType.Namespace, Diagnostics); + TryGetApiVersion(RelationshipResource.ResourceType, out string relationshipApiVersion); + _relationshipRestClient = new RelationshipsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, relationshipApiVersion); +#if DEBUG + ValidateResourceId(Id); +#endif + } + + internal static void ValidateResourceId(ResourceIdentifier id) + { + if (id.ResourceType != HealthModelResource.ResourceType) + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, HealthModelResource.ResourceType), nameof(id)); + } + + /// + /// Create a Relationship + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// 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 relationshipName, RelationshipData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _relationshipClientDiagnostics.CreateScope("RelationshipCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = await _relationshipRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, relationshipName, data, cancellationToken).ConfigureAwait(false); + var uri = _relationshipRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, relationshipName, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new RelationshipResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a Relationship + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// 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 relationshipName, RelationshipData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _relationshipClientDiagnostics.CreateScope("RelationshipCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = _relationshipRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, relationshipName, data, cancellationToken); + var uri = _relationshipRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, relationshipName, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new RelationshipResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a Relationship + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetAsync(string relationshipName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + + using var scope = _relationshipClientDiagnostics.CreateScope("RelationshipCollection.Get"); + scope.Start(); + try + { + var response = await _relationshipRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, relationshipName, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new RelationshipResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a Relationship + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Get(string relationshipName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + + using var scope = _relationshipClientDiagnostics.CreateScope("RelationshipCollection.Get"); + scope.Start(); + try + { + var response = _relationshipRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, relationshipName, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new RelationshipResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// List Relationship resources by HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships + /// + /// + /// Operation Id + /// Relationship_ListByHealthModel + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// An async collection of that may take multiple service requests to iterate over. + public virtual AsyncPageable GetAllAsync(DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => _relationshipRestClient.CreateListByHealthModelRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _relationshipRestClient.CreateListByHealthModelNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new RelationshipResource(Client, RelationshipData.DeserializeRelationshipData(e)), _relationshipClientDiagnostics, Pipeline, "RelationshipCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// List Relationship resources by HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships + /// + /// + /// Operation Id + /// Relationship_ListByHealthModel + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// A collection of that may take multiple service requests to iterate over. + public virtual Pageable GetAll(DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => _relationshipRestClient.CreateListByHealthModelRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _relationshipRestClient.CreateListByHealthModelNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new RelationshipResource(Client, RelationshipData.DeserializeRelationshipData(e)), _relationshipClientDiagnostics, Pipeline, "RelationshipCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// Checks to see if the resource exists in azure. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> ExistsAsync(string relationshipName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + + using var scope = _relationshipClientDiagnostics.CreateScope("RelationshipCollection.Exists"); + scope.Start(); + try + { + var response = await _relationshipRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, relationshipName, 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.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Exists(string relationshipName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + + using var scope = _relationshipClientDiagnostics.CreateScope("RelationshipCollection.Exists"); + scope.Start(); + try + { + var response = _relationshipRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, relationshipName, 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.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetIfExistsAsync(string relationshipName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + + using var scope = _relationshipClientDiagnostics.CreateScope("RelationshipCollection.GetIfExists"); + scope.Start(); + try + { + var response = await _relationshipRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, relationshipName, cancellationToken: cancellationToken).ConfigureAwait(false); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new RelationshipResource(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.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual NullableResponse GetIfExists(string relationshipName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + + using var scope = _relationshipClientDiagnostics.CreateScope("RelationshipCollection.GetIfExists"); + scope.Start(); + try + { + var response = _relationshipRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, relationshipName, cancellationToken: cancellationToken); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new RelationshipResource(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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipData.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipData.Serialization.cs new file mode 100644 index 000000000000..7813448eb413 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipData.Serialization.cs @@ -0,0 +1,155 @@ +// 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.CloudHealth.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + public partial class RelationshipData : 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(RelationshipData)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Properties)) + { + writer.WritePropertyName("properties"u8); + writer.WriteObjectValue(Properties, options); + } + } + + RelationshipData 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(RelationshipData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRelationshipData(document.RootElement, options); + } + + internal static RelationshipData DeserializeRelationshipData(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + RelationshipProperties properties = 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 = RelationshipProperties.DeserializeRelationshipProperties(property.Value, options); + 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 RelationshipData( + id, + name, + type, + systemData, + 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(RelationshipData)} does not support writing '{options.Format}' format."); + } + } + + RelationshipData 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 DeserializeRelationshipData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RelationshipData)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipData.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipData.cs new file mode 100644 index 000000000000..1f91a9e3fada --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipData.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; +using Azure.Core; +using Azure.ResourceManager.CloudHealth.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A class representing the Relationship data model. + /// A relationship (aka edge) between two entities in a health model + /// + public partial class RelationshipData : ResourceData + { + /// + /// 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 RelationshipData() + { + } + + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// The resource-specific properties for this resource. + /// Keeps track of any properties unknown to the library. + internal RelationshipData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, RelationshipProperties properties, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) + { + Properties = properties; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The resource-specific properties for this resource. + public RelationshipProperties Properties { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipResource.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipResource.Serialization.cs new file mode 100644 index 000000000000..6044c2185336 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipResource.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.CloudHealth +{ + public partial class RelationshipResource : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); + + RelationshipData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)Data).Create(ref reader, options); + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options); + + RelationshipData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options); + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)Data).GetFormatFromOptions(options); + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipResource.cs new file mode 100644 index 000000000000..040264ef05ae --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RelationshipResource.cs @@ -0,0 +1,355 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A Class representing a Relationship along with the instance operations that can be performed on it. + /// If you have a you can construct a + /// from an instance of using the GetRelationshipResource method. + /// Otherwise you can get one from its parent resource using the GetRelationship method. + /// + public partial class RelationshipResource : ArmResource + { + /// Generate the resource identifier of a instance. + /// The subscriptionId. + /// The resourceGroupName. + /// The healthModelName. + /// The relationshipName. + public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string healthModelName, string relationshipName) + { + var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName}"; + return new ResourceIdentifier(resourceId); + } + + private readonly ClientDiagnostics _relationshipClientDiagnostics; + private readonly RelationshipsRestOperations _relationshipRestClient; + private readonly RelationshipData _data; + + /// Gets the resource type for the operations. + public static readonly ResourceType ResourceType = "Microsoft.CloudHealth/healthmodels/relationships"; + + /// Initializes a new instance of the class for mocking. + protected RelationshipResource() + { + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The resource that is the target of operations. + internal RelationshipResource(ArmClient client, RelationshipData 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 RelationshipResource(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _relationshipClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CloudHealth", ResourceType.Namespace, Diagnostics); + TryGetApiVersion(ResourceType, out string relationshipApiVersion); + _relationshipRestClient = new RelationshipsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, relationshipApiVersion); +#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 RelationshipData 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 Relationship + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual async Task> GetAsync(CancellationToken cancellationToken = default) + { + using var scope = _relationshipClientDiagnostics.CreateScope("RelationshipResource.Get"); + scope.Start(); + try + { + var response = await _relationshipRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new RelationshipResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a Relationship + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual Response Get(CancellationToken cancellationToken = default) + { + using var scope = _relationshipClientDiagnostics.CreateScope("RelationshipResource.Get"); + scope.Start(); + try + { + var response = _relationshipRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new RelationshipResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a Relationship + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_Delete + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _relationshipClientDiagnostics.CreateScope("RelationshipResource.Delete"); + scope.Start(); + try + { + var response = await _relationshipRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); + var uri = _relationshipRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(response, rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a Relationship + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_Delete + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _relationshipClientDiagnostics.CreateScope("RelationshipResource.Delete"); + scope.Start(); + try + { + var response = _relationshipRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); + var uri = _relationshipRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(response, rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletionResponse(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a Relationship + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Resource create parameters. + /// The cancellation token to use. + /// is null. + public virtual async Task> UpdateAsync(WaitUntil waitUntil, RelationshipData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _relationshipClientDiagnostics.CreateScope("RelationshipResource.Update"); + scope.Start(); + try + { + var response = await _relationshipRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false); + var uri = _relationshipRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new RelationshipResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a Relationship + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/relationships/{relationshipName} + /// + /// + /// Operation Id + /// Relationship_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Resource create parameters. + /// The cancellation token to use. + /// is null. + public virtual ArmOperation Update(WaitUntil waitUntil, RelationshipData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _relationshipClientDiagnostics.CreateScope("RelationshipResource.Update"); + scope.Start(); + try + { + var response = _relationshipRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken); + var uri = _relationshipRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new RelationshipResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/AuthenticationSettingsRestOperations.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/AuthenticationSettingsRestOperations.cs new file mode 100644 index 000000000000..6f3b2034047d --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/AuthenticationSettingsRestOperations.cs @@ -0,0 +1,523 @@ +// 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.CloudHealth.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + internal partial class AuthenticationSettingsRestOperations + { + private readonly TelemetryDetails _userAgent; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// Initializes a new instance of AuthenticationSettingsRestOperations. + /// 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 AuthenticationSettingsRestOperations(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 ?? "2023-10-01-preview"; + _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); + } + + internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string authenticationSettingName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/authenticationsettings/", false); + uri.AppendPath(authenticationSettingName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string healthModelName, string authenticationSettingName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/authenticationsettings/", false); + uri.AppendPath(authenticationSettingName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Get a AuthenticationSetting. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the authentication setting. Must be unique within a health model. + /// 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 healthModelName, string authenticationSettingName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, healthModelName, authenticationSettingName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + AuthenticationSettingData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = AuthenticationSettingData.DeserializeAuthenticationSettingData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((AuthenticationSettingData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + /// Get a AuthenticationSetting. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the authentication setting. Must be unique within a health model. + /// 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 healthModelName, string authenticationSettingName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, healthModelName, authenticationSettingName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + AuthenticationSettingData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = AuthenticationSettingData.DeserializeAuthenticationSettingData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((AuthenticationSettingData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string authenticationSettingName, AuthenticationSettingData 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/authenticationsettings/", false); + uri.AppendPath(authenticationSettingName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string healthModelName, string authenticationSettingName, AuthenticationSettingData 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/authenticationsettings/", false); + uri.AppendPath(authenticationSettingName, 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 AuthenticationSetting. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the authentication setting. Must be unique within a health model. + /// 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 healthModelName, string authenticationSettingName, AuthenticationSettingData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, healthModelName, authenticationSettingName, data); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + case 201: + { + AuthenticationSettingData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = AuthenticationSettingData.DeserializeAuthenticationSettingData(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// Create a AuthenticationSetting. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the authentication setting. Must be unique within a health model. + /// 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 healthModelName, string authenticationSettingName, AuthenticationSettingData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, healthModelName, authenticationSettingName, data); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + case 201: + { + AuthenticationSettingData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = AuthenticationSettingData.DeserializeAuthenticationSettingData(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string authenticationSettingName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/authenticationsettings/", false); + uri.AppendPath(authenticationSettingName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string healthModelName, string authenticationSettingName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/authenticationsettings/", false); + uri.AppendPath(authenticationSettingName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Delete a AuthenticationSetting. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the authentication setting. Must be unique within a health model. + /// 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 healthModelName, string authenticationSettingName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, healthModelName, authenticationSettingName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + case 204: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + /// Delete a AuthenticationSetting. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the authentication setting. Must be unique within a health model. + /// 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 healthModelName, string authenticationSettingName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(authenticationSettingName, nameof(authenticationSettingName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, healthModelName, authenticationSettingName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + case 204: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListByHealthModelRequestUri(string subscriptionId, string resourceGroupName, string healthModelName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/authenticationsettings", false); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateListByHealthModelRequest(string subscriptionId, string resourceGroupName, string healthModelName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/authenticationsettings", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// List AuthenticationSetting resources by HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task> ListByHealthModelAsync(string subscriptionId, string resourceGroupName, string healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelRequest(subscriptionId, resourceGroupName, healthModelName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + AuthenticationSettingListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = AuthenticationSettingListResult.DeserializeAuthenticationSettingListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List AuthenticationSetting resources by HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response ListByHealthModel(string subscriptionId, string resourceGroupName, string healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelRequest(subscriptionId, resourceGroupName, healthModelName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + AuthenticationSettingListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = AuthenticationSettingListResult.DeserializeAuthenticationSettingListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListByHealthModelNextPageRequestUri(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + return uri; + } + + internal HttpMessage CreateListByHealthModelNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName) + { + 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 AuthenticationSetting resources by HealthModel. + /// 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. + /// Name of health model resource. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task> ListByHealthModelNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelNextPageRequest(nextLink, subscriptionId, resourceGroupName, healthModelName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + AuthenticationSettingListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = AuthenticationSettingListResult.DeserializeAuthenticationSettingListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List AuthenticationSetting resources by HealthModel. + /// 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. + /// Name of health model resource. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response ListByHealthModelNextPage(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelNextPageRequest(nextLink, subscriptionId, resourceGroupName, healthModelName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + AuthenticationSettingListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = AuthenticationSettingListResult.DeserializeAuthenticationSettingListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/DiscoveryRulesRestOperations.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/DiscoveryRulesRestOperations.cs new file mode 100644 index 000000000000..23ab0876b77f --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/DiscoveryRulesRestOperations.cs @@ -0,0 +1,535 @@ +// 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.CloudHealth.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + internal partial class DiscoveryRulesRestOperations + { + private readonly TelemetryDetails _userAgent; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// Initializes a new instance of DiscoveryRulesRestOperations. + /// 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 DiscoveryRulesRestOperations(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 ?? "2023-10-01-preview"; + _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); + } + + internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string discoveryRuleName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/discoveryrules/", false); + uri.AppendPath(discoveryRuleName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string healthModelName, string discoveryRuleName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/discoveryrules/", false); + uri.AppendPath(discoveryRuleName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Get a DiscoveryRule. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the discovery rule. Must be unique within a health model. + /// 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 healthModelName, string discoveryRuleName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, healthModelName, discoveryRuleName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + DiscoveryRuleData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = DiscoveryRuleData.DeserializeDiscoveryRuleData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((DiscoveryRuleData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + /// Get a DiscoveryRule. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the discovery rule. Must be unique within a health model. + /// 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 healthModelName, string discoveryRuleName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, healthModelName, discoveryRuleName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + DiscoveryRuleData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = DiscoveryRuleData.DeserializeDiscoveryRuleData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((DiscoveryRuleData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string discoveryRuleName, DiscoveryRuleData 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/discoveryrules/", false); + uri.AppendPath(discoveryRuleName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string healthModelName, string discoveryRuleName, DiscoveryRuleData 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/discoveryrules/", false); + uri.AppendPath(discoveryRuleName, 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 DiscoveryRule. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the discovery rule. Must be unique within a health model. + /// 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 healthModelName, string discoveryRuleName, DiscoveryRuleData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, healthModelName, discoveryRuleName, data); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + case 201: + { + DiscoveryRuleData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = DiscoveryRuleData.DeserializeDiscoveryRuleData(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// Create a DiscoveryRule. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the discovery rule. Must be unique within a health model. + /// 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 healthModelName, string discoveryRuleName, DiscoveryRuleData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, healthModelName, discoveryRuleName, data); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + case 201: + { + DiscoveryRuleData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = DiscoveryRuleData.DeserializeDiscoveryRuleData(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string discoveryRuleName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/discoveryrules/", false); + uri.AppendPath(discoveryRuleName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string healthModelName, string discoveryRuleName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/discoveryrules/", false); + uri.AppendPath(discoveryRuleName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Delete a DiscoveryRule. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the discovery rule. Must be unique within a health model. + /// 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 healthModelName, string discoveryRuleName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, healthModelName, discoveryRuleName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + case 204: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + /// Delete a DiscoveryRule. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the discovery rule. Must be unique within a health model. + /// 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 healthModelName, string discoveryRuleName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(discoveryRuleName, nameof(discoveryRuleName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, healthModelName, discoveryRuleName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + case 204: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListByHealthModelRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/discoveryrules", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (timestamp != null) + { + uri.AppendQuery("timestamp", timestamp.Value, "O", true); + } + return uri; + } + + internal HttpMessage CreateListByHealthModelRequest(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/discoveryrules", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (timestamp != null) + { + uri.AppendQuery("timestamp", timestamp.Value, "O", true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// List DiscoveryRule resources by HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task> ListByHealthModelAsync(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelRequest(subscriptionId, resourceGroupName, healthModelName, timestamp); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + DiscoveryRuleListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = DiscoveryRuleListResult.DeserializeDiscoveryRuleListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List DiscoveryRule resources by HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response ListByHealthModel(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelRequest(subscriptionId, resourceGroupName, healthModelName, timestamp); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + DiscoveryRuleListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = DiscoveryRuleListResult.DeserializeDiscoveryRuleListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListByHealthModelNextPageRequestUri(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + return uri; + } + + internal HttpMessage CreateListByHealthModelNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + 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 DiscoveryRule resources by HealthModel. + /// 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. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task> ListByHealthModelNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelNextPageRequest(nextLink, subscriptionId, resourceGroupName, healthModelName, timestamp); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + DiscoveryRuleListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = DiscoveryRuleListResult.DeserializeDiscoveryRuleListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List DiscoveryRule resources by HealthModel. + /// 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. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response ListByHealthModelNextPage(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelNextPageRequest(nextLink, subscriptionId, resourceGroupName, healthModelName, timestamp); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + DiscoveryRuleListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = DiscoveryRuleListResult.DeserializeDiscoveryRuleListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/EntitiesRestOperations.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/EntitiesRestOperations.cs new file mode 100644 index 000000000000..700b318edd5a --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/EntitiesRestOperations.cs @@ -0,0 +1,535 @@ +// 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.CloudHealth.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + internal partial class EntitiesRestOperations + { + private readonly TelemetryDetails _userAgent; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// Initializes a new instance of EntitiesRestOperations. + /// 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 EntitiesRestOperations(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 ?? "2023-10-01-preview"; + _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); + } + + internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string entityName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/entities/", false); + uri.AppendPath(entityName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string healthModelName, string entityName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/entities/", false); + uri.AppendPath(entityName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Get a Entity. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the entity. Must be unique within a health model. + /// 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 healthModelName, string entityName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, healthModelName, entityName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + EntityData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = EntityData.DeserializeEntityData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((EntityData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + /// Get a Entity. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the entity. Must be unique within a health model. + /// 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 healthModelName, string entityName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, healthModelName, entityName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + EntityData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = EntityData.DeserializeEntityData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((EntityData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string entityName, EntityData 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/entities/", false); + uri.AppendPath(entityName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string healthModelName, string entityName, EntityData 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/entities/", false); + uri.AppendPath(entityName, 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 Entity. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the entity. Must be unique within a health model. + /// 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 healthModelName, string entityName, EntityData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, healthModelName, entityName, data); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + case 201: + { + EntityData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = EntityData.DeserializeEntityData(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// Create a Entity. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the entity. Must be unique within a health model. + /// 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 healthModelName, string entityName, EntityData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, healthModelName, entityName, data); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + case 201: + { + EntityData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = EntityData.DeserializeEntityData(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string entityName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/entities/", false); + uri.AppendPath(entityName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string healthModelName, string entityName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/entities/", false); + uri.AppendPath(entityName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Delete a Entity. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the entity. Must be unique within a health model. + /// 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 healthModelName, string entityName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, healthModelName, entityName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + case 204: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + /// Delete a Entity. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the entity. Must be unique within a health model. + /// 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 healthModelName, string entityName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(entityName, nameof(entityName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, healthModelName, entityName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + case 204: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListByHealthModelRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/entities", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (timestamp != null) + { + uri.AppendQuery("timestamp", timestamp.Value, "O", true); + } + return uri; + } + + internal HttpMessage CreateListByHealthModelRequest(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/entities", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (timestamp != null) + { + uri.AppendQuery("timestamp", timestamp.Value, "O", true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// List Entity resources by HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task> ListByHealthModelAsync(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelRequest(subscriptionId, resourceGroupName, healthModelName, timestamp); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + EntityListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = EntityListResult.DeserializeEntityListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List Entity resources by HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response ListByHealthModel(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelRequest(subscriptionId, resourceGroupName, healthModelName, timestamp); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + EntityListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = EntityListResult.DeserializeEntityListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListByHealthModelNextPageRequestUri(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + return uri; + } + + internal HttpMessage CreateListByHealthModelNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + 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 Entity resources by HealthModel. + /// 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. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task> ListByHealthModelNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelNextPageRequest(nextLink, subscriptionId, resourceGroupName, healthModelName, timestamp); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + EntityListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = EntityListResult.DeserializeEntityListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List Entity resources by HealthModel. + /// 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. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response ListByHealthModelNextPage(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelNextPageRequest(nextLink, subscriptionId, resourceGroupName, healthModelName, timestamp); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + EntityListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = EntityListResult.DeserializeEntityListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/HealthModelsRestOperations.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/HealthModelsRestOperations.cs new file mode 100644 index 000000000000..c44d1f30901b --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/HealthModelsRestOperations.cs @@ -0,0 +1,723 @@ +// 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.CloudHealth.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + internal partial class HealthModelsRestOperations + { + private readonly TelemetryDetails _userAgent; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// Initializes a new instance of HealthModelsRestOperations. + /// 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 HealthModelsRestOperations(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 ?? "2023-10-01-preview"; + _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); + } + + internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceGroupName, string healthModelName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string healthModelName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Get a HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// 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 healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, healthModelName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + HealthModelData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = HealthModelData.DeserializeHealthModelData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((HealthModelData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + /// Get a HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// 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 healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, healthModelName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + HealthModelData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = HealthModelData.DeserializeHealthModelData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((HealthModelData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateCreateRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, HealthModelData 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateCreateRequest(string subscriptionId, string resourceGroupName, string healthModelName, HealthModelData 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, 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 HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// 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 CreateAsync(string subscriptionId, string resourceGroupName, string healthModelName, HealthModelData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateRequest(subscriptionId, resourceGroupName, healthModelName, 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 HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// 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 Create(string subscriptionId, string resourceGroupName, string healthModelName, HealthModelData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateRequest(subscriptionId, resourceGroupName, healthModelName, 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 healthModelName, HealthModelPatch 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string healthModelName, HealthModelPatch patch) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, 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(patch, ModelSerializationExtensions.WireOptions); + request.Content = content; + _userAgent.Apply(message); + return message; + } + + /// Update a HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// 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 healthModelName, HealthModelPatch patch, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNull(patch, nameof(patch)); + + using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, healthModelName, patch); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + case 202: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + /// Update a HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// 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 healthModelName, HealthModelPatch patch, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNull(patch, nameof(patch)); + + using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, healthModelName, patch); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + case 202: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string resourceGroupName, string healthModelName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string healthModelName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Delete a HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// 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 healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, healthModelName); + 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 HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// 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 healthModelName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, healthModelName); + _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.CloudHealth/healthmodels", 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.CloudHealth/healthmodels", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// List HealthModel 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: + { + HealthModelListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = HealthModelListResult.DeserializeHealthModelListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List HealthModel 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: + { + HealthModelListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = HealthModelListResult.DeserializeHealthModelListResult(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.CloudHealth/healthmodels", 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.CloudHealth/healthmodels", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// List HealthModel 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: + { + HealthModelListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = HealthModelListResult.DeserializeHealthModelListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List HealthModel 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: + { + HealthModelListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = HealthModelListResult.DeserializeHealthModelListResult(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 HealthModel 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: + { + HealthModelListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = HealthModelListResult.DeserializeHealthModelListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List HealthModel 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: + { + HealthModelListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = HealthModelListResult.DeserializeHealthModelListResult(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 HealthModel 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: + { + HealthModelListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = HealthModelListResult.DeserializeHealthModelListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List HealthModel 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: + { + HealthModelListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = HealthModelListResult.DeserializeHealthModelListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/RelationshipsRestOperations.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/RelationshipsRestOperations.cs new file mode 100644 index 000000000000..b8d505b7035c --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/RelationshipsRestOperations.cs @@ -0,0 +1,535 @@ +// 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.CloudHealth.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + internal partial class RelationshipsRestOperations + { + private readonly TelemetryDetails _userAgent; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// Initializes a new instance of RelationshipsRestOperations. + /// 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 RelationshipsRestOperations(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 ?? "2023-10-01-preview"; + _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); + } + + internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string relationshipName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/relationships/", false); + uri.AppendPath(relationshipName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string healthModelName, string relationshipName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/relationships/", false); + uri.AppendPath(relationshipName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Get a Relationship. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// 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 healthModelName, string relationshipName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, healthModelName, relationshipName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RelationshipData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = RelationshipData.DeserializeRelationshipData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((RelationshipData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + /// Get a Relationship. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// 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 healthModelName, string relationshipName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, healthModelName, relationshipName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RelationshipData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = RelationshipData.DeserializeRelationshipData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((RelationshipData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string relationshipName, RelationshipData 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/relationships/", false); + uri.AppendPath(relationshipName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string healthModelName, string relationshipName, RelationshipData 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/relationships/", false); + uri.AppendPath(relationshipName, 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 Relationship. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// 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 healthModelName, string relationshipName, RelationshipData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, healthModelName, relationshipName, data); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + case 201: + { + RelationshipData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = RelationshipData.DeserializeRelationshipData(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// Create a Relationship. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// 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 healthModelName, string relationshipName, RelationshipData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, healthModelName, relationshipName, data); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + case 201: + { + RelationshipData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = RelationshipData.DeserializeRelationshipData(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string relationshipName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/relationships/", false); + uri.AppendPath(relationshipName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string healthModelName, string relationshipName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/relationships/", false); + uri.AppendPath(relationshipName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Delete a Relationship. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// 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 healthModelName, string relationshipName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, healthModelName, relationshipName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + case 204: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + /// Delete a Relationship. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the relationship. Must be unique within a health model. For example, a concatenation of parentEntityName and childEntityName can be used as the name. + /// 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 healthModelName, string relationshipName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(relationshipName, nameof(relationshipName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, healthModelName, relationshipName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + case 204: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListByHealthModelRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/relationships", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (timestamp != null) + { + uri.AppendQuery("timestamp", timestamp.Value, "O", true); + } + return uri; + } + + internal HttpMessage CreateListByHealthModelRequest(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/relationships", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (timestamp != null) + { + uri.AppendQuery("timestamp", timestamp.Value, "O", true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// List Relationship resources by HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task> ListByHealthModelAsync(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelRequest(subscriptionId, resourceGroupName, healthModelName, timestamp); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RelationshipListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = RelationshipListResult.DeserializeRelationshipListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List Relationship resources by HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response ListByHealthModel(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelRequest(subscriptionId, resourceGroupName, healthModelName, timestamp); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RelationshipListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = RelationshipListResult.DeserializeRelationshipListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListByHealthModelNextPageRequestUri(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + return uri; + } + + internal HttpMessage CreateListByHealthModelNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + 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 Relationship resources by HealthModel. + /// 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. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task> ListByHealthModelNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelNextPageRequest(nextLink, subscriptionId, resourceGroupName, healthModelName, timestamp); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + RelationshipListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = RelationshipListResult.DeserializeRelationshipListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List Relationship resources by HealthModel. + /// 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. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response ListByHealthModelNextPage(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelNextPageRequest(nextLink, subscriptionId, resourceGroupName, healthModelName, timestamp); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + RelationshipListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = RelationshipListResult.DeserializeRelationshipListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/SignalDefinitionsRestOperations.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/SignalDefinitionsRestOperations.cs new file mode 100644 index 000000000000..9d3573801cf9 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/RestOperations/SignalDefinitionsRestOperations.cs @@ -0,0 +1,535 @@ +// 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.CloudHealth.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + internal partial class SignalDefinitionsRestOperations + { + private readonly TelemetryDetails _userAgent; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// Initializes a new instance of SignalDefinitionsRestOperations. + /// 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 SignalDefinitionsRestOperations(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 ?? "2023-10-01-preview"; + _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); + } + + internal RequestUriBuilder CreateGetRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string signalDefinitionName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/signaldefinitions/", false); + uri.AppendPath(signalDefinitionName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string healthModelName, string signalDefinitionName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/signaldefinitions/", false); + uri.AppendPath(signalDefinitionName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Get a SignalDefinition. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the signal definition. Must be unique within a health model. + /// 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 healthModelName, string signalDefinitionName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, healthModelName, signalDefinitionName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + SignalDefinitionData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = SignalDefinitionData.DeserializeSignalDefinitionData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((SignalDefinitionData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + /// Get a SignalDefinition. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the signal definition. Must be unique within a health model. + /// 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 healthModelName, string signalDefinitionName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + + using var message = CreateGetRequest(subscriptionId, resourceGroupName, healthModelName, signalDefinitionName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + SignalDefinitionData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = SignalDefinitionData.DeserializeSignalDefinitionData(document.RootElement); + return Response.FromValue(value, message.Response); + } + case 404: + return Response.FromValue((SignalDefinitionData)null, message.Response); + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateCreateOrUpdateRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string signalDefinitionName, SignalDefinitionData 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/signaldefinitions/", false); + uri.AppendPath(signalDefinitionName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string healthModelName, string signalDefinitionName, SignalDefinitionData 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/signaldefinitions/", false); + uri.AppendPath(signalDefinitionName, 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 SignalDefinition. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the signal definition. Must be unique within a health model. + /// 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 healthModelName, string signalDefinitionName, SignalDefinitionData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, healthModelName, signalDefinitionName, data); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + case 201: + { + SignalDefinitionData value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = SignalDefinitionData.DeserializeSignalDefinitionData(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// Create a SignalDefinition. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the signal definition. Must be unique within a health model. + /// 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 healthModelName, string signalDefinitionName, SignalDefinitionData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + Argument.AssertNotNull(data, nameof(data)); + + using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, healthModelName, signalDefinitionName, data); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + case 201: + { + SignalDefinitionData value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = SignalDefinitionData.DeserializeSignalDefinitionData(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateDeleteRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, string signalDefinitionName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/signaldefinitions/", false); + uri.AppendPath(signalDefinitionName, true); + uri.AppendQuery("api-version", _apiVersion, true); + return uri; + } + + internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string healthModelName, string signalDefinitionName) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/signaldefinitions/", false); + uri.AppendPath(signalDefinitionName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// Delete a SignalDefinition. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the signal definition. Must be unique within a health model. + /// 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 healthModelName, string signalDefinitionName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, healthModelName, signalDefinitionName); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + case 204: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + /// Delete a SignalDefinition. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Name of the signal definition. Must be unique within a health model. + /// 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 healthModelName, string signalDefinitionName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + + using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, healthModelName, signalDefinitionName); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + case 204: + return message.Response; + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListByHealthModelRequestUri(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/signaldefinitions", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (timestamp != null) + { + uri.AppendQuery("timestamp", timestamp.Value, "O", true); + } + return uri; + } + + internal HttpMessage CreateListByHealthModelRequest(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + 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.CloudHealth/healthmodels/", false); + uri.AppendPath(healthModelName, true); + uri.AppendPath("/signaldefinitions", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (timestamp != null) + { + uri.AppendQuery("timestamp", timestamp.Value, "O", true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + _userAgent.Apply(message); + return message; + } + + /// List SignalDefinition resources by HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task> ListByHealthModelAsync(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelRequest(subscriptionId, resourceGroupName, healthModelName, timestamp); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + SignalDefinitionListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = SignalDefinitionListResult.DeserializeSignalDefinitionListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List SignalDefinition resources by HealthModel. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response ListByHealthModel(string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelRequest(subscriptionId, resourceGroupName, healthModelName, timestamp); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + SignalDefinitionListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = SignalDefinitionListResult.DeserializeSignalDefinitionListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + internal RequestUriBuilder CreateListByHealthModelNextPageRequestUri(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + return uri; + } + + internal HttpMessage CreateListByHealthModelNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp) + { + 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 SignalDefinition resources by HealthModel. + /// 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. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public async Task> ListByHealthModelNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelNextPageRequest(nextLink, subscriptionId, resourceGroupName, healthModelName, timestamp); + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); + switch (message.Response.Status) + { + case 200: + { + SignalDefinitionListResult value = default; + using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); + value = SignalDefinitionListResult.DeserializeSignalDefinitionListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + + /// List SignalDefinition resources by HealthModel. + /// 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. + /// Name of health model resource. + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// , , or is null. + /// , or is an empty string, and was expected to be non-empty. + public Response ListByHealthModelNextPage(string nextLink, string subscriptionId, string resourceGroupName, string healthModelName, DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(nextLink, nameof(nextLink)); + Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); + Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); + Argument.AssertNotNullOrEmpty(healthModelName, nameof(healthModelName)); + + using var message = CreateListByHealthModelNextPageRequest(nextLink, subscriptionId, resourceGroupName, healthModelName, timestamp); + _pipeline.Send(message, cancellationToken); + switch (message.Response.Status) + { + case 200: + { + SignalDefinitionListResult value = default; + using var document = JsonDocument.Parse(message.Response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); + value = SignalDefinitionListResult.DeserializeSignalDefinitionListResult(document.RootElement); + return Response.FromValue(value, message.Response); + } + default: + throw new RequestFailedException(message.Response); + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionCollection.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionCollection.cs new file mode 100644 index 000000000000..ec9d0fe4c2f6 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionCollection.cs @@ -0,0 +1,499 @@ +// 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; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A class representing a collection of and their operations. + /// Each in the collection will belong to the same instance of . + /// To get a instance call the GetSignalDefinitions method from an instance of . + /// + public partial class SignalDefinitionCollection : ArmCollection, IEnumerable, IAsyncEnumerable + { + private readonly ClientDiagnostics _signalDefinitionClientDiagnostics; + private readonly SignalDefinitionsRestOperations _signalDefinitionRestClient; + + /// Initializes a new instance of the class for mocking. + protected SignalDefinitionCollection() + { + } + + /// 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 SignalDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _signalDefinitionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CloudHealth", SignalDefinitionResource.ResourceType.Namespace, Diagnostics); + TryGetApiVersion(SignalDefinitionResource.ResourceType, out string signalDefinitionApiVersion); + _signalDefinitionRestClient = new SignalDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, signalDefinitionApiVersion); +#if DEBUG + ValidateResourceId(Id); +#endif + } + + internal static void ValidateResourceId(ResourceIdentifier id) + { + if (id.ResourceType != HealthModelResource.ResourceType) + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, HealthModelResource.ResourceType), nameof(id)); + } + + /// + /// Create a SignalDefinition + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Name of the signal definition. Must be unique within a health model. + /// 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 signalDefinitionName, SignalDefinitionData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = await _signalDefinitionRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, signalDefinitionName, data, cancellationToken).ConfigureAwait(false); + var uri = _signalDefinitionRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, signalDefinitionName, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new SignalDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a SignalDefinition + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Name of the signal definition. Must be unique within a health model. + /// 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 signalDefinitionName, SignalDefinitionData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionCollection.CreateOrUpdate"); + scope.Start(); + try + { + var response = _signalDefinitionRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, signalDefinitionName, data, cancellationToken); + var uri = _signalDefinitionRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, signalDefinitionName, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new SignalDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a SignalDefinition + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the signal definition. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetAsync(string signalDefinitionName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + + using var scope = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionCollection.Get"); + scope.Start(); + try + { + var response = await _signalDefinitionRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, signalDefinitionName, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new SignalDefinitionResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a SignalDefinition + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the signal definition. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Get(string signalDefinitionName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + + using var scope = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionCollection.Get"); + scope.Start(); + try + { + var response = _signalDefinitionRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, signalDefinitionName, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new SignalDefinitionResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// List SignalDefinition resources by HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions + /// + /// + /// Operation Id + /// SignalDefinition_ListByHealthModel + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// An async collection of that may take multiple service requests to iterate over. + public virtual AsyncPageable GetAllAsync(DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => _signalDefinitionRestClient.CreateListByHealthModelRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _signalDefinitionRestClient.CreateListByHealthModelNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => new SignalDefinitionResource(Client, SignalDefinitionData.DeserializeSignalDefinitionData(e)), _signalDefinitionClientDiagnostics, Pipeline, "SignalDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// List SignalDefinition resources by HealthModel + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions + /// + /// + /// Operation Id + /// SignalDefinition_ListByHealthModel + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Timestamp to use for the operation. When specified, the version of the resource at this point in time is retrieved. If not specified, the latest version is used. + /// The cancellation token to use. + /// A collection of that may take multiple service requests to iterate over. + public virtual Pageable GetAll(DateTimeOffset? timestamp = null, CancellationToken cancellationToken = default) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => _signalDefinitionRestClient.CreateListByHealthModelRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => _signalDefinitionRestClient.CreateListByHealthModelNextPageRequest(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, timestamp); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => new SignalDefinitionResource(Client, SignalDefinitionData.DeserializeSignalDefinitionData(e)), _signalDefinitionClientDiagnostics, Pipeline, "SignalDefinitionCollection.GetAll", "value", "nextLink", cancellationToken); + } + + /// + /// Checks to see if the resource exists in azure. + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the signal definition. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> ExistsAsync(string signalDefinitionName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + + using var scope = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionCollection.Exists"); + scope.Start(); + try + { + var response = await _signalDefinitionRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, signalDefinitionName, 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.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the signal definition. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual Response Exists(string signalDefinitionName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + + using var scope = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionCollection.Exists"); + scope.Start(); + try + { + var response = _signalDefinitionRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, signalDefinitionName, 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.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the signal definition. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual async Task> GetIfExistsAsync(string signalDefinitionName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + + using var scope = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionCollection.GetIfExists"); + scope.Start(); + try + { + var response = await _signalDefinitionRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, signalDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new SignalDefinitionResource(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.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// Name of the signal definition. Must be unique within a health model. + /// The cancellation token to use. + /// is an empty string, and was expected to be non-empty. + /// is null. + public virtual NullableResponse GetIfExists(string signalDefinitionName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(signalDefinitionName, nameof(signalDefinitionName)); + + using var scope = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionCollection.GetIfExists"); + scope.Start(); + try + { + var response = _signalDefinitionRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, signalDefinitionName, cancellationToken: cancellationToken); + if (response.Value == null) + return new NoValueResponse(response.GetRawResponse()); + return Response.FromValue(new SignalDefinitionResource(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/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionData.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionData.Serialization.cs new file mode 100644 index 000000000000..551792fde22f --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionData.Serialization.cs @@ -0,0 +1,155 @@ +// 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.CloudHealth.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + public partial class SignalDefinitionData : 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(SignalDefinitionData)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Properties)) + { + writer.WritePropertyName("properties"u8); + writer.WriteObjectValue(Properties, options); + } + } + + SignalDefinitionData 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(SignalDefinitionData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSignalDefinitionData(document.RootElement, options); + } + + internal static SignalDefinitionData DeserializeSignalDefinitionData(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + SignalDefinitionProperties properties = 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 = SignalDefinitionProperties.DeserializeSignalDefinitionProperties(property.Value, options); + 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 SignalDefinitionData( + id, + name, + type, + systemData, + 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(SignalDefinitionData)} does not support writing '{options.Format}' format."); + } + } + + SignalDefinitionData 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 DeserializeSignalDefinitionData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SignalDefinitionData)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionData.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionData.cs new file mode 100644 index 000000000000..762f6cf3cf31 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionData.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.CloudHealth.Models; +using Azure.ResourceManager.Models; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A class representing the SignalDefinition data model. + /// A signal definition in a health model + /// + public partial class SignalDefinitionData : ResourceData + { + /// + /// 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 SignalDefinitionData() + { + } + + /// Initializes a new instance of . + /// The id. + /// The name. + /// The resourceType. + /// The systemData. + /// + /// The resource-specific properties for this resource. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + /// Keeps track of any properties unknown to the library. + internal SignalDefinitionData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, SignalDefinitionProperties properties, IDictionary serializedAdditionalRawData) : base(id, name, resourceType, systemData) + { + Properties = properties; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// The resource-specific properties for this resource. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public SignalDefinitionProperties Properties { get; set; } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionResource.Serialization.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionResource.Serialization.cs new file mode 100644 index 000000000000..c44d724d5090 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionResource.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.CloudHealth +{ + public partial class SignalDefinitionResource : IJsonModel + { + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel)Data).Write(writer, options); + + SignalDefinitionData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel)Data).Create(ref reader, options); + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => ModelReaderWriter.Write(Data, options); + + SignalDefinitionData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => ModelReaderWriter.Read(data, options); + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel)Data).GetFormatFromOptions(options); + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionResource.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionResource.cs new file mode 100644 index 000000000000..6f1ac4f70b73 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Generated/SignalDefinitionResource.cs @@ -0,0 +1,355 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.ResourceManager.CloudHealth +{ + /// + /// A Class representing a SignalDefinition along with the instance operations that can be performed on it. + /// If you have a you can construct a + /// from an instance of using the GetSignalDefinitionResource method. + /// Otherwise you can get one from its parent resource using the GetSignalDefinition method. + /// + public partial class SignalDefinitionResource : ArmResource + { + /// Generate the resource identifier of a instance. + /// The subscriptionId. + /// The resourceGroupName. + /// The healthModelName. + /// The signalDefinitionName. + public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string healthModelName, string signalDefinitionName) + { + var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName}"; + return new ResourceIdentifier(resourceId); + } + + private readonly ClientDiagnostics _signalDefinitionClientDiagnostics; + private readonly SignalDefinitionsRestOperations _signalDefinitionRestClient; + private readonly SignalDefinitionData _data; + + /// Gets the resource type for the operations. + public static readonly ResourceType ResourceType = "Microsoft.CloudHealth/healthmodels/signaldefinitions"; + + /// Initializes a new instance of the class for mocking. + protected SignalDefinitionResource() + { + } + + /// Initializes a new instance of the class. + /// The client parameters to use in these operations. + /// The resource that is the target of operations. + internal SignalDefinitionResource(ArmClient client, SignalDefinitionData 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 SignalDefinitionResource(ArmClient client, ResourceIdentifier id) : base(client, id) + { + _signalDefinitionClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CloudHealth", ResourceType.Namespace, Diagnostics); + TryGetApiVersion(ResourceType, out string signalDefinitionApiVersion); + _signalDefinitionRestClient = new SignalDefinitionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, signalDefinitionApiVersion); +#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 SignalDefinitionData 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 SignalDefinition + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual async Task> GetAsync(CancellationToken cancellationToken = default) + { + using var scope = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionResource.Get"); + scope.Start(); + try + { + var response = await _signalDefinitionRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new SignalDefinitionResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Get a SignalDefinition + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_Get + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// Resource + /// + /// + /// + /// + /// The cancellation token to use. + public virtual Response Get(CancellationToken cancellationToken = default) + { + using var scope = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionResource.Get"); + scope.Start(); + try + { + var response = _signalDefinitionRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); + if (response.Value == null) + throw new RequestFailedException(response.GetRawResponse()); + return Response.FromValue(new SignalDefinitionResource(Client, response.Value), response.GetRawResponse()); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a SignalDefinition + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_Delete + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionResource.Delete"); + scope.Start(); + try + { + var response = await _signalDefinitionRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); + var uri = _signalDefinitionRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(response, rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Delete a SignalDefinition + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_Delete + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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 = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionResource.Delete"); + scope.Start(); + try + { + var response = _signalDefinitionRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); + var uri = _signalDefinitionRestClient.CreateDeleteRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Delete, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(response, rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletionResponse(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a SignalDefinition + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Resource create parameters. + /// The cancellation token to use. + /// is null. + public virtual async Task> UpdateAsync(WaitUntil waitUntil, SignalDefinitionData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionResource.Update"); + scope.Start(); + try + { + var response = await _signalDefinitionRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false); + var uri = _signalDefinitionRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new SignalDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Create a SignalDefinition + /// + /// + /// Request Path + /// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CloudHealth/healthmodels/{healthModelName}/signaldefinitions/{signalDefinitionName} + /// + /// + /// Operation Id + /// SignalDefinition_CreateOrUpdate + /// + /// + /// Default Api Version + /// 2023-10-01-preview + /// + /// + /// 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. + /// Resource create parameters. + /// The cancellation token to use. + /// is null. + public virtual ArmOperation Update(WaitUntil waitUntil, SignalDefinitionData data, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + using var scope = _signalDefinitionClientDiagnostics.CreateScope("SignalDefinitionResource.Update"); + scope.Start(); + try + { + var response = _signalDefinitionRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data, cancellationToken); + var uri = _signalDefinitionRestClient.CreateCreateOrUpdateRequestUri(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, data); + var rehydrationToken = NextLinkOperationImplementation.GetRehydrationToken(RequestMethod.Put, uri.ToUri(), uri.ToString(), "None", null, OperationFinalStateVia.OriginalUri.ToString()); + var operation = new CloudHealthArmOperation(Response.FromValue(new SignalDefinitionResource(Client, response), response.GetRawResponse()), rehydrationToken); + if (waitUntil == WaitUntil.Completed) + operation.WaitForCompletion(cancellationToken); + return operation; + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Properties/AssemblyInfo.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/src/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..653b56e0e519 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/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.CloudHealth.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("CloudHealth")] diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/tests/Azure.ResourceManager.CloudHealth.Tests.csproj b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/tests/Azure.ResourceManager.CloudHealth.Tests.csproj new file mode 100644 index 000000000000..a0e1c642300e --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/tests/Azure.ResourceManager.CloudHealth.Tests.csproj @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/tests/CloudHealthManagementTestBase.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/tests/CloudHealthManagementTestBase.cs new file mode 100644 index 000000000000..58f890d34aac --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/tests/CloudHealthManagementTestBase.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.CloudHealth.Tests +{ + public class CloudHealthManagementTestBase : ManagementRecordedTestBase + { + protected ArmClient Client { get; private set; } + protected SubscriptionResource DefaultSubscription { get; private set; } + + protected CloudHealthManagementTestBase(bool isAsync, RecordedTestMode mode) + : base(isAsync, mode) + { + } + + protected CloudHealthManagementTestBase(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/cloudhealth/Azure.ResourceManager.CloudHealth/tests/CloudHealthManagementTestEnvironment.cs b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/tests/CloudHealthManagementTestEnvironment.cs new file mode 100644 index 000000000000..34f76b1907df --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/tests/CloudHealthManagementTestEnvironment.cs @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core.TestFramework; + +namespace Azure.ResourceManager.CloudHealth.Tests +{ + public class CloudHealthManagementTestEnvironment : TestEnvironment + { + } +} diff --git a/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/tsp-location.yaml b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/tsp-location.yaml new file mode 100644 index 000000000000..1c6afe6988b2 --- /dev/null +++ b/sdk/cloudhealth/Azure.ResourceManager.CloudHealth/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/cloudhealth/CloudHealth.Management +commit: a7cd3fbd39eb9ec8a620e00ec1b1e2624bb97503 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/cloudhealth/ci.mgmt.yml b/sdk/cloudhealth/ci.mgmt.yml new file mode 100644 index 000000000000..9bb0d523f25a --- /dev/null +++ b/sdk/cloudhealth/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/cloudhealth /ci.mgmt.yml + - sdk/cloudhealth /Azure.ResourceManager.CloudHealth / + + +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: cloudhealth + ArtifactName: packages + LimitForPullRequest: true + Artifacts: + - name: Azure.ResourceManager.CloudHealth + safeName: AzureResourceManagerCloudHealth diff --git a/sdk/resourcemanager/ci.mgmt.yml b/sdk/resourcemanager/ci.mgmt.yml index 9ae0a7e75290..31030cac3848 100644 --- a/sdk/resourcemanager/ci.mgmt.yml +++ b/sdk/resourcemanager/ci.mgmt.yml @@ -40,6 +40,7 @@ trigger: - sdk/cdn/Azure.ResourceManager.Cdn - sdk/changeanalysis/Azure.ResourceManager.ChangeAnalysis - sdk/chaos/Azure.ResourceManager.Chaos + - sdk/cloudhealth/Azure.ResourceManager.CloudHealth - sdk/cognitiveservices/Azure.ResourceManager.CognitiveServices - sdk/communication/Azure.ResourceManager.Communication - sdk/compute/Azure.ResourceManager.Compute @@ -256,6 +257,7 @@ pr: - sdk/cdn/Azure.ResourceManager.Cdn - sdk/changeanalysis/Azure.ResourceManager.ChangeAnalysis - sdk/chaos/Azure.ResourceManager.Chaos + - sdk/cloudhealth/Azure.ResourceManager.CloudHealth - sdk/cognitiveservices/Azure.ResourceManager.CognitiveServices - sdk/communication/Azure.ResourceManager.Communication - sdk/compute/Azure.ResourceManager.Compute 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/