From ab9157547f88803a54f7e15311a54c4a8cbdf88c Mon Sep 17 00:00:00 2001 From: dennis-gr Date: Thu, 21 Aug 2025 13:13:53 +0200 Subject: [PATCH 1/8] Add VauHttpClientHandler for transparent encryption and decryption f VAU requests --- lib-vau-csharp-test/Constants.cs | 7 + .../Auth/AuthorizationServiceClient.cs | 3034 ++++++++++++++ .../EpaApiClients/Auth/nswag.json | 57 + .../EntitlementManagementClient.cs | 3557 +++++++++++++++++ .../EntitlementManagement/nswag.json | 57 + lib-vau-csharp-test/EpaDeploymentTest.cs | 36 +- lib-vau-csharp-test/HandShakeTests.cs | 22 +- lib-vau-csharp-test/VauClientTest.cs | 127 + .../lib-vau-csharp-test.csproj | 8 +- lib-vau-csharp/IVauClientProvider.cs | 34 + lib-vau-csharp/VauClient.cs | 178 +- lib-vau-csharp/VauHttpClientHandler.cs | 66 + lib-vau-csharp/VauRequest.cs | 62 + lib-vau-csharp/VauResponse.cs | 87 + lib-vau-csharp/lib-vau-csharp.csproj | 8 +- lib-vau-csharp/util/Extensions.cs | 32 + .../util/HttpResponseHeaderNames.cs | 117 + lib-vau-csharp/util/IsExternalInit.cs | 20 + lib-vau-csharp/util/MediaTypeHeader.cs | 27 + 19 files changed, 7464 insertions(+), 72 deletions(-) create mode 100644 lib-vau-csharp-test/EpaApiClients/Auth/AuthorizationServiceClient.cs create mode 100644 lib-vau-csharp-test/EpaApiClients/Auth/nswag.json create mode 100644 lib-vau-csharp-test/EpaApiClients/EntitlementManagement/EntitlementManagementClient.cs create mode 100644 lib-vau-csharp-test/EpaApiClients/EntitlementManagement/nswag.json create mode 100644 lib-vau-csharp-test/VauClientTest.cs create mode 100644 lib-vau-csharp/IVauClientProvider.cs create mode 100644 lib-vau-csharp/VauHttpClientHandler.cs create mode 100644 lib-vau-csharp/VauRequest.cs create mode 100644 lib-vau-csharp/VauResponse.cs create mode 100644 lib-vau-csharp/util/Extensions.cs create mode 100644 lib-vau-csharp/util/HttpResponseHeaderNames.cs create mode 100644 lib-vau-csharp/util/IsExternalInit.cs create mode 100644 lib-vau-csharp/util/MediaTypeHeader.cs diff --git a/lib-vau-csharp-test/Constants.cs b/lib-vau-csharp-test/Constants.cs index 6ebd4d2..7a71121 100644 --- a/lib-vau-csharp-test/Constants.cs +++ b/lib-vau-csharp-test/Constants.cs @@ -16,6 +16,11 @@ * For additional notes and disclaimer from gematik and in case of changes by gematik find details in the "Readme" file. */ +using System; +using System.IO; + +using lib_vau_csharp_test.util; + using lib_vau_csharp.data; using lib_vau_csharp_test.util; using Org.BouncyCastle.Crypto.Parameters; @@ -26,6 +31,8 @@ namespace lib_vau_csharp_test { public static class Constants { + public static Uri EpaDeploymentUrl = new Uri("http://localhost:443/"); + public static class Keys { public static readonly EccKyberKeyPair EccKyberKeyPair = FileUtil.ReadEccKyberKeyPairFromFile(Paths.VauServerKeys); diff --git a/lib-vau-csharp-test/EpaApiClients/Auth/AuthorizationServiceClient.cs b/lib-vau-csharp-test/EpaApiClients/Auth/AuthorizationServiceClient.cs new file mode 100644 index 0000000..6d16005 --- /dev/null +++ b/lib-vau-csharp-test/EpaApiClients/Auth/AuthorizationServiceClient.cs @@ -0,0 +1,3034 @@ +//---------------------- +// +// Generated using the NSwag toolchain v14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0)) (http://NSwag.org) +// +//---------------------- + +#pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended." +#pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." +#pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?' +#pragma warning disable 612 // Disable "CS0612 '...' is obsolete" +#pragma warning disable 649 // Disable "CS0649 Field is never assigned to, and will always have its default value null" +#pragma warning disable 1573 // Disable "CS1573 Parameter '...' has no matching param tag in the XML comment for ... +#pragma warning disable 1591 // Disable "CS1591 Missing XML comment for publicly visible type or member ..." +#pragma warning disable 8073 // Disable "CS8073 The result of the expression is always 'false' since a value of type 'T' is never equal to 'null' of type 'T?'" +#pragma warning disable 3016 // Disable "CS3016 Arrays as attribute arguments is not CLS-compliant" +#pragma warning disable 8600 // Disable "CS8600 Converting null literal or possible null value to non-nullable type" +#pragma warning disable 8602 // Disable "CS8602 Dereference of a possibly null reference" +#pragma warning disable 8603 // Disable "CS8603 Possible null reference return" +#pragma warning disable 8604 // Disable "CS8604 Possible null reference argument for parameter" +#pragma warning disable 8625 // Disable "CS8625 Cannot convert null literal to non-nullable reference type" +#pragma warning disable 8765 // Disable "CS8765 Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes)." + +namespace lib_vau_csharp_test.EpaApiClients.Auth +{ + using System = global::System; + + [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial interface IAuthorizationServiceClient + { + /// + /// (getFHIRVZDtoken) Get the FHIR VZD search access-token + /// + /// + /// Get the directory service (FHIR VZD) search-token of the health record system. + ///
This operation is limited to authenticated users (IDP) only. + ///
+ ///
**Client**:</br> + ///
A client shall use the provided search access-token for directory service queries instead of an own, individual + ///
registration. + ///
+ ///
**Provider**: + ///
The authorization service shall return the search access-token as received from the FHIR Directory. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// user agent information + /// OK + /// A server side error occurred. + System.Threading.Tasks.Task GetFHIRVZDtokenAsync(string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getFHIRVZDtoken) Get the FHIR VZD search access-token + /// + /// + /// Get the directory service (FHIR VZD) search-token of the health record system. + ///
This operation is limited to authenticated users (IDP) only. + ///
+ ///
**Client**:</br> + ///
A client shall use the provided search access-token for directory service queries instead of an own, individual + ///
registration. + ///
+ ///
**Provider**: + ///
The authorization service shall return the search access-token as received from the FHIR Directory. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// user agent information + /// OK + /// A server side error occurred. + System.Threading.Tasks.Task GetFHIRVZDtokenAsync(string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (getNonce) Generate nonce (random value) for an authorization request + /// + /// + /// A nonce is a generated unique random value. This operation provides the nonce + ///
for the client (attestation).</br> + ///
Remark: This is NOT the nonce used by the authorization + ///
service towards the IDP in an IDP flow! + ///
+ ///
**Client**:</br> + ///
A client shall sign the received nonce. The signed nonce shall be used as client + ///
attestation for the authorization requests finalization (_sendAuthCodeSC_). + ///
+ ///
**Provider**:</br> + ///
The nonce shall be stored for later comparison in a subsequent _sendAuthCodeSc_ operation. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The nonce is kept for subsequent _sendAuthCodeSC_ operation || + ///
+ /// user agent information + /// Ok. + /// A server side error occurred. + System.Threading.Tasks.Task GetNonceAsync(string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getNonce) Generate nonce (random value) for an authorization request + /// + /// + /// A nonce is a generated unique random value. This operation provides the nonce + ///
for the client (attestation).</br> + ///
Remark: This is NOT the nonce used by the authorization + ///
service towards the IDP in an IDP flow! + ///
+ ///
**Client**:</br> + ///
A client shall sign the received nonce. The signed nonce shall be used as client + ///
attestation for the authorization requests finalization (_sendAuthCodeSC_). + ///
+ ///
**Provider**:</br> + ///
The nonce shall be stored for later comparison in a subsequent _sendAuthCodeSc_ operation. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The nonce is kept for subsequent _sendAuthCodeSC_ operation || + ///
+ /// user agent information + /// Ok. + /// A server side error occurred. + System.Threading.Tasks.Task GetNonceAsync(string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (sendAuthorizationRequestSC) Send authorization request + /// + /// + /// Request authorization for a smartcard (SMC-B) based client. + ///
+ ///
**Client**:</br> + ///
A client will receive a well prepared redirection uri and parameters for the authoriation request + ///
towards the authenticator. A client shall invoke the authenticator and IDP flow to revceive an + ///
authorization code for the subsequent _sendAuthCodeSC_ operation. + ///
+ ///
**Provider**:</br> + ///
The authorization server shall prepare a complete redirection uri and authorization request parameters + ///
(PAR-URI) for the central smartcard IDP. + ///
This operation shall be rejected if the corresponding user session is already authorized. Repeated authorization + ///
attempts are not supported. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 302 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Invalid request | 403 | invalAuth | includes any error of Authorization Service which is not mapped to 500 internal Server error | + ///
| Repeated authorization attempt | 409 | statusMismatch | when user session is already authorized only | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// user agent information + /// A server side error occurred. + System.Threading.Tasks.Task SendAuthorizationRequestSCAsync(string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (sendAuthorizationRequestSC) Send authorization request + /// + /// + /// Request authorization for a smartcard (SMC-B) based client. + ///
+ ///
**Client**:</br> + ///
A client will receive a well prepared redirection uri and parameters for the authoriation request + ///
towards the authenticator. A client shall invoke the authenticator and IDP flow to revceive an + ///
authorization code for the subsequent _sendAuthCodeSC_ operation. + ///
+ ///
**Provider**:</br> + ///
The authorization server shall prepare a complete redirection uri and authorization request parameters + ///
(PAR-URI) for the central smartcard IDP. + ///
This operation shall be rejected if the corresponding user session is already authorized. Repeated authorization + ///
attempts are not supported. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 302 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Invalid request | 403 | invalAuth | includes any error of Authorization Service which is not mapped to 500 internal Server error | + ///
| Repeated authorization attempt | 409 | statusMismatch | when user session is already authorized only | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// user agent information + /// A server side error occurred. + System.Threading.Tasks.Task SendAuthorizationRequestSCAsync(string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (sendAuthCodeSC) Send authorization code + /// + /// + /// After successful user authentication the authorization code grant was returned to the authorization + ///
service, that is exchanged for an ID token at the IDP's token endpoint using this operation. + ///
This operation is limited to users of the "Allowed usergroups for Authorization SMC-B" + ///
+ ///
**Client**:</br> + ///
A client shall submit the authorization code received from the authenticator and the client attestation + ///
(signed nonce) + ///
+ ///
**Provider**:</br> + ///
The authorization service shall use the authorization code to prepare a token request for the IDP and receive + ///
the encrypted ID-Token in return. + ///
The received ID-Token shall be validated with HSM rule 'rr0'. The resulting HSM-ID-Token shall be added to the user session. + ///
+ ///
The authorization service shall further validate the ID-token against the stored nonce (from a preceding _getNonce_ operation) + ///
and the client attestation: + ///
- _clientAttest_ is valid if + ///
- signature is valid + ///
- "exp" expiration_time is a timestamp 20 minutes in the future "iat". + ///
- user has role as in "Allowed usergroups for Authorization SMC-B" (from signature cert) + ///
- stored nonce shall not be outdated + ///
- stored nonce shall match client attestation nonce + ///
- Telematik-Id of client attestation (from signature cert) shall match the telematik-id claim of the ID-Token + ///
+ ///
The user session of the client shall be closed and all session related data shall be deleted in case operation is not successful. + ///
+ ///
The nonce shall be discarded, i.e. reuse of a client attestation for user session establishment shall be rejected. + ///
+ ///
The VAU user preudonym as generated for the vau-channel (see: vau protocol) shall be returned in a successful operation response. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Invalid request | 403 | invalAuth | includes any error of Authorization Service which are not mapped to 500 internal Server error | + ///
| No or outdated nonce | 409 | statusMismatch | No preceding _getNonce_ call or stored nonce outdated/invalid | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The nonce is discarded || + ///
| User session has valid HSM-ID-Token for requesting client (telematik-id) | successful operation only | + ///
| User session and temporary data is deleted | failed operation only | + ///
+ /// user agent information + /// OK, Successful login + /// A server side error occurred. + System.Threading.Tasks.Task SendAuthCodeSCAsync(SendAuthCodeSCtype body, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (sendAuthCodeSC) Send authorization code + /// + /// + /// After successful user authentication the authorization code grant was returned to the authorization + ///
service, that is exchanged for an ID token at the IDP's token endpoint using this operation. + ///
This operation is limited to users of the "Allowed usergroups for Authorization SMC-B" + ///
+ ///
**Client**:</br> + ///
A client shall submit the authorization code received from the authenticator and the client attestation + ///
(signed nonce) + ///
+ ///
**Provider**:</br> + ///
The authorization service shall use the authorization code to prepare a token request for the IDP and receive + ///
the encrypted ID-Token in return. + ///
The received ID-Token shall be validated with HSM rule 'rr0'. The resulting HSM-ID-Token shall be added to the user session. + ///
+ ///
The authorization service shall further validate the ID-token against the stored nonce (from a preceding _getNonce_ operation) + ///
and the client attestation: + ///
- _clientAttest_ is valid if + ///
- signature is valid + ///
- "exp" expiration_time is a timestamp 20 minutes in the future "iat". + ///
- user has role as in "Allowed usergroups for Authorization SMC-B" (from signature cert) + ///
- stored nonce shall not be outdated + ///
- stored nonce shall match client attestation nonce + ///
- Telematik-Id of client attestation (from signature cert) shall match the telematik-id claim of the ID-Token + ///
+ ///
The user session of the client shall be closed and all session related data shall be deleted in case operation is not successful. + ///
+ ///
The nonce shall be discarded, i.e. reuse of a client attestation for user session establishment shall be rejected. + ///
+ ///
The VAU user preudonym as generated for the vau-channel (see: vau protocol) shall be returned in a successful operation response. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Invalid request | 403 | invalAuth | includes any error of Authorization Service which are not mapped to 500 internal Server error | + ///
| No or outdated nonce | 409 | statusMismatch | No preceding _getNonce_ call or stored nonce outdated/invalid | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The nonce is discarded || + ///
| User session has valid HSM-ID-Token for requesting client (telematik-id) | successful operation only | + ///
| User session and temporary data is deleted | failed operation only | + ///
+ /// user agent information + /// OK, Successful login + /// A server side error occurred. + System.Threading.Tasks.Task SendAuthCodeSCAsync(SendAuthCodeSCtype body, string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (getFreshnessParameter) Get freshness parameter for a bearer token + /// + /// + /// Get a new freshness parameter for a new bearer token for the authorization by bearer token. + ///
+ ///
**Client**</br> + ///
The ePrescription backend shall use the freshness parameter for a signed JWT (bearer token) according to requirement gemSpec_Aktensystem_ePAfuerAlle, A_25165*. + ///
+ ///
**Provider**</br> + ///
The returned freshness parameter shall follow the requirements in gemSpec_Krypt, A_24658* and be verifiable by HSM rule 'rr0'. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// user agent information + /// OK + /// A server side error occurred. + System.Threading.Tasks.Task GetFreshnessParameterAsync(string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getFreshnessParameter) Get freshness parameter for a bearer token + /// + /// + /// Get a new freshness parameter for a new bearer token for the authorization by bearer token. + ///
+ ///
**Client**</br> + ///
The ePrescription backend shall use the freshness parameter for a signed JWT (bearer token) according to requirement gemSpec_Aktensystem_ePAfuerAlle, A_25165*. + ///
+ ///
**Provider**</br> + ///
The returned freshness parameter shall follow the requirements in gemSpec_Krypt, A_24658* and be verifiable by HSM rule 'rr0'. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// user agent information + /// OK + /// A server side error occurred. + System.Threading.Tasks.Task GetFreshnessParameterAsync(string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (sendAuthorizationRequestBearerToken) Client authorization based on JWT authorization grant. + /// + /// + /// Authorization of the ePrescription backend (E-Rezept-Fachdienst). + ///
+ ///
**Client**</br> + ///
The ePrescription backend shall send a signed JWT (bearerToken) according to requirement gemSpec_Aktensystem_ePAfuerAlle, A_25165*. + ///
The token shall contain a fresh parameter (see: _getFreshnessParameter_). + ///
+ ///
**Provider**</br> + ///
The received token shall be validated with HSM rule 'rr0'. The resulting HSM-ID-Token shall be added to the user session. + ///
The received token shall have a claim "sub", this claim shall state the telematik-id of the ePrescription backend. + ///
+ ///
The user session of the client shall be closed and all session related data shall be deleted in case operation is not successful. + ///
+ ///
The VAU user preudonym as generated for the vau-channel (see: vau protocol) shall be returned in a successful operation response. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest | also for _bearerToken_ does not match token schema | + ///
| Invalid request | 403 | invalAuth | _bearerToken_ is invalid by means of HSM rule 'rr0' or timestamp | + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| authorized user session with HSM-ID-Token for ePrescription backend exists | successful operation only | + ///
| user session and temporary data is deleted | failed operation only | + ///
+ /// user agent information + /// OK, Successful login + /// A server side error occurred. + System.Threading.Tasks.Task SendAuthorizationRequestBearerTokenAsync(BearerTokenType body, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (sendAuthorizationRequestBearerToken) Client authorization based on JWT authorization grant. + /// + /// + /// Authorization of the ePrescription backend (E-Rezept-Fachdienst). + ///
+ ///
**Client**</br> + ///
The ePrescription backend shall send a signed JWT (bearerToken) according to requirement gemSpec_Aktensystem_ePAfuerAlle, A_25165*. + ///
The token shall contain a fresh parameter (see: _getFreshnessParameter_). + ///
+ ///
**Provider**</br> + ///
The received token shall be validated with HSM rule 'rr0'. The resulting HSM-ID-Token shall be added to the user session. + ///
The received token shall have a claim "sub", this claim shall state the telematik-id of the ePrescription backend. + ///
+ ///
The user session of the client shall be closed and all session related data shall be deleted in case operation is not successful. + ///
+ ///
The VAU user preudonym as generated for the vau-channel (see: vau protocol) shall be returned in a successful operation response. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest | also for _bearerToken_ does not match token schema | + ///
| Invalid request | 403 | invalAuth | _bearerToken_ is invalid by means of HSM rule 'rr0' or timestamp | + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| authorized user session with HSM-ID-Token for ePrescription backend exists | successful operation only | + ///
| user session and temporary data is deleted | failed operation only | + ///
+ /// user agent information + /// OK, Successful login + /// A server side error occurred. + System.Threading.Tasks.Task SendAuthorizationRequestBearerTokenAsync(BearerTokenType body, string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (sendAuthorizationRequestFdV) Send authorization request + /// + /// + /// Sends an authorization request to the authorization service. + ///
+ ///
**Client**:</br> + ///
A client shall use parameter _x-authorize_representative_ for the "Authorize Representative" use case, + ///
a login of a user on not owned device for representative entitlement only. + ///
The _x-authorize-representative_ parameter will force an authentication of the user with egK + pin only and limit the possible operations to entitlement management only. + ///
A client shall use the returned redirect url to invoke the authenticator. <br/> + ///
+ ///
A client shall use parameter _x-authorize-egk_ for a login in guest mode with egk and pin, e.g. of a validation identity + ///
(i.e. "Prüfkarte eGK"), forcing the authorization service to request an authentication at the identity provider + ///
in guest mode (eGK + pin). + ///
A client shall use the returned redirect url to invoke the authenticator. + ///
+ ///
**Provider**:</br> + ///
The authorization service shall send a pushed authorization request (PAR) to the IDP (see: find more details). + ///
+ ///
The _redirect_uri_ parameter of the PAR shall be set to a predefined value when operation parameter + ///
_x-redirecturi_ is not present, else the content of _x-redirecturi_ shall be used (according to A_25717-*). + ///
+ ///
The authorize representative situation (_x-authorize-representative_ == _true_) shall be kept for the subsequent + ///
_sendAuthCodeFdV_ and device management operations. + ///
+ ///
For the _x-authorize-representative_ and the _x-authorize-egk_ case the PAR for the IDP shall include: + ///
- amr = urn:telematik:auth:guest:eGK + ///
+ ///
_x-authorize-representative_ and _x-authorize-egk_ both should not be set to _true_ at the same time. + ///
+ ///
This operation shall be rejected if the corresponding user session is already authorized. Repeated authorization + ///
attempts are not supported. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 302 ||| + ///
| Request does not match schema | 400 | malformedRequest | also if both "x-authorize"-parameters are set to _true_ | + ///
| Invalid request | 403 | invalAuth | includes any error of Authorization Service and IDP which is not mapped to 500 internal Server error | + ///
| unregistered redirecturi | 403 | invalRedir | redirecturi in _x-redirecturi_ is not known, registration required | + ///
| Invalid URI (x-idp-iss) | 404 | noResource | | + ///
| Repeated authorization attempt | 409 | statusMismatch | when user session is already authorized only | + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| _authorize_representative_ kept for subsequent _sendAuthCodeFdV_ evaluation | if applicable | + ///
+ /// The issuer Identifier (URL) of the IDP to be used for user authentication + /// This parameter shall be absent or set to _true_ to indicate an authorization request without epa device management registration checks. + /// This parameter shall be absent or set to _true_ to indicate an authorization request in guest mode with egk + pin e.g. for validation identities. + /// An optional redirecturi (URL) to be used in PAR for redirection of the authorizationcode. The redirecturi must be registered as valid on the epa application server (entity statement) + /// user agent information + /// A server side error occurred. + System.Threading.Tasks.Task SendAuthorizationRequestFdVAsync(string x_idp_iss, bool? x_authorize_representative, bool? x_authorize_egk, string x_redirecturi, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (sendAuthorizationRequestFdV) Send authorization request + /// + /// + /// Sends an authorization request to the authorization service. + ///
+ ///
**Client**:</br> + ///
A client shall use parameter _x-authorize_representative_ for the "Authorize Representative" use case, + ///
a login of a user on not owned device for representative entitlement only. + ///
The _x-authorize-representative_ parameter will force an authentication of the user with egK + pin only and limit the possible operations to entitlement management only. + ///
A client shall use the returned redirect url to invoke the authenticator. <br/> + ///
+ ///
A client shall use parameter _x-authorize-egk_ for a login in guest mode with egk and pin, e.g. of a validation identity + ///
(i.e. "Prüfkarte eGK"), forcing the authorization service to request an authentication at the identity provider + ///
in guest mode (eGK + pin). + ///
A client shall use the returned redirect url to invoke the authenticator. + ///
+ ///
**Provider**:</br> + ///
The authorization service shall send a pushed authorization request (PAR) to the IDP (see: find more details). + ///
+ ///
The _redirect_uri_ parameter of the PAR shall be set to a predefined value when operation parameter + ///
_x-redirecturi_ is not present, else the content of _x-redirecturi_ shall be used (according to A_25717-*). + ///
+ ///
The authorize representative situation (_x-authorize-representative_ == _true_) shall be kept for the subsequent + ///
_sendAuthCodeFdV_ and device management operations. + ///
+ ///
For the _x-authorize-representative_ and the _x-authorize-egk_ case the PAR for the IDP shall include: + ///
- amr = urn:telematik:auth:guest:eGK + ///
+ ///
_x-authorize-representative_ and _x-authorize-egk_ both should not be set to _true_ at the same time. + ///
+ ///
This operation shall be rejected if the corresponding user session is already authorized. Repeated authorization + ///
attempts are not supported. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 302 ||| + ///
| Request does not match schema | 400 | malformedRequest | also if both "x-authorize"-parameters are set to _true_ | + ///
| Invalid request | 403 | invalAuth | includes any error of Authorization Service and IDP which is not mapped to 500 internal Server error | + ///
| unregistered redirecturi | 403 | invalRedir | redirecturi in _x-redirecturi_ is not known, registration required | + ///
| Invalid URI (x-idp-iss) | 404 | noResource | | + ///
| Repeated authorization attempt | 409 | statusMismatch | when user session is already authorized only | + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| _authorize_representative_ kept for subsequent _sendAuthCodeFdV_ evaluation | if applicable | + ///
+ /// The issuer Identifier (URL) of the IDP to be used for user authentication + /// This parameter shall be absent or set to _true_ to indicate an authorization request without epa device management registration checks. + /// This parameter shall be absent or set to _true_ to indicate an authorization request in guest mode with egk + pin e.g. for validation identities. + /// An optional redirecturi (URL) to be used in PAR for redirection of the authorizationcode. The redirecturi must be registered as valid on the epa application server (entity statement) + /// user agent information + /// A server side error occurred. + System.Threading.Tasks.Task SendAuthorizationRequestFdVAsync(string x_idp_iss, bool? x_authorize_representative, bool? x_authorize_egk, string x_redirecturi, string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (sendAuthCodeFdV) Send authorization code + /// + /// + /// Send the authorization code to the authorization service to complete the login and (optional) + ///
verify the device registration. + ///
+ ///
**Client**:</br> + ///
A client shall always send the authorization code received from the authenticator / IDP. <br/> + ///
+ ///
A client shall send both, _x-device-identifier_ and _x-device-token_, on login to the home system + ///
of the user for proof of a registered device. + ///
+ ///
If the user has a device registration in another home system, then a device attestation from his home + ///
system must be used and a client shall submit _x-device-attestation_ (instead of _x-device-identifier_ + ///
and _x-device-token_). A client can obtain a device attestation from the home system via a + ///
_getDeviceAttestation_ operation call. + ///
+ ///
A client shall not send _x-device-identifier_ and _x-device-token_ or even _x-device-attestation_ + ///
(suppress parameters at all) if the device is not yet registered and confirmed or if the preceding + ///
_sendAuthorizationRequestFdV_ call includes the parameter _x-authorize_representative_ == _true_. + ///
+ ///
(For registration of a new device, including confirmation of the registration, see Device Management + ///
Service operations _registerDevice_ and _confirmDevice_). + ///
+ ///
+ ///
**Provider**:</br> + ///
The provided authorization code shall be exchanged for an ID-Token with the IDP. The ID-Token shall be converted + ///
into a HSM-ID-Token with an extended validity period. + ///
+ ///
Device verification - home system:</br> + ///
If _x-device-identifier_ and _x-device-token_ are both submitted the device verification starts immediately after + ///
the authorization completion. + ///
Device identifier and -token shall be verified with the registered values. + ///
The x-device-identifier / x-device-token check shall only consider device registrations for the authorized user. + ///
+ ///
Device verification - other than home system:</br> + ///
If _x-device-attestation_ is submitted the device verification starts immediately after the authorization completion. + ///
The authorization service shall accept a device attestation in case + ///
- signature is valid + ///
- "exp" expiration_time is a timestamp 120 minutes in the future "iat". + ///
- current time is greater or equal than 'iat' and less than 'exp' with 15 seconds tolerance ('iat' - 15s <= current time < 'exp' + 15s). + ///
- claim _actorId_ from device attestation matches kvnr of ID-Token or HSM-ID-Token. + ///
+ ///
If the device attestation is valid by signature and time, and the KVNR submitted in device attestation matches the + ///
KVNR of the authorized user the authorization service shall accept the device registration. + ///
+ ///
On success (ID-Token / HSM-ID-Token received and device binding check successful) a new user session shall be instantiated, + ///
associated to the HSM-ID-Token. + ///
+ ///
If device verification succeeds, access to all services of a health record shall be possible for the associated + ///
user session. + ///
if x-authorize-representative is set, access to the user's health record entitlement management only shall be + ///
possible for the user session. + ///
In all other (success cases) access of the user session shall be limited to the device management service. + ///
+ ///
The user session of a client shall be closed and all session related data shall be deleted in case operation is not successful. + ///
+ ///
The VAU user preudonym as generated for the vau-channel (see: vau protocol) shall be returned in a successful operation response. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Only _x-device-identifier_ or _x-device-token_ provided | 400 | paramExcpected | both parameters required or none | + ///
| (_x-device-identifier_ and/or _x-device-token_) and _x-device-attestation_ provided | 400 | paramExcpected | use only registration of home system, another system or none (yet unregistered device) | + ///
| _authorize_representative_ is set and _x-device-identifier_ and/or _x-device-token_ and/or x-device-attestation_ provided | 400 | authorizeRep | _x-authorize_representative_ from preceding sendAuthorizationRequestFdV | + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| _authorizationCode_ not valid | 403 | invalAuth | includes any error of Authorization Service and IDP which is not mapped to 500 internal Server error | + ///
| Wrong _x-device-token_ | 403 | invalidToken | if both parameters avaiable and allowed| + ///
| Invalid _x-device-attestation_ | 403 | invalSignature || + ///
| Device registration does not exist (_x-device-identifier_)| 404| noResource | also if device is not associated to requestor kvnr | + ///
| Device registration not confirmed (_status_ == _pending_) | 409 | statusMismatch | confirm pending device registration before retry | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| user session has valid HSM-ID-Token | successful operation only | + ///
| user session contains device verification result | successful operation with device parameters only | + ///
| _lastUse_ of device registration is updated to current time | successful operation with device parameters only | + ///
| user session and temporary data is deleted | failed operation only | + ///
+ /// The deviceidentifier of a device registration + /// The devicetoken of a device registration + /// The deviceAttestation of a device registration + /// user agent information + /// OK, Successful login + /// A server side error occurred. + System.Threading.Tasks.Task SendAuthCodeFdVAsync(System.Guid? x_device_identifier, string x_device_token, DeviceAttestationType x_device_attestation, SendAuthCodeFdVtype body, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (sendAuthCodeFdV) Send authorization code + /// + /// + /// Send the authorization code to the authorization service to complete the login and (optional) + ///
verify the device registration. + ///
+ ///
**Client**:</br> + ///
A client shall always send the authorization code received from the authenticator / IDP. <br/> + ///
+ ///
A client shall send both, _x-device-identifier_ and _x-device-token_, on login to the home system + ///
of the user for proof of a registered device. + ///
+ ///
If the user has a device registration in another home system, then a device attestation from his home + ///
system must be used and a client shall submit _x-device-attestation_ (instead of _x-device-identifier_ + ///
and _x-device-token_). A client can obtain a device attestation from the home system via a + ///
_getDeviceAttestation_ operation call. + ///
+ ///
A client shall not send _x-device-identifier_ and _x-device-token_ or even _x-device-attestation_ + ///
(suppress parameters at all) if the device is not yet registered and confirmed or if the preceding + ///
_sendAuthorizationRequestFdV_ call includes the parameter _x-authorize_representative_ == _true_. + ///
+ ///
(For registration of a new device, including confirmation of the registration, see Device Management + ///
Service operations _registerDevice_ and _confirmDevice_). + ///
+ ///
+ ///
**Provider**:</br> + ///
The provided authorization code shall be exchanged for an ID-Token with the IDP. The ID-Token shall be converted + ///
into a HSM-ID-Token with an extended validity period. + ///
+ ///
Device verification - home system:</br> + ///
If _x-device-identifier_ and _x-device-token_ are both submitted the device verification starts immediately after + ///
the authorization completion. + ///
Device identifier and -token shall be verified with the registered values. + ///
The x-device-identifier / x-device-token check shall only consider device registrations for the authorized user. + ///
+ ///
Device verification - other than home system:</br> + ///
If _x-device-attestation_ is submitted the device verification starts immediately after the authorization completion. + ///
The authorization service shall accept a device attestation in case + ///
- signature is valid + ///
- "exp" expiration_time is a timestamp 120 minutes in the future "iat". + ///
- current time is greater or equal than 'iat' and less than 'exp' with 15 seconds tolerance ('iat' - 15s <= current time < 'exp' + 15s). + ///
- claim _actorId_ from device attestation matches kvnr of ID-Token or HSM-ID-Token. + ///
+ ///
If the device attestation is valid by signature and time, and the KVNR submitted in device attestation matches the + ///
KVNR of the authorized user the authorization service shall accept the device registration. + ///
+ ///
On success (ID-Token / HSM-ID-Token received and device binding check successful) a new user session shall be instantiated, + ///
associated to the HSM-ID-Token. + ///
+ ///
If device verification succeeds, access to all services of a health record shall be possible for the associated + ///
user session. + ///
if x-authorize-representative is set, access to the user's health record entitlement management only shall be + ///
possible for the user session. + ///
In all other (success cases) access of the user session shall be limited to the device management service. + ///
+ ///
The user session of a client shall be closed and all session related data shall be deleted in case operation is not successful. + ///
+ ///
The VAU user preudonym as generated for the vau-channel (see: vau protocol) shall be returned in a successful operation response. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Only _x-device-identifier_ or _x-device-token_ provided | 400 | paramExcpected | both parameters required or none | + ///
| (_x-device-identifier_ and/or _x-device-token_) and _x-device-attestation_ provided | 400 | paramExcpected | use only registration of home system, another system or none (yet unregistered device) | + ///
| _authorize_representative_ is set and _x-device-identifier_ and/or _x-device-token_ and/or x-device-attestation_ provided | 400 | authorizeRep | _x-authorize_representative_ from preceding sendAuthorizationRequestFdV | + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| _authorizationCode_ not valid | 403 | invalAuth | includes any error of Authorization Service and IDP which is not mapped to 500 internal Server error | + ///
| Wrong _x-device-token_ | 403 | invalidToken | if both parameters avaiable and allowed| + ///
| Invalid _x-device-attestation_ | 403 | invalSignature || + ///
| Device registration does not exist (_x-device-identifier_)| 404| noResource | also if device is not associated to requestor kvnr | + ///
| Device registration not confirmed (_status_ == _pending_) | 409 | statusMismatch | confirm pending device registration before retry | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| user session has valid HSM-ID-Token | successful operation only | + ///
| user session contains device verification result | successful operation with device parameters only | + ///
| _lastUse_ of device registration is updated to current time | successful operation with device parameters only | + ///
| user session and temporary data is deleted | failed operation only | + ///
+ /// The deviceidentifier of a device registration + /// The devicetoken of a device registration + /// The deviceAttestation of a device registration + /// user agent information + /// OK, Successful login + /// A server side error occurred. + System.Threading.Tasks.Task SendAuthCodeFdVAsync(System.Guid? x_device_identifier, string x_device_token, DeviceAttestationType x_device_attestation, SendAuthCodeFdVtype body, string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (logoutFdV) Logout from user session. + /// + /// + /// A logout terminates the associated user session. For any further service usage a new + ///
authentication of the user is required. + ///
+ ///
**Client**:</br> + ///
A client shall perform this explicit logout to close the user session and all + ///
health record related activities. For further access a client shall perform a new login, including + ///
negotiation of a new VAU-channel. + ///
+ ///
**Provider**:</br> + ///
The user session of a client shall be closed and all session related + ///
data shall be deleted. Associated health record contexts shall be released / closed. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful logout | 204 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The user session and all related temporary data is terminated / deleted | successful operation only | + ///
+ /// user agent information + /// OK + /// A server side error occurred. + System.Threading.Tasks.Task LogoutFdVAsync(string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (logoutFdV) Logout from user session. + /// + /// + /// A logout terminates the associated user session. For any further service usage a new + ///
authentication of the user is required. + ///
+ ///
**Client**:</br> + ///
A client shall perform this explicit logout to close the user session and all + ///
health record related activities. For further access a client shall perform a new login, including + ///
negotiation of a new VAU-channel. + ///
+ ///
**Provider**:</br> + ///
The user session of a client shall be closed and all session related + ///
data shall be deleted. Associated health record contexts shall be released / closed. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful logout | 204 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The user session and all related temporary data is terminated / deleted | successful operation only | + ///
+ /// user agent information + /// OK + /// A server side error occurred. + System.Threading.Tasks.Task LogoutFdVAsync(string x_useragent, System.Threading.CancellationToken cancellationToken); + + } + + [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class AuthorizationServiceClient : IAuthorizationServiceClient + { + private System.Net.Http.HttpClient _httpClient; + private static System.Lazy _settings = new System.Lazy(CreateSerializerSettings, true); + private System.Text.Json.JsonSerializerOptions _instanceSettings; + + #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + public AuthorizationServiceClient(System.Net.Http.HttpClient httpClient) + #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + { + _httpClient = httpClient; + Initialize(); + } + + private static System.Text.Json.JsonSerializerOptions CreateSerializerSettings() + { + var settings = new System.Text.Json.JsonSerializerOptions(); + UpdateJsonSerializerSettings(settings); + return settings; + } + + protected System.Text.Json.JsonSerializerOptions JsonSerializerSettings { get { return _instanceSettings ?? _settings.Value; } } + + static partial void UpdateJsonSerializerSettings(System.Text.Json.JsonSerializerOptions settings); + + partial void Initialize(); + + partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url); + partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); + partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); + + /// + /// (getFHIRVZDtoken) Get the FHIR VZD search access-token + /// + /// + /// Get the directory service (FHIR VZD) search-token of the health record system. + ///
This operation is limited to authenticated users (IDP) only. + ///
+ ///
**Client**:</br> + ///
A client shall use the provided search access-token for directory service queries instead of an own, individual + ///
registration. + ///
+ ///
**Provider**: + ///
The authorization service shall return the search access-token as received from the FHIR Directory. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// user agent information + /// OK + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetFHIRVZDtokenAsync(string x_useragent) + { + return GetFHIRVZDtokenAsync(x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getFHIRVZDtoken) Get the FHIR VZD search access-token + /// + /// + /// Get the directory service (FHIR VZD) search-token of the health record system. + ///
This operation is limited to authenticated users (IDP) only. + ///
+ ///
**Client**:</br> + ///
A client shall use the provided search access-token for directory service queries instead of an own, individual + ///
registration. + ///
+ ///
**Provider**: + ///
The authorization service shall return the search access-token as received from the FHIR Directory. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// user agent information + /// OK + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetFHIRVZDtokenAsync(string x_useragent, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/vzd/v1/vzdToken" + urlBuilder_.Append("epa/vzd/v1/vzdToken"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new AuthorizationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (getNonce) Generate nonce (random value) for an authorization request + /// + /// + /// A nonce is a generated unique random value. This operation provides the nonce + ///
for the client (attestation).</br> + ///
Remark: This is NOT the nonce used by the authorization + ///
service towards the IDP in an IDP flow! + ///
+ ///
**Client**:</br> + ///
A client shall sign the received nonce. The signed nonce shall be used as client + ///
attestation for the authorization requests finalization (_sendAuthCodeSC_). + ///
+ ///
**Provider**:</br> + ///
The nonce shall be stored for later comparison in a subsequent _sendAuthCodeSc_ operation. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The nonce is kept for subsequent _sendAuthCodeSC_ operation || + ///
+ /// user agent information + /// Ok. + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetNonceAsync(string x_useragent) + { + return GetNonceAsync(x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getNonce) Generate nonce (random value) for an authorization request + /// + /// + /// A nonce is a generated unique random value. This operation provides the nonce + ///
for the client (attestation).</br> + ///
Remark: This is NOT the nonce used by the authorization + ///
service towards the IDP in an IDP flow! + ///
+ ///
**Client**:</br> + ///
A client shall sign the received nonce. The signed nonce shall be used as client + ///
attestation for the authorization requests finalization (_sendAuthCodeSC_). + ///
+ ///
**Provider**:</br> + ///
The nonce shall be stored for later comparison in a subsequent _sendAuthCodeSc_ operation. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The nonce is kept for subsequent _sendAuthCodeSC_ operation || + ///
+ /// user agent information + /// Ok. + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetNonceAsync(string x_useragent, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/authz/v1/getNonce" + urlBuilder_.Append("epa/authz/v1/getNonce"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new AuthorizationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (sendAuthorizationRequestSC) Send authorization request + /// + /// + /// Request authorization for a smartcard (SMC-B) based client. + ///
+ ///
**Client**:</br> + ///
A client will receive a well prepared redirection uri and parameters for the authoriation request + ///
towards the authenticator. A client shall invoke the authenticator and IDP flow to revceive an + ///
authorization code for the subsequent _sendAuthCodeSC_ operation. + ///
+ ///
**Provider**:</br> + ///
The authorization server shall prepare a complete redirection uri and authorization request parameters + ///
(PAR-URI) for the central smartcard IDP. + ///
This operation shall be rejected if the corresponding user session is already authorized. Repeated authorization + ///
attempts are not supported. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 302 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Invalid request | 403 | invalAuth | includes any error of Authorization Service which is not mapped to 500 internal Server error | + ///
| Repeated authorization attempt | 409 | statusMismatch | when user session is already authorized only | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// user agent information + /// A server side error occurred. + public virtual System.Threading.Tasks.Task SendAuthorizationRequestSCAsync(string x_useragent) + { + return SendAuthorizationRequestSCAsync(x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (sendAuthorizationRequestSC) Send authorization request + /// + /// + /// Request authorization for a smartcard (SMC-B) based client. + ///
+ ///
**Client**:</br> + ///
A client will receive a well prepared redirection uri and parameters for the authoriation request + ///
towards the authenticator. A client shall invoke the authenticator and IDP flow to revceive an + ///
authorization code for the subsequent _sendAuthCodeSC_ operation. + ///
+ ///
**Provider**:</br> + ///
The authorization server shall prepare a complete redirection uri and authorization request parameters + ///
(PAR-URI) for the central smartcard IDP. + ///
This operation shall be rejected if the corresponding user session is already authorized. Repeated authorization + ///
attempts are not supported. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 302 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Invalid request | 403 | invalAuth | includes any error of Authorization Service which is not mapped to 500 internal Server error | + ///
| Repeated authorization attempt | 409 | statusMismatch | when user session is already authorized only | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// user agent information + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task SendAuthorizationRequestSCAsync(string x_useragent, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/authz/v1/send_authorization_request_sc" + urlBuilder_.Append("epa/authz/v1/send_authorization_request_sc"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 302) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new AuthorizationServiceException("Found", status_, responseText_, headers_, null); + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + + if (status_ == 200 || status_ == 204) + { + + return; + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new AuthorizationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (sendAuthCodeSC) Send authorization code + /// + /// + /// After successful user authentication the authorization code grant was returned to the authorization + ///
service, that is exchanged for an ID token at the IDP's token endpoint using this operation. + ///
This operation is limited to users of the "Allowed usergroups for Authorization SMC-B" + ///
+ ///
**Client**:</br> + ///
A client shall submit the authorization code received from the authenticator and the client attestation + ///
(signed nonce) + ///
+ ///
**Provider**:</br> + ///
The authorization service shall use the authorization code to prepare a token request for the IDP and receive + ///
the encrypted ID-Token in return. + ///
The received ID-Token shall be validated with HSM rule 'rr0'. The resulting HSM-ID-Token shall be added to the user session. + ///
+ ///
The authorization service shall further validate the ID-token against the stored nonce (from a preceding _getNonce_ operation) + ///
and the client attestation: + ///
- _clientAttest_ is valid if + ///
- signature is valid + ///
- "exp" expiration_time is a timestamp 20 minutes in the future "iat". + ///
- user has role as in "Allowed usergroups for Authorization SMC-B" (from signature cert) + ///
- stored nonce shall not be outdated + ///
- stored nonce shall match client attestation nonce + ///
- Telematik-Id of client attestation (from signature cert) shall match the telematik-id claim of the ID-Token + ///
+ ///
The user session of the client shall be closed and all session related data shall be deleted in case operation is not successful. + ///
+ ///
The nonce shall be discarded, i.e. reuse of a client attestation for user session establishment shall be rejected. + ///
+ ///
The VAU user preudonym as generated for the vau-channel (see: vau protocol) shall be returned in a successful operation response. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Invalid request | 403 | invalAuth | includes any error of Authorization Service which are not mapped to 500 internal Server error | + ///
| No or outdated nonce | 409 | statusMismatch | No preceding _getNonce_ call or stored nonce outdated/invalid | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The nonce is discarded || + ///
| User session has valid HSM-ID-Token for requesting client (telematik-id) | successful operation only | + ///
| User session and temporary data is deleted | failed operation only | + ///
+ /// user agent information + /// OK, Successful login + /// A server side error occurred. + public virtual System.Threading.Tasks.Task SendAuthCodeSCAsync(SendAuthCodeSCtype body, string x_useragent) + { + return SendAuthCodeSCAsync(body, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (sendAuthCodeSC) Send authorization code + /// + /// + /// After successful user authentication the authorization code grant was returned to the authorization + ///
service, that is exchanged for an ID token at the IDP's token endpoint using this operation. + ///
This operation is limited to users of the "Allowed usergroups for Authorization SMC-B" + ///
+ ///
**Client**:</br> + ///
A client shall submit the authorization code received from the authenticator and the client attestation + ///
(signed nonce) + ///
+ ///
**Provider**:</br> + ///
The authorization service shall use the authorization code to prepare a token request for the IDP and receive + ///
the encrypted ID-Token in return. + ///
The received ID-Token shall be validated with HSM rule 'rr0'. The resulting HSM-ID-Token shall be added to the user session. + ///
+ ///
The authorization service shall further validate the ID-token against the stored nonce (from a preceding _getNonce_ operation) + ///
and the client attestation: + ///
- _clientAttest_ is valid if + ///
- signature is valid + ///
- "exp" expiration_time is a timestamp 20 minutes in the future "iat". + ///
- user has role as in "Allowed usergroups for Authorization SMC-B" (from signature cert) + ///
- stored nonce shall not be outdated + ///
- stored nonce shall match client attestation nonce + ///
- Telematik-Id of client attestation (from signature cert) shall match the telematik-id claim of the ID-Token + ///
+ ///
The user session of the client shall be closed and all session related data shall be deleted in case operation is not successful. + ///
+ ///
The nonce shall be discarded, i.e. reuse of a client attestation for user session establishment shall be rejected. + ///
+ ///
The VAU user preudonym as generated for the vau-channel (see: vau protocol) shall be returned in a successful operation response. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Invalid request | 403 | invalAuth | includes any error of Authorization Service which are not mapped to 500 internal Server error | + ///
| No or outdated nonce | 409 | statusMismatch | No preceding _getNonce_ call or stored nonce outdated/invalid | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The nonce is discarded || + ///
| User session has valid HSM-ID-Token for requesting client (telematik-id) | successful operation only | + ///
| User session and temporary data is deleted | failed operation only | + ///
+ /// user agent information + /// OK, Successful login + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task SendAuthCodeSCAsync(SendAuthCodeSCtype body, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + if (body == null) + throw new System.ArgumentNullException("body"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + var json_ = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(body, JsonSerializerSettings); + var content_ = new System.Net.Http.ByteArrayContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/authz/v1/send_authcode_sc" + urlBuilder_.Append("epa/authz/v1/send_authcode_sc"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new AuthorizationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (getFreshnessParameter) Get freshness parameter for a bearer token + /// + /// + /// Get a new freshness parameter for a new bearer token for the authorization by bearer token. + ///
+ ///
**Client**</br> + ///
The ePrescription backend shall use the freshness parameter for a signed JWT (bearer token) according to requirement gemSpec_Aktensystem_ePAfuerAlle, A_25165*. + ///
+ ///
**Provider**</br> + ///
The returned freshness parameter shall follow the requirements in gemSpec_Krypt, A_24658* and be verifiable by HSM rule 'rr0'. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// user agent information + /// OK + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetFreshnessParameterAsync(string x_useragent) + { + return GetFreshnessParameterAsync(x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getFreshnessParameter) Get freshness parameter for a bearer token + /// + /// + /// Get a new freshness parameter for a new bearer token for the authorization by bearer token. + ///
+ ///
**Client**</br> + ///
The ePrescription backend shall use the freshness parameter for a signed JWT (bearer token) according to requirement gemSpec_Aktensystem_ePAfuerAlle, A_25165*. + ///
+ ///
**Provider**</br> + ///
The returned freshness parameter shall follow the requirements in gemSpec_Krypt, A_24658* and be verifiable by HSM rule 'rr0'. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// user agent information + /// OK + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetFreshnessParameterAsync(string x_useragent, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/authz/v1/freshness" + urlBuilder_.Append("epa/authz/v1/freshness"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new AuthorizationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (sendAuthorizationRequestBearerToken) Client authorization based on JWT authorization grant. + /// + /// + /// Authorization of the ePrescription backend (E-Rezept-Fachdienst). + ///
+ ///
**Client**</br> + ///
The ePrescription backend shall send a signed JWT (bearerToken) according to requirement gemSpec_Aktensystem_ePAfuerAlle, A_25165*. + ///
The token shall contain a fresh parameter (see: _getFreshnessParameter_). + ///
+ ///
**Provider**</br> + ///
The received token shall be validated with HSM rule 'rr0'. The resulting HSM-ID-Token shall be added to the user session. + ///
The received token shall have a claim "sub", this claim shall state the telematik-id of the ePrescription backend. + ///
+ ///
The user session of the client shall be closed and all session related data shall be deleted in case operation is not successful. + ///
+ ///
The VAU user preudonym as generated for the vau-channel (see: vau protocol) shall be returned in a successful operation response. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest | also for _bearerToken_ does not match token schema | + ///
| Invalid request | 403 | invalAuth | _bearerToken_ is invalid by means of HSM rule 'rr0' or timestamp | + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| authorized user session with HSM-ID-Token for ePrescription backend exists | successful operation only | + ///
| user session and temporary data is deleted | failed operation only | + ///
+ /// user agent information + /// OK, Successful login + /// A server side error occurred. + public virtual System.Threading.Tasks.Task SendAuthorizationRequestBearerTokenAsync(BearerTokenType body, string x_useragent) + { + return SendAuthorizationRequestBearerTokenAsync(body, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (sendAuthorizationRequestBearerToken) Client authorization based on JWT authorization grant. + /// + /// + /// Authorization of the ePrescription backend (E-Rezept-Fachdienst). + ///
+ ///
**Client**</br> + ///
The ePrescription backend shall send a signed JWT (bearerToken) according to requirement gemSpec_Aktensystem_ePAfuerAlle, A_25165*. + ///
The token shall contain a fresh parameter (see: _getFreshnessParameter_). + ///
+ ///
**Provider**</br> + ///
The received token shall be validated with HSM rule 'rr0'. The resulting HSM-ID-Token shall be added to the user session. + ///
The received token shall have a claim "sub", this claim shall state the telematik-id of the ePrescription backend. + ///
+ ///
The user session of the client shall be closed and all session related data shall be deleted in case operation is not successful. + ///
+ ///
The VAU user preudonym as generated for the vau-channel (see: vau protocol) shall be returned in a successful operation response. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest | also for _bearerToken_ does not match token schema | + ///
| Invalid request | 403 | invalAuth | _bearerToken_ is invalid by means of HSM rule 'rr0' or timestamp | + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| authorized user session with HSM-ID-Token for ePrescription backend exists | successful operation only | + ///
| user session and temporary data is deleted | failed operation only | + ///
+ /// user agent information + /// OK, Successful login + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task SendAuthorizationRequestBearerTokenAsync(BearerTokenType body, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + if (body == null) + throw new System.ArgumentNullException("body"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + var json_ = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(body, JsonSerializerSettings); + var content_ = new System.Net.Http.ByteArrayContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/authz/v1/send_authorization_request_bearertoken" + urlBuilder_.Append("epa/authz/v1/send_authorization_request_bearertoken"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new AuthorizationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (sendAuthorizationRequestFdV) Send authorization request + /// + /// + /// Sends an authorization request to the authorization service. + ///
+ ///
**Client**:</br> + ///
A client shall use parameter _x-authorize_representative_ for the "Authorize Representative" use case, + ///
a login of a user on not owned device for representative entitlement only. + ///
The _x-authorize-representative_ parameter will force an authentication of the user with egK + pin only and limit the possible operations to entitlement management only. + ///
A client shall use the returned redirect url to invoke the authenticator. <br/> + ///
+ ///
A client shall use parameter _x-authorize-egk_ for a login in guest mode with egk and pin, e.g. of a validation identity + ///
(i.e. "Prüfkarte eGK"), forcing the authorization service to request an authentication at the identity provider + ///
in guest mode (eGK + pin). + ///
A client shall use the returned redirect url to invoke the authenticator. + ///
+ ///
**Provider**:</br> + ///
The authorization service shall send a pushed authorization request (PAR) to the IDP (see: find more details). + ///
+ ///
The _redirect_uri_ parameter of the PAR shall be set to a predefined value when operation parameter + ///
_x-redirecturi_ is not present, else the content of _x-redirecturi_ shall be used (according to A_25717-*). + ///
+ ///
The authorize representative situation (_x-authorize-representative_ == _true_) shall be kept for the subsequent + ///
_sendAuthCodeFdV_ and device management operations. + ///
+ ///
For the _x-authorize-representative_ and the _x-authorize-egk_ case the PAR for the IDP shall include: + ///
- amr = urn:telematik:auth:guest:eGK + ///
+ ///
_x-authorize-representative_ and _x-authorize-egk_ both should not be set to _true_ at the same time. + ///
+ ///
This operation shall be rejected if the corresponding user session is already authorized. Repeated authorization + ///
attempts are not supported. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 302 ||| + ///
| Request does not match schema | 400 | malformedRequest | also if both "x-authorize"-parameters are set to _true_ | + ///
| Invalid request | 403 | invalAuth | includes any error of Authorization Service and IDP which is not mapped to 500 internal Server error | + ///
| unregistered redirecturi | 403 | invalRedir | redirecturi in _x-redirecturi_ is not known, registration required | + ///
| Invalid URI (x-idp-iss) | 404 | noResource | | + ///
| Repeated authorization attempt | 409 | statusMismatch | when user session is already authorized only | + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| _authorize_representative_ kept for subsequent _sendAuthCodeFdV_ evaluation | if applicable | + ///
+ /// The issuer Identifier (URL) of the IDP to be used for user authentication + /// This parameter shall be absent or set to _true_ to indicate an authorization request without epa device management registration checks. + /// This parameter shall be absent or set to _true_ to indicate an authorization request in guest mode with egk + pin e.g. for validation identities. + /// An optional redirecturi (URL) to be used in PAR for redirection of the authorizationcode. The redirecturi must be registered as valid on the epa application server (entity statement) + /// user agent information + /// A server side error occurred. + public virtual System.Threading.Tasks.Task SendAuthorizationRequestFdVAsync(string x_idp_iss, bool? x_authorize_representative, bool? x_authorize_egk, string x_redirecturi, string x_useragent) + { + return SendAuthorizationRequestFdVAsync(x_idp_iss, x_authorize_representative, x_authorize_egk, x_redirecturi, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (sendAuthorizationRequestFdV) Send authorization request + /// + /// + /// Sends an authorization request to the authorization service. + ///
+ ///
**Client**:</br> + ///
A client shall use parameter _x-authorize_representative_ for the "Authorize Representative" use case, + ///
a login of a user on not owned device for representative entitlement only. + ///
The _x-authorize-representative_ parameter will force an authentication of the user with egK + pin only and limit the possible operations to entitlement management only. + ///
A client shall use the returned redirect url to invoke the authenticator. <br/> + ///
+ ///
A client shall use parameter _x-authorize-egk_ for a login in guest mode with egk and pin, e.g. of a validation identity + ///
(i.e. "Prüfkarte eGK"), forcing the authorization service to request an authentication at the identity provider + ///
in guest mode (eGK + pin). + ///
A client shall use the returned redirect url to invoke the authenticator. + ///
+ ///
**Provider**:</br> + ///
The authorization service shall send a pushed authorization request (PAR) to the IDP (see: find more details). + ///
+ ///
The _redirect_uri_ parameter of the PAR shall be set to a predefined value when operation parameter + ///
_x-redirecturi_ is not present, else the content of _x-redirecturi_ shall be used (according to A_25717-*). + ///
+ ///
The authorize representative situation (_x-authorize-representative_ == _true_) shall be kept for the subsequent + ///
_sendAuthCodeFdV_ and device management operations. + ///
+ ///
For the _x-authorize-representative_ and the _x-authorize-egk_ case the PAR for the IDP shall include: + ///
- amr = urn:telematik:auth:guest:eGK + ///
+ ///
_x-authorize-representative_ and _x-authorize-egk_ both should not be set to _true_ at the same time. + ///
+ ///
This operation shall be rejected if the corresponding user session is already authorized. Repeated authorization + ///
attempts are not supported. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 302 ||| + ///
| Request does not match schema | 400 | malformedRequest | also if both "x-authorize"-parameters are set to _true_ | + ///
| Invalid request | 403 | invalAuth | includes any error of Authorization Service and IDP which is not mapped to 500 internal Server error | + ///
| unregistered redirecturi | 403 | invalRedir | redirecturi in _x-redirecturi_ is not known, registration required | + ///
| Invalid URI (x-idp-iss) | 404 | noResource | | + ///
| Repeated authorization attempt | 409 | statusMismatch | when user session is already authorized only | + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| _authorize_representative_ kept for subsequent _sendAuthCodeFdV_ evaluation | if applicable | + ///
+ /// The issuer Identifier (URL) of the IDP to be used for user authentication + /// This parameter shall be absent or set to _true_ to indicate an authorization request without epa device management registration checks. + /// This parameter shall be absent or set to _true_ to indicate an authorization request in guest mode with egk + pin e.g. for validation identities. + /// An optional redirecturi (URL) to be used in PAR for redirection of the authorizationcode. The redirecturi must be registered as valid on the epa application server (entity statement) + /// user agent information + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task SendAuthorizationRequestFdVAsync(string x_idp_iss, bool? x_authorize_representative, bool? x_authorize_egk, string x_redirecturi, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_idp_iss == null) + throw new System.ArgumentNullException("x_idp_iss"); + request_.Headers.TryAddWithoutValidation("x-idp-iss", ConvertToString(x_idp_iss, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_authorize_representative != null) + request_.Headers.TryAddWithoutValidation("x-authorize-representative", ConvertToString(x_authorize_representative, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_authorize_egk != null) + request_.Headers.TryAddWithoutValidation("x-authorize-egk", ConvertToString(x_authorize_egk, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_redirecturi != null) + request_.Headers.TryAddWithoutValidation("x-redirecturi", ConvertToString(x_redirecturi, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/authz/v1/send_authorization_request_fdv" + urlBuilder_.Append("epa/authz/v1/send_authorization_request_fdv"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 302) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new AuthorizationServiceException("Found", status_, responseText_, headers_, null); + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 404) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Not found.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + + if (status_ == 200 || status_ == 204) + { + + return; + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new AuthorizationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (sendAuthCodeFdV) Send authorization code + /// + /// + /// Send the authorization code to the authorization service to complete the login and (optional) + ///
verify the device registration. + ///
+ ///
**Client**:</br> + ///
A client shall always send the authorization code received from the authenticator / IDP. <br/> + ///
+ ///
A client shall send both, _x-device-identifier_ and _x-device-token_, on login to the home system + ///
of the user for proof of a registered device. + ///
+ ///
If the user has a device registration in another home system, then a device attestation from his home + ///
system must be used and a client shall submit _x-device-attestation_ (instead of _x-device-identifier_ + ///
and _x-device-token_). A client can obtain a device attestation from the home system via a + ///
_getDeviceAttestation_ operation call. + ///
+ ///
A client shall not send _x-device-identifier_ and _x-device-token_ or even _x-device-attestation_ + ///
(suppress parameters at all) if the device is not yet registered and confirmed or if the preceding + ///
_sendAuthorizationRequestFdV_ call includes the parameter _x-authorize_representative_ == _true_. + ///
+ ///
(For registration of a new device, including confirmation of the registration, see Device Management + ///
Service operations _registerDevice_ and _confirmDevice_). + ///
+ ///
+ ///
**Provider**:</br> + ///
The provided authorization code shall be exchanged for an ID-Token with the IDP. The ID-Token shall be converted + ///
into a HSM-ID-Token with an extended validity period. + ///
+ ///
Device verification - home system:</br> + ///
If _x-device-identifier_ and _x-device-token_ are both submitted the device verification starts immediately after + ///
the authorization completion. + ///
Device identifier and -token shall be verified with the registered values. + ///
The x-device-identifier / x-device-token check shall only consider device registrations for the authorized user. + ///
+ ///
Device verification - other than home system:</br> + ///
If _x-device-attestation_ is submitted the device verification starts immediately after the authorization completion. + ///
The authorization service shall accept a device attestation in case + ///
- signature is valid + ///
- "exp" expiration_time is a timestamp 120 minutes in the future "iat". + ///
- current time is greater or equal than 'iat' and less than 'exp' with 15 seconds tolerance ('iat' - 15s <= current time < 'exp' + 15s). + ///
- claim _actorId_ from device attestation matches kvnr of ID-Token or HSM-ID-Token. + ///
+ ///
If the device attestation is valid by signature and time, and the KVNR submitted in device attestation matches the + ///
KVNR of the authorized user the authorization service shall accept the device registration. + ///
+ ///
On success (ID-Token / HSM-ID-Token received and device binding check successful) a new user session shall be instantiated, + ///
associated to the HSM-ID-Token. + ///
+ ///
If device verification succeeds, access to all services of a health record shall be possible for the associated + ///
user session. + ///
if x-authorize-representative is set, access to the user's health record entitlement management only shall be + ///
possible for the user session. + ///
In all other (success cases) access of the user session shall be limited to the device management service. + ///
+ ///
The user session of a client shall be closed and all session related data shall be deleted in case operation is not successful. + ///
+ ///
The VAU user preudonym as generated for the vau-channel (see: vau protocol) shall be returned in a successful operation response. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Only _x-device-identifier_ or _x-device-token_ provided | 400 | paramExcpected | both parameters required or none | + ///
| (_x-device-identifier_ and/or _x-device-token_) and _x-device-attestation_ provided | 400 | paramExcpected | use only registration of home system, another system or none (yet unregistered device) | + ///
| _authorize_representative_ is set and _x-device-identifier_ and/or _x-device-token_ and/or x-device-attestation_ provided | 400 | authorizeRep | _x-authorize_representative_ from preceding sendAuthorizationRequestFdV | + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| _authorizationCode_ not valid | 403 | invalAuth | includes any error of Authorization Service and IDP which is not mapped to 500 internal Server error | + ///
| Wrong _x-device-token_ | 403 | invalidToken | if both parameters avaiable and allowed| + ///
| Invalid _x-device-attestation_ | 403 | invalSignature || + ///
| Device registration does not exist (_x-device-identifier_)| 404| noResource | also if device is not associated to requestor kvnr | + ///
| Device registration not confirmed (_status_ == _pending_) | 409 | statusMismatch | confirm pending device registration before retry | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| user session has valid HSM-ID-Token | successful operation only | + ///
| user session contains device verification result | successful operation with device parameters only | + ///
| _lastUse_ of device registration is updated to current time | successful operation with device parameters only | + ///
| user session and temporary data is deleted | failed operation only | + ///
+ /// The deviceidentifier of a device registration + /// The devicetoken of a device registration + /// The deviceAttestation of a device registration + /// user agent information + /// OK, Successful login + /// A server side error occurred. + public virtual System.Threading.Tasks.Task SendAuthCodeFdVAsync(System.Guid? x_device_identifier, string x_device_token, DeviceAttestationType x_device_attestation, SendAuthCodeFdVtype body, string x_useragent) + { + return SendAuthCodeFdVAsync(x_device_identifier, x_device_token, x_device_attestation, body, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (sendAuthCodeFdV) Send authorization code + /// + /// + /// Send the authorization code to the authorization service to complete the login and (optional) + ///
verify the device registration. + ///
+ ///
**Client**:</br> + ///
A client shall always send the authorization code received from the authenticator / IDP. <br/> + ///
+ ///
A client shall send both, _x-device-identifier_ and _x-device-token_, on login to the home system + ///
of the user for proof of a registered device. + ///
+ ///
If the user has a device registration in another home system, then a device attestation from his home + ///
system must be used and a client shall submit _x-device-attestation_ (instead of _x-device-identifier_ + ///
and _x-device-token_). A client can obtain a device attestation from the home system via a + ///
_getDeviceAttestation_ operation call. + ///
+ ///
A client shall not send _x-device-identifier_ and _x-device-token_ or even _x-device-attestation_ + ///
(suppress parameters at all) if the device is not yet registered and confirmed or if the preceding + ///
_sendAuthorizationRequestFdV_ call includes the parameter _x-authorize_representative_ == _true_. + ///
+ ///
(For registration of a new device, including confirmation of the registration, see Device Management + ///
Service operations _registerDevice_ and _confirmDevice_). + ///
+ ///
+ ///
**Provider**:</br> + ///
The provided authorization code shall be exchanged for an ID-Token with the IDP. The ID-Token shall be converted + ///
into a HSM-ID-Token with an extended validity period. + ///
+ ///
Device verification - home system:</br> + ///
If _x-device-identifier_ and _x-device-token_ are both submitted the device verification starts immediately after + ///
the authorization completion. + ///
Device identifier and -token shall be verified with the registered values. + ///
The x-device-identifier / x-device-token check shall only consider device registrations for the authorized user. + ///
+ ///
Device verification - other than home system:</br> + ///
If _x-device-attestation_ is submitted the device verification starts immediately after the authorization completion. + ///
The authorization service shall accept a device attestation in case + ///
- signature is valid + ///
- "exp" expiration_time is a timestamp 120 minutes in the future "iat". + ///
- current time is greater or equal than 'iat' and less than 'exp' with 15 seconds tolerance ('iat' - 15s <= current time < 'exp' + 15s). + ///
- claim _actorId_ from device attestation matches kvnr of ID-Token or HSM-ID-Token. + ///
+ ///
If the device attestation is valid by signature and time, and the KVNR submitted in device attestation matches the + ///
KVNR of the authorized user the authorization service shall accept the device registration. + ///
+ ///
On success (ID-Token / HSM-ID-Token received and device binding check successful) a new user session shall be instantiated, + ///
associated to the HSM-ID-Token. + ///
+ ///
If device verification succeeds, access to all services of a health record shall be possible for the associated + ///
user session. + ///
if x-authorize-representative is set, access to the user's health record entitlement management only shall be + ///
possible for the user session. + ///
In all other (success cases) access of the user session shall be limited to the device management service. + ///
+ ///
The user session of a client shall be closed and all session related data shall be deleted in case operation is not successful. + ///
+ ///
The VAU user preudonym as generated for the vau-channel (see: vau protocol) shall be returned in a successful operation response. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Only _x-device-identifier_ or _x-device-token_ provided | 400 | paramExcpected | both parameters required or none | + ///
| (_x-device-identifier_ and/or _x-device-token_) and _x-device-attestation_ provided | 400 | paramExcpected | use only registration of home system, another system or none (yet unregistered device) | + ///
| _authorize_representative_ is set and _x-device-identifier_ and/or _x-device-token_ and/or x-device-attestation_ provided | 400 | authorizeRep | _x-authorize_representative_ from preceding sendAuthorizationRequestFdV | + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| _authorizationCode_ not valid | 403 | invalAuth | includes any error of Authorization Service and IDP which is not mapped to 500 internal Server error | + ///
| Wrong _x-device-token_ | 403 | invalidToken | if both parameters avaiable and allowed| + ///
| Invalid _x-device-attestation_ | 403 | invalSignature || + ///
| Device registration does not exist (_x-device-identifier_)| 404| noResource | also if device is not associated to requestor kvnr | + ///
| Device registration not confirmed (_status_ == _pending_) | 409 | statusMismatch | confirm pending device registration before retry | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| user session has valid HSM-ID-Token | successful operation only | + ///
| user session contains device verification result | successful operation with device parameters only | + ///
| _lastUse_ of device registration is updated to current time | successful operation with device parameters only | + ///
| user session and temporary data is deleted | failed operation only | + ///
+ /// The deviceidentifier of a device registration + /// The devicetoken of a device registration + /// The deviceAttestation of a device registration + /// user agent information + /// OK, Successful login + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task SendAuthCodeFdVAsync(System.Guid? x_device_identifier, string x_device_token, DeviceAttestationType x_device_attestation, SendAuthCodeFdVtype body, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + if (body == null) + throw new System.ArgumentNullException("body"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_device_identifier != null) + request_.Headers.TryAddWithoutValidation("x-device-identifier", ConvertToString(x_device_identifier, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_device_token != null) + request_.Headers.TryAddWithoutValidation("x-device-token", ConvertToString(x_device_token, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_device_attestation != null) + request_.Headers.TryAddWithoutValidation("x-device-attestation", ConvertToString(x_device_attestation, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + var json_ = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(body, JsonSerializerSettings); + var content_ = new System.Net.Http.ByteArrayContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/authz/v1/send_authcode_fdv" + urlBuilder_.Append("epa/authz/v1/send_authcode_fdv"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Bad Request.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Forbidden", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 404) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Not found.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new AuthorizationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (logoutFdV) Logout from user session. + /// + /// + /// A logout terminates the associated user session. For any further service usage a new + ///
authentication of the user is required. + ///
+ ///
**Client**:</br> + ///
A client shall perform this explicit logout to close the user session and all + ///
health record related activities. For further access a client shall perform a new login, including + ///
negotiation of a new VAU-channel. + ///
+ ///
**Provider**:</br> + ///
The user session of a client shall be closed and all session related + ///
data shall be deleted. Associated health record contexts shall be released / closed. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful logout | 204 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The user session and all related temporary data is terminated / deleted | successful operation only | + ///
+ /// user agent information + /// OK + /// A server side error occurred. + public virtual System.Threading.Tasks.Task LogoutFdVAsync(string x_useragent) + { + return LogoutFdVAsync(x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (logoutFdV) Logout from user session. + /// + /// + /// A logout terminates the associated user session. For any further service usage a new + ///
authentication of the user is required. + ///
+ ///
**Client**:</br> + ///
A client shall perform this explicit logout to close the user session and all + ///
health record related activities. For further access a client shall perform a new login, including + ///
negotiation of a new VAU-channel. + ///
+ ///
**Provider**:</br> + ///
The user session of a client shall be closed and all session related + ///
data shall be deleted. Associated health record contexts shall be released / closed. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful logout | 204 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The user session and all related temporary data is terminated / deleted | successful operation only | + ///
+ /// user agent information + /// OK + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task LogoutFdVAsync(string x_useragent, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/authz/v1/logoutFdV" + urlBuilder_.Append("epa/authz/v1/logoutFdV"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 204) + { + return; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new AuthorizationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new AuthorizationServiceException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new AuthorizationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + protected struct ObjectResponseResult + { + public ObjectResponseResult(T responseObject, string responseText) + { + this.Object = responseObject; + this.Text = responseText; + } + + public T Object { get; } + + public string Text { get; } + } + + public bool ReadResponseAsString { get; set; } + + protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken) + { + if (response == null || response.Content == null) + { + return new ObjectResponseResult(default(T), string.Empty); + } + + if (ReadResponseAsString) + { + var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + var typedBody = System.Text.Json.JsonSerializer.Deserialize(responseText, JsonSerializerSettings); + return new ObjectResponseResult(typedBody, responseText); + } + catch (System.Text.Json.JsonException exception) + { + var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; + throw new AuthorizationServiceException(message, (int)response.StatusCode, responseText, headers, exception); + } + } + else + { + try + { + using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) + { + var typedBody = await System.Text.Json.JsonSerializer.DeserializeAsync(responseStream, JsonSerializerSettings, cancellationToken).ConfigureAwait(false); + return new ObjectResponseResult(typedBody, string.Empty); + } + } + catch (System.Text.Json.JsonException exception) + { + var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; + throw new AuthorizationServiceException(message, (int)response.StatusCode, string.Empty, headers, exception); + } + } + } + + private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) + { + if (value == null) + { + return ""; + } + + if (value is System.Enum) + { + var name = System.Enum.GetName(value.GetType(), value); + if (name != null) + { + var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name); + if (field != null) + { + var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) + as System.Runtime.Serialization.EnumMemberAttribute; + if (attribute != null) + { + return attribute.Value != null ? attribute.Value : name; + } + } + + var converted = System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo)); + return converted == null ? string.Empty : converted; + } + } + else if (value is bool) + { + return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant(); + } + else if (value is byte[]) + { + return System.Convert.ToBase64String((byte[]) value); + } + else if (value is string[]) + { + return string.Join(",", (string[])value); + } + else if (value.GetType().IsArray) + { + var valueArray = (System.Array)value; + var valueTextArray = new string[valueArray.Length]; + for (var i = 0; i < valueArray.Length; i++) + { + valueTextArray[i] = ConvertToString(valueArray.GetValue(i), cultureInfo); + } + return string.Join(",", valueTextArray); + } + + var result = System.Convert.ToString(value, cultureInfo); + return result == null ? "" : result; + } + } + + /// + /// "A JSON Web Token (JWT) with following format build according to RFC-7515:</br> + ///
base64url (protected_header) + '.' + base64url (payload) + '.' + base64url (signature)"</br> + ///
Content for device attestation:</br> + ///
- protected_header contains: + ///
- "typ": "JWT" + ///
- "alg": "ES256" + ///
- "x5c": signature certificate (C.FD.SIG) + ///
- payload claims: + ///
- "iat" issued_at is the timestamp of the time of issue. + ///
- "exp" expiration_time is a timestamp 120 minutes in the future "iat". + ///
- "actorId": KVNR + ///
- signature contains token signature + ///
+ ///
+ [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class DeviceAttestationType + { + + [System.Text.Json.Serialization.JsonPropertyName("jwt")] + public string Jwt { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Authorization code and client attestation + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class SendAuthCodeSCtype + { + + [System.Text.Json.Serialization.JsonPropertyName("authorizationCode")] + public string AuthorizationCode { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("clientAttest")] + public string ClientAttest { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Authorization code + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class SendAuthCodeFdVtype + { + + [System.Text.Json.Serialization.JsonPropertyName("authorizationCode")] + public string AuthorizationCode { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Search access-token as received from FHIR Directory + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class SearchAccessTokenType + { + + [System.Text.Json.Serialization.JsonPropertyName("access_token")] + public string Access_token { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("token_type")] + public string Token_type { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("expires_in")] + public int Expires_in { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// "A JSON Web Token (JWT) with following format build according to RFC-7515:</br> + ///
base64url (protected_header) + '.' + base64url (payload) + '.' + base64url (signature)"</br> + ///
Content for ePrescription backend bearerToken</br> + ///
(expiration time is implicite, HSM rule 'rr0' will reject tokens with 'iat' + ///
more than 10 minutes in the past of current time.)</br> + ///
- protected_header contains: + ///
- "typ": "JWT" + ///
- "alg": "ES256" + ///
- "x5c": signature certificate c.fd.aut + ///
- payload claims: + ///
- "type": "ePA-Authentisierung über PKI" (fixed value) + ///
- "iat" issued_at is the timestamp of the time of issue. + ///
- "challenge": freshness parameter (base64 encoded) + ///
- "sub": Telematik-ID ePrescription backend + ///
- signature: contains token signature + ///
+ ///
+ [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class BearerTokenType + { + + [System.Text.Json.Serialization.JsonPropertyName("bearerToken")] + public string BearerToken { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Error object with additional information about the occurred error + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class ErrorType + { + /// + /// Error condition specifier + /// + + [System.Text.Json.Serialization.JsonPropertyName("errorCode")] + public string ErrorCode { get; set; } + + /// + /// Additional details regarding the error condition (if applicable) + /// + + [System.Text.Json.Serialization.JsonPropertyName("errorDetail")] + public string ErrorDetail { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// A new nonce + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response + { + + [System.Text.Json.Serialization.JsonPropertyName("nonce")] + public string Nonce { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response2 + { + + [System.Text.Json.Serialization.JsonPropertyName("vau-np")] + public string VauNp { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response3 + { + /// + /// A base64 encoded freshness parameter for a bearer token (health record system specific content) + /// + + [System.Text.Json.Serialization.JsonPropertyName("freshness")] + public byte[] Freshness { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response4 + { + + [System.Text.Json.Serialization.JsonPropertyName("vau-np")] + public string VauNp { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("actorId")] + public string ActorId { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("displayName")] + public string DisplayName { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + + + [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class AuthorizationServiceException : System.Exception + { + public int StatusCode { get; private set; } + + public string Response { get; private set; } + + public System.Collections.Generic.IReadOnlyDictionary> Headers { get; private set; } + + public AuthorizationServiceException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Exception innerException) + : base(message + "\n\nStatus: " + statusCode + "\nResponse: \n" + ((response == null) ? "(null)" : response.Substring(0, response.Length >= 512 ? 512 : response.Length)), innerException) + { + StatusCode = statusCode; + Response = response; + Headers = headers; + } + + public override string ToString() + { + return string.Format("HTTP Response: \n\n{0}\n\n{1}", Response, base.ToString()); + } + } + + [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class AuthorizationServiceException : AuthorizationServiceException + { + public TResult Result { get; private set; } + + public AuthorizationServiceException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, TResult result, System.Exception innerException) + : base(message, statusCode, response, headers, innerException) + { + Result = result; + } + } + +} + +#pragma warning restore 108 +#pragma warning restore 114 +#pragma warning restore 472 +#pragma warning restore 612 +#pragma warning restore 1573 +#pragma warning restore 1591 +#pragma warning restore 8073 +#pragma warning restore 3016 +#pragma warning restore 8600 +#pragma warning restore 8602 +#pragma warning restore 8603 +#pragma warning restore 8604 +#pragma warning restore 8625 \ No newline at end of file diff --git a/lib-vau-csharp-test/EpaApiClients/Auth/nswag.json b/lib-vau-csharp-test/EpaApiClients/Auth/nswag.json new file mode 100644 index 0000000..920512d --- /dev/null +++ b/lib-vau-csharp-test/EpaApiClients/Auth/nswag.json @@ -0,0 +1,57 @@ +{ + "runtime": "net80", + "documentGenerator": { + "fromDocument": { + "url": "https://raw.githubusercontent.com/gematik/ePA-Basic/refs/heads/ePA-3.0.5/src/openapi/I_Authorization_Service.yaml", + "newLineBehavior": "Auto" + } + }, + "codeGenerators": { + "openApiToCSharpClient": { + "generateClientClasses": true, + "generateDtoTypes": true, + "injectHttpClient": true, + "disposeHttpClient": false, + "generateExceptionClasses": true, + "exceptionClass": "AuthorizationServiceException", + "wrapDtoExceptions": true, + "useHttpClientCreationMethod": false, + "httpClientType": "System.Net.Http.HttpClient", + "useHttpRequestMessageCreationMethod": false, + "useBaseUrl": false, + "generateBaseUrlProperty": false, + "generateSyncMethods": false, + "exposeJsonSerializerSettings": false, + "generateClientInterfaces": true, + "clientClassAccessModifier": "public", + "typeAccessModifier": "public", + "generateContractsOutput": false, + "parameterDateTimeFormat": "s", + "generateUpdateJsonSerializerSettingsMethod": true, + "serializeTypeInformation": false, + "queryNullValue": "", + "className": "AuthorizationServiceClient", + "operationGenerationMode": "MultipleClientsFromOperationId", + "generateOptionalParameters": false, + "generateJsonMethods": false, + "wrapResponses": false, + "generateResponseClasses": true, + "responseClass": "AuthorizationServiceResponse", + "requiredPropertiesMustBeDefined": true, + "dateType": "System.DateTime", + "dateTimeType": "System.DateTime", + "timeType": "System.TimeSpan", + "timeSpanType": "System.TimeSpan", + "generateDefaultValues": true, + "generateDataAnnotations": false, + "excludedTypeNames": [], + "handleReferences": false, + "namespace": "lib_vau_csharp_test.EpaApiClients.Auth", + "generateImmutableArrayProperties": false, + "generateImmutableDictionaryProperties": false, + "output": "AuthorizationServiceClient.cs", + "jsonLibrary": "SystemTextJson", + "jsonSerializerSettingsTransformationMethod": null + } + } +} diff --git a/lib-vau-csharp-test/EpaApiClients/EntitlementManagement/EntitlementManagementClient.cs b/lib-vau-csharp-test/EpaApiClients/EntitlementManagement/EntitlementManagementClient.cs new file mode 100644 index 0000000..d57a2d3 --- /dev/null +++ b/lib-vau-csharp-test/EpaApiClients/EntitlementManagement/EntitlementManagementClient.cs @@ -0,0 +1,3557 @@ +//---------------------- +// +// Generated using the NSwag toolchain v14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0)) (http://NSwag.org) +// +//---------------------- + +#pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended." +#pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." +#pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?' +#pragma warning disable 612 // Disable "CS0612 '...' is obsolete" +#pragma warning disable 649 // Disable "CS0649 Field is never assigned to, and will always have its default value null" +#pragma warning disable 1573 // Disable "CS1573 Parameter '...' has no matching param tag in the XML comment for ... +#pragma warning disable 1591 // Disable "CS1591 Missing XML comment for publicly visible type or member ..." +#pragma warning disable 8073 // Disable "CS8073 The result of the expression is always 'false' since a value of type 'T' is never equal to 'null' of type 'T?'" +#pragma warning disable 3016 // Disable "CS3016 Arrays as attribute arguments is not CLS-compliant" +#pragma warning disable 8600 // Disable "CS8600 Converting null literal or possible null value to non-nullable type" +#pragma warning disable 8602 // Disable "CS8602 Dereference of a possibly null reference" +#pragma warning disable 8603 // Disable "CS8603 Possible null reference return" +#pragma warning disable 8604 // Disable "CS8604 Possible null reference argument for parameter" +#pragma warning disable 8625 // Disable "CS8625 Cannot convert null literal to non-nullable reference type" +#pragma warning disable 8765 // Disable "CS8765 Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes)." + +namespace lib_vau_csharp_test.EpaApiClients.EntitlementManagement +{ + using System = global::System; + + [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial interface IEntitlementManagementClient + { + /// + /// (getEntitlements) Get a list of all granted entitlements, their related user and validity period + /// + /// + /// Get a list of actual granted entitlements of the health record.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Provider**:</br> + ///
The returned list shall contain only entitlements not expired (_validTo_).</br> + ///
+ ///
The operation shall NOT consider the static entitlements for a response (even if stored + ///
in SecureAdminStorage). + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch || + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// user agent information + /// OK. Returns a list of all entitlements + /// A server side error occurred. + System.Threading.Tasks.Task GetEntitlementsAsync(string x_insurantid, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getEntitlements) Get a list of all granted entitlements, their related user and validity period + /// + /// + /// Get a list of actual granted entitlements of the health record.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Provider**:</br> + ///
The returned list shall contain only entitlements not expired (_validTo_).</br> + ///
+ ///
The operation shall NOT consider the static entitlements for a response (even if stored + ///
in SecureAdminStorage). + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch || + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// user agent information + /// OK. Returns a list of all entitlements + /// A server side error occurred. + System.Threading.Tasks.Task GetEntitlementsAsync(string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (setEntitlement) Set a single entitlement + /// + /// + /// This operation sets a new entitlement for a health record user. Entitlements refer to a specific + ///
user, identified by its telematik-id or kvnr and grant access to the health record for a specified + ///
period of time.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Client**:</br> + ///
A client shall apply a date-time of 9999-12-31T00:00:00.000Z to the _validTo_ claim of a request for unlimited + ///
entitlements.</br> + ///
A client shall (mandatory) apply a date-time of 9999-12-31T00:00:00Z to the _validTo_ claim of a request if the + ///
entitlement addresses a user identified by a kvnr (representative).</br> + ///
A client shall (mandatory) apply a date-time of 9999-12-31T00:00:00Z to the _validTo_ claim of a request if the + ///
entitlement addresses a DiGA (oid_diga).</br> + ///
A client shall (mandatory) apply an email address for notification if a _new_ + ///
entitlement addresses a user identified by a kvnr (representative).</br> + ///
A client shall delete an assignment of the Blocked User Policy associated to the addressee of this + ///
entitlement request first (entitlement is applicable for non-blocked users only). + ///
+ ///
**Provider**:</br> + ///
The received JWT shall be passed to the HSM for entitlement verification, using rule _rr1_ + ///
if requestor is the insurant and using rule _rr2_ if requestor is a representative (requestor + ///
kvnr != health record identifier). + ///
+ ///
The HSM rules verify JWT signature, _actorID_, _kvnr_ (associated health record) and claim + ///
in a CMAC secured result _actorId_, _kvnr_ and _validTo_. + ///
+ ///
The CMAC secured result shall be completed with the following data: + ///
- _oid_ of the entitled user (from JWT) + ///
- _displayName_ of the entitled user (from JWT) + ///
- _issued-at_ current system time + ///
- _issued-actorId_ of requestor (from request context) + ///
- _issued-displayName_ of requestor (from request context) + ///
+ ///
The completed entitlement shall be stored, encrypted by SecureAdminStorageKey of the health record.</br> + ///
Existing entitlements (same _actorId_ and _oid_, _displayName_ ignored) shall automatically be replaced by the completed entitlement. + ///
+ ///
The completed entitlement shall NOT be stored and cause operation abortion in cases: + ///
- request claims _actorId_ which is _actorId_ of a static entitlement + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and _validTo_ is not equal 9999-12-31T00:00:00Z + ///
- request claims _oid_ == oid_diga and _validTo_ is not equal 9999-12-31T00:00:00Z + ///
- request claims _actorId_ and _actorId_ is referenced by a Blocked User Policy assignment + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and requestor is not insurant + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter), entitlement is new (i.e. does not replace any existing one) and _email_ is not in request + ///
- request claims _validTo_ which is not equal or in the future of current date + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and representative limit already + ///
reached and new request does not replace existing one (i.e. requests entitlement for the 6th representative) + ///
+ ///
Representative Entitlement:</br> + ///
The maximum amount of entitled representatives is five (5). Requests exceeding this limit shall be rejected. + ///
A request for a new representative entitlement shall provide (mandatory) a notification mail address + ///
of the representative. A notification mail shall be sent to the representative using this mail address + ///
for information about the new established representative role for the insurant's health record, including + ///
kvnr and name of the insurant. The mail address provision and the notification is optional in case + ///
the new entitlement replaces an existing entitlement of the representative, but if address is available a + ///
notification shall be sent.<br> + ///
The email address shall be discarded after use and shall not be persistet. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 201 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| HSM verification failed | 403 | invalidToken || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| request claims _actorId_ which is _actorId_ of a static entitlement | 409 | invalidActorId || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and _validTo_ is not equal 9999-12-31T00:00:00Z | 409 | requestMismatch || + ///
| request claims _oid_ == oid_diga and _validTo_ is not equal 9999-12-31T00:00:00Z | 409 | requestMismatch || + ///
| request claims _actorId_ and _actorId_ is referenced by a Blocked User Policy assignment | 409 | blockedActorId || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and requestor is not insurant | 409 | requestMismatch || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and _email_ is not in request | 409 | noMail || + ///
| request claims _validTo_ which is not equal or in the future of current date | 409 | requestMismatch || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and representative limit already reached | 409 | representativeLimit | only if limit is exceeded | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The valid and completed entitlement is stored in SecureDataStorage | a possible existing entitlement is replaced | + ///
| Entitlement notification is sent | if applicable, for representative entitlement only | + ///
| A log-entry for the operation exists | successful operation only | + ///
| The raw-data of the operation is collected and associated to _useragent_ | for any operation result according to gemSpec_Perf UC_A2.2 and UC_A2.5 | + ///
+ /// Health Record Identifier. + /// user agent information + /// Created + /// A server side error occurred. + System.Threading.Tasks.Task SetEntitlementAsync(Body body, string x_insurantid, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (setEntitlement) Set a single entitlement + /// + /// + /// This operation sets a new entitlement for a health record user. Entitlements refer to a specific + ///
user, identified by its telematik-id or kvnr and grant access to the health record for a specified + ///
period of time.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Client**:</br> + ///
A client shall apply a date-time of 9999-12-31T00:00:00.000Z to the _validTo_ claim of a request for unlimited + ///
entitlements.</br> + ///
A client shall (mandatory) apply a date-time of 9999-12-31T00:00:00Z to the _validTo_ claim of a request if the + ///
entitlement addresses a user identified by a kvnr (representative).</br> + ///
A client shall (mandatory) apply a date-time of 9999-12-31T00:00:00Z to the _validTo_ claim of a request if the + ///
entitlement addresses a DiGA (oid_diga).</br> + ///
A client shall (mandatory) apply an email address for notification if a _new_ + ///
entitlement addresses a user identified by a kvnr (representative).</br> + ///
A client shall delete an assignment of the Blocked User Policy associated to the addressee of this + ///
entitlement request first (entitlement is applicable for non-blocked users only). + ///
+ ///
**Provider**:</br> + ///
The received JWT shall be passed to the HSM for entitlement verification, using rule _rr1_ + ///
if requestor is the insurant and using rule _rr2_ if requestor is a representative (requestor + ///
kvnr != health record identifier). + ///
+ ///
The HSM rules verify JWT signature, _actorID_, _kvnr_ (associated health record) and claim + ///
in a CMAC secured result _actorId_, _kvnr_ and _validTo_. + ///
+ ///
The CMAC secured result shall be completed with the following data: + ///
- _oid_ of the entitled user (from JWT) + ///
- _displayName_ of the entitled user (from JWT) + ///
- _issued-at_ current system time + ///
- _issued-actorId_ of requestor (from request context) + ///
- _issued-displayName_ of requestor (from request context) + ///
+ ///
The completed entitlement shall be stored, encrypted by SecureAdminStorageKey of the health record.</br> + ///
Existing entitlements (same _actorId_ and _oid_, _displayName_ ignored) shall automatically be replaced by the completed entitlement. + ///
+ ///
The completed entitlement shall NOT be stored and cause operation abortion in cases: + ///
- request claims _actorId_ which is _actorId_ of a static entitlement + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and _validTo_ is not equal 9999-12-31T00:00:00Z + ///
- request claims _oid_ == oid_diga and _validTo_ is not equal 9999-12-31T00:00:00Z + ///
- request claims _actorId_ and _actorId_ is referenced by a Blocked User Policy assignment + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and requestor is not insurant + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter), entitlement is new (i.e. does not replace any existing one) and _email_ is not in request + ///
- request claims _validTo_ which is not equal or in the future of current date + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and representative limit already + ///
reached and new request does not replace existing one (i.e. requests entitlement for the 6th representative) + ///
+ ///
Representative Entitlement:</br> + ///
The maximum amount of entitled representatives is five (5). Requests exceeding this limit shall be rejected. + ///
A request for a new representative entitlement shall provide (mandatory) a notification mail address + ///
of the representative. A notification mail shall be sent to the representative using this mail address + ///
for information about the new established representative role for the insurant's health record, including + ///
kvnr and name of the insurant. The mail address provision and the notification is optional in case + ///
the new entitlement replaces an existing entitlement of the representative, but if address is available a + ///
notification shall be sent.<br> + ///
The email address shall be discarded after use and shall not be persistet. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 201 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| HSM verification failed | 403 | invalidToken || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| request claims _actorId_ which is _actorId_ of a static entitlement | 409 | invalidActorId || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and _validTo_ is not equal 9999-12-31T00:00:00Z | 409 | requestMismatch || + ///
| request claims _oid_ == oid_diga and _validTo_ is not equal 9999-12-31T00:00:00Z | 409 | requestMismatch || + ///
| request claims _actorId_ and _actorId_ is referenced by a Blocked User Policy assignment | 409 | blockedActorId || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and requestor is not insurant | 409 | requestMismatch || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and _email_ is not in request | 409 | noMail || + ///
| request claims _validTo_ which is not equal or in the future of current date | 409 | requestMismatch || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and representative limit already reached | 409 | representativeLimit | only if limit is exceeded | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The valid and completed entitlement is stored in SecureDataStorage | a possible existing entitlement is replaced | + ///
| Entitlement notification is sent | if applicable, for representative entitlement only | + ///
| A log-entry for the operation exists | successful operation only | + ///
| The raw-data of the operation is collected and associated to _useragent_ | for any operation result according to gemSpec_Perf UC_A2.2 and UC_A2.5 | + ///
+ /// Health Record Identifier. + /// user agent information + /// Created + /// A server side error occurred. + System.Threading.Tasks.Task SetEntitlementAsync(Body body, string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (getEntitlement) Get a single specific entitlement + /// + /// + /// Get a specific granted and not expired entitlement of the health record.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Client**:</br> + ///
no recommendations. + ///
+ ///
**Provider**:</br> + ///
The response shall contain the entitlement related to _actorId_ if available + ///
+ ///
The operation shall NOT consider the static entitlements for a response (even if stored + ///
in SecureAdminStorage). + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Entitlement (_actorId_) does not exist | 404 | noResource | applies also if _actorId_ refers to a static entitlement | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch || + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// user agent information + /// OK + /// A server side error occurred. + System.Threading.Tasks.Task GetEntitlementAsync(string actorId, string x_insurantid, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getEntitlement) Get a single specific entitlement + /// + /// + /// Get a specific granted and not expired entitlement of the health record.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Client**:</br> + ///
no recommendations. + ///
+ ///
**Provider**:</br> + ///
The response shall contain the entitlement related to _actorId_ if available + ///
+ ///
The operation shall NOT consider the static entitlements for a response (even if stored + ///
in SecureAdminStorage). + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Entitlement (_actorId_) does not exist | 404 | noResource | applies also if _actorId_ refers to a static entitlement | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch || + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// user agent information + /// OK + /// A server side error occurred. + System.Threading.Tasks.Task GetEntitlementAsync(string actorId, string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (deleteEntitlement) Delete a single specific entitlement + /// + /// + /// Delete one existing entitlement.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Client**:</br> + ///
The client shall not delete static entilements. The client of a representative shall not delete + ///
entitlements of other representatives. + ///
+ ///
**Provider**:</br> + ///
The addressed entitlement shall be finally removed from the SecureAdminStorage.</br> + ///
Deletion of entitlements addressing a kvnr (actorId = kvnr, oid = oid_versicherter) shall only be + ///
successful if requestor is the insurant (kvnr == health record identifier) or the entitled + ///
representative (actorId == kvnr of requestor), i.e. a representative shall not delete entitlements + ///
of other representatives.</br> + ///
Deletion of static entitlements shall not be successful. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 204 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| Requestor is representative deleting an entitlement of another representative | 403 | accessDenied || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Entitlement to delete does not exist | 404 | noResource || + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Parameter _actorId_ refers to a static entitlement| 409 | requestMismatch || + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The addressed assignment is removed from the associated policy || + ///
| A log-entry for the operation exists | successful operation only | + ///
+ /// Health Record Identifier. + /// user agent information + /// OK + /// A server side error occurred. + System.Threading.Tasks.Task DeleteEntitlementAsync(string actorId, string x_insurantid, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (deleteEntitlement) Delete a single specific entitlement + /// + /// + /// Delete one existing entitlement.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Client**:</br> + ///
The client shall not delete static entilements. The client of a representative shall not delete + ///
entitlements of other representatives. + ///
+ ///
**Provider**:</br> + ///
The addressed entitlement shall be finally removed from the SecureAdminStorage.</br> + ///
Deletion of entitlements addressing a kvnr (actorId = kvnr, oid = oid_versicherter) shall only be + ///
successful if requestor is the insurant (kvnr == health record identifier) or the entitled + ///
representative (actorId == kvnr of requestor), i.e. a representative shall not delete entitlements + ///
of other representatives.</br> + ///
Deletion of static entitlements shall not be successful. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 204 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| Requestor is representative deleting an entitlement of another representative | 403 | accessDenied || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Entitlement to delete does not exist | 404 | noResource || + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Parameter _actorId_ refers to a static entitlement| 409 | requestMismatch || + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The addressed assignment is removed from the associated policy || + ///
| A log-entry for the operation exists | successful operation only | + ///
+ /// Health Record Identifier. + /// user agent information + /// OK + /// A server side error occurred. + System.Threading.Tasks.Task DeleteEntitlementAsync(string actorId, string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (setEntitlementPs) Set a single entitlement with proof of audit evidence + /// + /// + /// Set an entitlement with predefined validity period for the requesting user in a + ///
treatment situation.</br> + ///
This operation is limited to users of the "Allowed usergroups for entitlements with proof of audit". + ///
+ ///
**Client**:</br> + ///
A client shall use this operation in a patient presence situation only, i.e. in case + ///
the vsdm update service provides a proof of audit as result of a validation procedure + ///
of a physical health insurance card (eGK) of the health record owner. + ///
+ ///
+ ///
**Provider**:</br> + ///
This operation does not require an existing entitlement for the requesting user. Instead, + ///
an entitlement for this user shall be the result of this operation. + ///
+ ///
The lack of an existing entitlement for this operation is substituted by verifiable + ///
evidence (JWT) associated to the health record owner acting as health record owner's explicit + ///
permission for the requesting user to establish a new entitlement. + ///
+ ///
The operation shall count the number of failed comparison check of _hcv_ values + ///
and also _kvnr_ for each user (telematik-id). + ///
In case of more than 5 failed comparison checks (5 checks for each counter) within 1 hour + ///
the operation shall be aborted. + ///
+ ///
The received JWT shall be passed to the HSM for entitlement verification, using rule _rr3_. + ///
+ ///
The HSM rule verifies JWT signature, _actorID_, encryption of _kvnr_ (associated health record) and claims + ///
in a CMAC secured result _actorId_, _kvnr_ and _validTo_ (_validTo_ is applied by HSM according to + ///
user role). HSM verifies also consistence of requestor properties vs claims in JWT signature + ///
and audit evidence. + ///
+ ///
The entitlement management enforces the requirements for rate limiting. + ///
+ ///
The CMAC secured result shall be completed with the following data: + ///
- _oid_ of the entitled user (from JWT or request context) + ///
- _displayName_ of the entitled user (from JWT or request context) + ///
- _issued-at_ current system time + ///
- _issued-actorId_ of requestor (from request context) + ///
- _issued-displayName_ of requestor (from request context) + ///
+ ///
The completed entitlement shall NOT be stored and cause operation abortion in cases: + ///
- _oid_ is not in the list of allowed usergroups (role) + ///
- _actorId_ is referenced by a Blocked User Policy assignment + ///
- _actorId_ is referenced by a Deny List assignment + ///
+ ///
- if _enforce_hcv_check_ == true or _hcv_ value of JWT and _hcv_ from hsm rule _rr3_ are both available: + ///
- _hcv_ value of JWT does not match _hcv_ from hsm rule _rr3_ + ///
- _x-insurantid_ does not match _kvnr_ from hsm rule _rr3_ + ///
+ ///
If an existing and stored entitlement addressing the same user exists and if this stored + ///
entitlement indicates a _validTo_ which is in the future of the new entitlement's _validTo_, + ///
then the existing entitlement shall be kept, else the completed new entitlement shall be stored, + ///
encrypted by SecureAdminStorageKey of the health record.</br> + ///
If the new entitlement is stored, a possibly existing entitlement is deleted automatically.</br> + ///
All above are success cases for this operation. + ///
The response of the operation shall return the current _validTo_ setting as information. + ///
+ ///
The addressed user of the request shall be entitled after successful operation. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 201 || even if an existing entitlement is kept due to longer validity | + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor role is not in the list of allowed usergroups | 403 | invalidOid || + ///
| Token verification failed | 403 | invalidToken || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| hcv value of jwt does not exist | 409 | hcvMissing || + ///
| request claims _actorId_ and _actorId_ is referenced by a Blocked User Policy assignment | 409 | requestMismatch || + ///
| request claims _actorId_ and _actorId_ is referenced by a Deny List assignment | 409 | requestMismatch || + ///
| Rate limiting | 423 | locked|| + ///
| to many failed attempts | 423 | locked | _hcv_ check limit | + ///
| to many failed attempts | 423 | locked | _kvnr_ check limit | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The valid and completed entitlement is stored in SecureDataStorage | a possible existing entitlement with earlier _validTo_ is replaced | + ///
| The user addressed by the new entitlement is entitled | successful operation only | + ///
| A log-entry for the operation exists | successful operation only | + ///
| The raw-data of the operation is collected and associated to _useragent_ | for any operation result according to gemSpec_Perf UC_A2.1 | + ///
+ /// Health Record Identifier. + /// user agent information + /// Created. User is entitled + /// A server side error occurred. + System.Threading.Tasks.Task SetEntitlementPsAsync(EntitlementRequestType body, string x_insurantid, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (setEntitlementPs) Set a single entitlement with proof of audit evidence + /// + /// + /// Set an entitlement with predefined validity period for the requesting user in a + ///
treatment situation.</br> + ///
This operation is limited to users of the "Allowed usergroups for entitlements with proof of audit". + ///
+ ///
**Client**:</br> + ///
A client shall use this operation in a patient presence situation only, i.e. in case + ///
the vsdm update service provides a proof of audit as result of a validation procedure + ///
of a physical health insurance card (eGK) of the health record owner. + ///
+ ///
+ ///
**Provider**:</br> + ///
This operation does not require an existing entitlement for the requesting user. Instead, + ///
an entitlement for this user shall be the result of this operation. + ///
+ ///
The lack of an existing entitlement for this operation is substituted by verifiable + ///
evidence (JWT) associated to the health record owner acting as health record owner's explicit + ///
permission for the requesting user to establish a new entitlement. + ///
+ ///
The operation shall count the number of failed comparison check of _hcv_ values + ///
and also _kvnr_ for each user (telematik-id). + ///
In case of more than 5 failed comparison checks (5 checks for each counter) within 1 hour + ///
the operation shall be aborted. + ///
+ ///
The received JWT shall be passed to the HSM for entitlement verification, using rule _rr3_. + ///
+ ///
The HSM rule verifies JWT signature, _actorID_, encryption of _kvnr_ (associated health record) and claims + ///
in a CMAC secured result _actorId_, _kvnr_ and _validTo_ (_validTo_ is applied by HSM according to + ///
user role). HSM verifies also consistence of requestor properties vs claims in JWT signature + ///
and audit evidence. + ///
+ ///
The entitlement management enforces the requirements for rate limiting. + ///
+ ///
The CMAC secured result shall be completed with the following data: + ///
- _oid_ of the entitled user (from JWT or request context) + ///
- _displayName_ of the entitled user (from JWT or request context) + ///
- _issued-at_ current system time + ///
- _issued-actorId_ of requestor (from request context) + ///
- _issued-displayName_ of requestor (from request context) + ///
+ ///
The completed entitlement shall NOT be stored and cause operation abortion in cases: + ///
- _oid_ is not in the list of allowed usergroups (role) + ///
- _actorId_ is referenced by a Blocked User Policy assignment + ///
- _actorId_ is referenced by a Deny List assignment + ///
+ ///
- if _enforce_hcv_check_ == true or _hcv_ value of JWT and _hcv_ from hsm rule _rr3_ are both available: + ///
- _hcv_ value of JWT does not match _hcv_ from hsm rule _rr3_ + ///
- _x-insurantid_ does not match _kvnr_ from hsm rule _rr3_ + ///
+ ///
If an existing and stored entitlement addressing the same user exists and if this stored + ///
entitlement indicates a _validTo_ which is in the future of the new entitlement's _validTo_, + ///
then the existing entitlement shall be kept, else the completed new entitlement shall be stored, + ///
encrypted by SecureAdminStorageKey of the health record.</br> + ///
If the new entitlement is stored, a possibly existing entitlement is deleted automatically.</br> + ///
All above are success cases for this operation. + ///
The response of the operation shall return the current _validTo_ setting as information. + ///
+ ///
The addressed user of the request shall be entitled after successful operation. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 201 || even if an existing entitlement is kept due to longer validity | + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor role is not in the list of allowed usergroups | 403 | invalidOid || + ///
| Token verification failed | 403 | invalidToken || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| hcv value of jwt does not exist | 409 | hcvMissing || + ///
| request claims _actorId_ and _actorId_ is referenced by a Blocked User Policy assignment | 409 | requestMismatch || + ///
| request claims _actorId_ and _actorId_ is referenced by a Deny List assignment | 409 | requestMismatch || + ///
| Rate limiting | 423 | locked|| + ///
| to many failed attempts | 423 | locked | _hcv_ check limit | + ///
| to many failed attempts | 423 | locked | _kvnr_ check limit | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The valid and completed entitlement is stored in SecureDataStorage | a possible existing entitlement with earlier _validTo_ is replaced | + ///
| The user addressed by the new entitlement is entitled | successful operation only | + ///
| A log-entry for the operation exists | successful operation only | + ///
| The raw-data of the operation is collected and associated to _useragent_ | for any operation result according to gemSpec_Perf UC_A2.1 | + ///
+ /// Health Record Identifier. + /// user agent information + /// Created. User is entitled + /// A server side error occurred. + System.Threading.Tasks.Task SetEntitlementPsAsync(EntitlementRequestType body, string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (getBlockedUserPolicyAssignments) get a list of blocked users + /// + /// + /// Get a list of actual set assignments of the blocked user policy.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle. + ///
+ ///
**Provider**:</br> + ///
The returned list shall contain only all assignments of the blocked user policy.</br> + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not oid_versicherter_ or _oid_ombudsstelle_| 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// user agent information + /// Ok. Returns a list of policy assignments + /// A server side error occurred. + System.Threading.Tasks.Task GetBlockedUserPolicyAssignmentsAsync(string x_insurantid, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getBlockedUserPolicyAssignments) get a list of blocked users + /// + /// + /// Get a list of actual set assignments of the blocked user policy.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle. + ///
+ ///
**Provider**:</br> + ///
The returned list shall contain only all assignments of the blocked user policy.</br> + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not oid_versicherter_ or _oid_ombudsstelle_| 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// user agent information + /// Ok. Returns a list of policy assignments + /// A server side error occurred. + System.Threading.Tasks.Task GetBlockedUserPolicyAssignmentsAsync(string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (setBlockedUserPolicyAssignment) add a user to the blocked user policy + /// + /// + /// Set a new assignment for the blocked user policy.</br> + ///
The user addressed by the policy assignment can not be entitled by any means, a possibly existing + ///
entitlement is lost.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle. + ///
+ ///
**Client**:</br> + ///
A client shall set assignments for users of the allowed roles for + ///
user blocking only.</br> + ///
+ ///
**Provider**:</br> + ///
A valid new assignment shall be added to the blocked user policy. + ///
+ ///
Each new valid assigment shall be extended by a timestamp (_at_ = current date and time) + ///
by the server. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 201 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ or _oid_ombudsstelle_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| The assignment parameter _oid_ is not in the list of allowd oids | 409 | requestMismatch || + ///
| The assignment does yet exist (same _actorId_) | 409 | requestMismatch | avoid duplicates | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The policy assignment is extended with the timestamp and stored in SecureDataStorage || + ///
| An existing entitlement for the addressed user of the assignment is deleted || + ///
| An eMail is sent to the insurant, including information about the blocked user policy change| if eMail address is available | + ///
| A log-entry for the operation exists | all operation results | + ///
+ /// Health Record Identifier. + /// user agent information + /// Created + /// A server side error occurred. + System.Threading.Tasks.Task SetBlockedUserPolicyAssignmentAsync(BlockedUserPolicyAssignmentType body, string x_insurantid, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (setBlockedUserPolicyAssignment) add a user to the blocked user policy + /// + /// + /// Set a new assignment for the blocked user policy.</br> + ///
The user addressed by the policy assignment can not be entitled by any means, a possibly existing + ///
entitlement is lost.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle. + ///
+ ///
**Client**:</br> + ///
A client shall set assignments for users of the allowed roles for + ///
user blocking only.</br> + ///
+ ///
**Provider**:</br> + ///
A valid new assignment shall be added to the blocked user policy. + ///
+ ///
Each new valid assigment shall be extended by a timestamp (_at_ = current date and time) + ///
by the server. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 201 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ or _oid_ombudsstelle_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| The assignment parameter _oid_ is not in the list of allowd oids | 409 | requestMismatch || + ///
| The assignment does yet exist (same _actorId_) | 409 | requestMismatch | avoid duplicates | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The policy assignment is extended with the timestamp and stored in SecureDataStorage || + ///
| An existing entitlement for the addressed user of the assignment is deleted || + ///
| An eMail is sent to the insurant, including information about the blocked user policy change| if eMail address is available | + ///
| A log-entry for the operation exists | all operation results | + ///
+ /// Health Record Identifier. + /// user agent information + /// Created + /// A server side error occurred. + System.Threading.Tasks.Task SetBlockedUserPolicyAssignmentAsync(BlockedUserPolicyAssignmentType body, string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (getBlockedUserPolicyAssignment) get a particular blocked user + /// + /// + /// Get one particular assignment of the blocked user policy.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle . + ///
+ ///
**Client**:</br> + ///
no recommendations. + ///
+ ///
**Provider**:</br> + ///
The addressed assigment shall be returned. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not oid_versicherter_ or _oid_ombudsstelle_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Resource for _telematikid_ does not exist | 404 | noResource || + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// TelematikID + /// user agent information + /// Ok. + /// A server side error occurred. + System.Threading.Tasks.Task GetBlockedUserPolicyAssignmentAsync(string x_insurantid, string telematikid, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getBlockedUserPolicyAssignment) get a particular blocked user + /// + /// + /// Get one particular assignment of the blocked user policy.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle . + ///
+ ///
**Client**:</br> + ///
no recommendations. + ///
+ ///
**Provider**:</br> + ///
The addressed assigment shall be returned. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not oid_versicherter_ or _oid_ombudsstelle_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Resource for _telematikid_ does not exist | 404 | noResource || + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// TelematikID + /// user agent information + /// Ok. + /// A server side error occurred. + System.Threading.Tasks.Task GetBlockedUserPolicyAssignmentAsync(string x_insurantid, string telematikid, string x_useragent, System.Threading.CancellationToken cancellationToken); + + /// + /// (deleteBlockedUserPolicyAssignment) remove a user from the blocked user policy + /// + /// + /// Delete one existing assignment of the blocked user policy.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle. + ///
+ ///
**Client**:</br> + ///
no recommendations. + ///
+ ///
**Provider**:</br> + ///
The addressed assigment shall be removed from the policy. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 204 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ or _oid_ombudsstelle_| 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Assignment (_telematikid_) does not exist | 404 | noResource || + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The addressed assignment is removed from the associated policy || + ///
| An eMail is sent to the insurant, including information about the blocked user policy change| if eMail address is available | + ///
| A log-entry for the operation exists | all operation results | + ///
+ /// Health Record Identifier. + /// TelematikID + /// user agent information + /// OK. Assignment deleted + /// A server side error occurred. + System.Threading.Tasks.Task DeleteBlockedUserPolicyAssignmentAsync(string x_insurantid, string telematikid, string x_useragent); + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (deleteBlockedUserPolicyAssignment) remove a user from the blocked user policy + /// + /// + /// Delete one existing assignment of the blocked user policy.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle. + ///
+ ///
**Client**:</br> + ///
no recommendations. + ///
+ ///
**Provider**:</br> + ///
The addressed assigment shall be removed from the policy. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 204 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ or _oid_ombudsstelle_| 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Assignment (_telematikid_) does not exist | 404 | noResource || + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The addressed assignment is removed from the associated policy || + ///
| An eMail is sent to the insurant, including information about the blocked user policy change| if eMail address is available | + ///
| A log-entry for the operation exists | all operation results | + ///
+ /// Health Record Identifier. + /// TelematikID + /// user agent information + /// OK. Assignment deleted + /// A server side error occurred. + System.Threading.Tasks.Task DeleteBlockedUserPolicyAssignmentAsync(string x_insurantid, string telematikid, string x_useragent, System.Threading.CancellationToken cancellationToken); + + } + + [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class EntitlementManagementClient : IEntitlementManagementClient + { + private System.Net.Http.HttpClient _httpClient; + private static System.Lazy _settings = new System.Lazy(CreateSerializerSettings, true); + private System.Text.Json.JsonSerializerOptions _instanceSettings; + + #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + public EntitlementManagementClient(System.Net.Http.HttpClient httpClient) + #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + { + _httpClient = httpClient; + Initialize(); + } + + private static System.Text.Json.JsonSerializerOptions CreateSerializerSettings() + { + var settings = new System.Text.Json.JsonSerializerOptions(); + UpdateJsonSerializerSettings(settings); + return settings; + } + + protected System.Text.Json.JsonSerializerOptions JsonSerializerSettings { get { return _instanceSettings ?? _settings.Value; } } + + static partial void UpdateJsonSerializerSettings(System.Text.Json.JsonSerializerOptions settings); + + partial void Initialize(); + + partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url); + partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); + partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); + + /// + /// (getEntitlements) Get a list of all granted entitlements, their related user and validity period + /// + /// + /// Get a list of actual granted entitlements of the health record.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Provider**:</br> + ///
The returned list shall contain only entitlements not expired (_validTo_).</br> + ///
+ ///
The operation shall NOT consider the static entitlements for a response (even if stored + ///
in SecureAdminStorage). + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch || + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// user agent information + /// OK. Returns a list of all entitlements + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetEntitlementsAsync(string x_insurantid, string x_useragent) + { + return GetEntitlementsAsync(x_insurantid, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getEntitlements) Get a list of all granted entitlements, their related user and validity period + /// + /// + /// Get a list of actual granted entitlements of the health record.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Provider**:</br> + ///
The returned list shall contain only entitlements not expired (_validTo_).</br> + ///
+ ///
The operation shall NOT consider the static entitlements for a response (even if stored + ///
in SecureAdminStorage). + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch || + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// user agent information + /// OK. Returns a list of all entitlements + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetEntitlementsAsync(string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/basic/api/v1/entitlements" + urlBuilder_.Append("epa/basic/api/v1/entitlements"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Bad Request.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 404) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Not found.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new EntitlementManagementException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (setEntitlement) Set a single entitlement + /// + /// + /// This operation sets a new entitlement for a health record user. Entitlements refer to a specific + ///
user, identified by its telematik-id or kvnr and grant access to the health record for a specified + ///
period of time.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Client**:</br> + ///
A client shall apply a date-time of 9999-12-31T00:00:00.000Z to the _validTo_ claim of a request for unlimited + ///
entitlements.</br> + ///
A client shall (mandatory) apply a date-time of 9999-12-31T00:00:00Z to the _validTo_ claim of a request if the + ///
entitlement addresses a user identified by a kvnr (representative).</br> + ///
A client shall (mandatory) apply a date-time of 9999-12-31T00:00:00Z to the _validTo_ claim of a request if the + ///
entitlement addresses a DiGA (oid_diga).</br> + ///
A client shall (mandatory) apply an email address for notification if a _new_ + ///
entitlement addresses a user identified by a kvnr (representative).</br> + ///
A client shall delete an assignment of the Blocked User Policy associated to the addressee of this + ///
entitlement request first (entitlement is applicable for non-blocked users only). + ///
+ ///
**Provider**:</br> + ///
The received JWT shall be passed to the HSM for entitlement verification, using rule _rr1_ + ///
if requestor is the insurant and using rule _rr2_ if requestor is a representative (requestor + ///
kvnr != health record identifier). + ///
+ ///
The HSM rules verify JWT signature, _actorID_, _kvnr_ (associated health record) and claim + ///
in a CMAC secured result _actorId_, _kvnr_ and _validTo_. + ///
+ ///
The CMAC secured result shall be completed with the following data: + ///
- _oid_ of the entitled user (from JWT) + ///
- _displayName_ of the entitled user (from JWT) + ///
- _issued-at_ current system time + ///
- _issued-actorId_ of requestor (from request context) + ///
- _issued-displayName_ of requestor (from request context) + ///
+ ///
The completed entitlement shall be stored, encrypted by SecureAdminStorageKey of the health record.</br> + ///
Existing entitlements (same _actorId_ and _oid_, _displayName_ ignored) shall automatically be replaced by the completed entitlement. + ///
+ ///
The completed entitlement shall NOT be stored and cause operation abortion in cases: + ///
- request claims _actorId_ which is _actorId_ of a static entitlement + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and _validTo_ is not equal 9999-12-31T00:00:00Z + ///
- request claims _oid_ == oid_diga and _validTo_ is not equal 9999-12-31T00:00:00Z + ///
- request claims _actorId_ and _actorId_ is referenced by a Blocked User Policy assignment + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and requestor is not insurant + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter), entitlement is new (i.e. does not replace any existing one) and _email_ is not in request + ///
- request claims _validTo_ which is not equal or in the future of current date + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and representative limit already + ///
reached and new request does not replace existing one (i.e. requests entitlement for the 6th representative) + ///
+ ///
Representative Entitlement:</br> + ///
The maximum amount of entitled representatives is five (5). Requests exceeding this limit shall be rejected. + ///
A request for a new representative entitlement shall provide (mandatory) a notification mail address + ///
of the representative. A notification mail shall be sent to the representative using this mail address + ///
for information about the new established representative role for the insurant's health record, including + ///
kvnr and name of the insurant. The mail address provision and the notification is optional in case + ///
the new entitlement replaces an existing entitlement of the representative, but if address is available a + ///
notification shall be sent.<br> + ///
The email address shall be discarded after use and shall not be persistet. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 201 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| HSM verification failed | 403 | invalidToken || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| request claims _actorId_ which is _actorId_ of a static entitlement | 409 | invalidActorId || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and _validTo_ is not equal 9999-12-31T00:00:00Z | 409 | requestMismatch || + ///
| request claims _oid_ == oid_diga and _validTo_ is not equal 9999-12-31T00:00:00Z | 409 | requestMismatch || + ///
| request claims _actorId_ and _actorId_ is referenced by a Blocked User Policy assignment | 409 | blockedActorId || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and requestor is not insurant | 409 | requestMismatch || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and _email_ is not in request | 409 | noMail || + ///
| request claims _validTo_ which is not equal or in the future of current date | 409 | requestMismatch || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and representative limit already reached | 409 | representativeLimit | only if limit is exceeded | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The valid and completed entitlement is stored in SecureDataStorage | a possible existing entitlement is replaced | + ///
| Entitlement notification is sent | if applicable, for representative entitlement only | + ///
| A log-entry for the operation exists | successful operation only | + ///
| The raw-data of the operation is collected and associated to _useragent_ | for any operation result according to gemSpec_Perf UC_A2.2 and UC_A2.5 | + ///
+ /// Health Record Identifier. + /// user agent information + /// Created + /// A server side error occurred. + public virtual System.Threading.Tasks.Task SetEntitlementAsync(Body body, string x_insurantid, string x_useragent) + { + return SetEntitlementAsync(body, x_insurantid, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (setEntitlement) Set a single entitlement + /// + /// + /// This operation sets a new entitlement for a health record user. Entitlements refer to a specific + ///
user, identified by its telematik-id or kvnr and grant access to the health record for a specified + ///
period of time.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Client**:</br> + ///
A client shall apply a date-time of 9999-12-31T00:00:00.000Z to the _validTo_ claim of a request for unlimited + ///
entitlements.</br> + ///
A client shall (mandatory) apply a date-time of 9999-12-31T00:00:00Z to the _validTo_ claim of a request if the + ///
entitlement addresses a user identified by a kvnr (representative).</br> + ///
A client shall (mandatory) apply a date-time of 9999-12-31T00:00:00Z to the _validTo_ claim of a request if the + ///
entitlement addresses a DiGA (oid_diga).</br> + ///
A client shall (mandatory) apply an email address for notification if a _new_ + ///
entitlement addresses a user identified by a kvnr (representative).</br> + ///
A client shall delete an assignment of the Blocked User Policy associated to the addressee of this + ///
entitlement request first (entitlement is applicable for non-blocked users only). + ///
+ ///
**Provider**:</br> + ///
The received JWT shall be passed to the HSM for entitlement verification, using rule _rr1_ + ///
if requestor is the insurant and using rule _rr2_ if requestor is a representative (requestor + ///
kvnr != health record identifier). + ///
+ ///
The HSM rules verify JWT signature, _actorID_, _kvnr_ (associated health record) and claim + ///
in a CMAC secured result _actorId_, _kvnr_ and _validTo_. + ///
+ ///
The CMAC secured result shall be completed with the following data: + ///
- _oid_ of the entitled user (from JWT) + ///
- _displayName_ of the entitled user (from JWT) + ///
- _issued-at_ current system time + ///
- _issued-actorId_ of requestor (from request context) + ///
- _issued-displayName_ of requestor (from request context) + ///
+ ///
The completed entitlement shall be stored, encrypted by SecureAdminStorageKey of the health record.</br> + ///
Existing entitlements (same _actorId_ and _oid_, _displayName_ ignored) shall automatically be replaced by the completed entitlement. + ///
+ ///
The completed entitlement shall NOT be stored and cause operation abortion in cases: + ///
- request claims _actorId_ which is _actorId_ of a static entitlement + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and _validTo_ is not equal 9999-12-31T00:00:00Z + ///
- request claims _oid_ == oid_diga and _validTo_ is not equal 9999-12-31T00:00:00Z + ///
- request claims _actorId_ and _actorId_ is referenced by a Blocked User Policy assignment + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and requestor is not insurant + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter), entitlement is new (i.e. does not replace any existing one) and _email_ is not in request + ///
- request claims _validTo_ which is not equal or in the future of current date + ///
- request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and representative limit already + ///
reached and new request does not replace existing one (i.e. requests entitlement for the 6th representative) + ///
+ ///
Representative Entitlement:</br> + ///
The maximum amount of entitled representatives is five (5). Requests exceeding this limit shall be rejected. + ///
A request for a new representative entitlement shall provide (mandatory) a notification mail address + ///
of the representative. A notification mail shall be sent to the representative using this mail address + ///
for information about the new established representative role for the insurant's health record, including + ///
kvnr and name of the insurant. The mail address provision and the notification is optional in case + ///
the new entitlement replaces an existing entitlement of the representative, but if address is available a + ///
notification shall be sent.<br> + ///
The email address shall be discarded after use and shall not be persistet. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 201 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| HSM verification failed | 403 | invalidToken || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| request claims _actorId_ which is _actorId_ of a static entitlement | 409 | invalidActorId || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and _validTo_ is not equal 9999-12-31T00:00:00Z | 409 | requestMismatch || + ///
| request claims _oid_ == oid_diga and _validTo_ is not equal 9999-12-31T00:00:00Z | 409 | requestMismatch || + ///
| request claims _actorId_ and _actorId_ is referenced by a Blocked User Policy assignment | 409 | blockedActorId || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and requestor is not insurant | 409 | requestMismatch || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and _email_ is not in request | 409 | noMail || + ///
| request claims _validTo_ which is not equal or in the future of current date | 409 | requestMismatch || + ///
| request claims _actorId_ == kvnr (_oid_ == oid_versicherter) and representative limit already reached | 409 | representativeLimit | only if limit is exceeded | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The valid and completed entitlement is stored in SecureDataStorage | a possible existing entitlement is replaced | + ///
| Entitlement notification is sent | if applicable, for representative entitlement only | + ///
| A log-entry for the operation exists | successful operation only | + ///
| The raw-data of the operation is collected and associated to _useragent_ | for any operation result according to gemSpec_Perf UC_A2.2 and UC_A2.5 | + ///
+ /// Health Record Identifier. + /// user agent information + /// Created + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task SetEntitlementAsync(Body body, string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + if (body == null) + throw new System.ArgumentNullException("body"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + var json_ = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(body, JsonSerializerSettings); + var content_ = new System.Net.Http.ByteArrayContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/basic/api/v1/entitlements" + urlBuilder_.Append("epa/basic/api/v1/entitlements"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 201) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Bad Request.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 404) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Not found.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new EntitlementManagementException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (getEntitlement) Get a single specific entitlement + /// + /// + /// Get a specific granted and not expired entitlement of the health record.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Client**:</br> + ///
no recommendations. + ///
+ ///
**Provider**:</br> + ///
The response shall contain the entitlement related to _actorId_ if available + ///
+ ///
The operation shall NOT consider the static entitlements for a response (even if stored + ///
in SecureAdminStorage). + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Entitlement (_actorId_) does not exist | 404 | noResource | applies also if _actorId_ refers to a static entitlement | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch || + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// user agent information + /// OK + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetEntitlementAsync(string actorId, string x_insurantid, string x_useragent) + { + return GetEntitlementAsync(actorId, x_insurantid, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getEntitlement) Get a single specific entitlement + /// + /// + /// Get a specific granted and not expired entitlement of the health record.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Client**:</br> + ///
no recommendations. + ///
+ ///
**Provider**:</br> + ///
The response shall contain the entitlement related to _actorId_ if available + ///
+ ///
The operation shall NOT consider the static entitlements for a response (even if stored + ///
in SecureAdminStorage). + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Entitlement (_actorId_) does not exist | 404 | noResource | applies also if _actorId_ refers to a static entitlement | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch || + ///
| Any other error | 500 | internalError || + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// user agent information + /// OK + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetEntitlementAsync(string actorId, string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + if (actorId == null) + throw new System.ArgumentNullException("actorId"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/basic/api/v1/entitlements/{actorId}" + urlBuilder_.Append("epa/basic/api/v1/entitlements/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(actorId, System.Globalization.CultureInfo.InvariantCulture))); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Bad Request.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 404) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Not found.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new EntitlementManagementException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (deleteEntitlement) Delete a single specific entitlement + /// + /// + /// Delete one existing entitlement.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Client**:</br> + ///
The client shall not delete static entilements. The client of a representative shall not delete + ///
entitlements of other representatives. + ///
+ ///
**Provider**:</br> + ///
The addressed entitlement shall be finally removed from the SecureAdminStorage.</br> + ///
Deletion of entitlements addressing a kvnr (actorId = kvnr, oid = oid_versicherter) shall only be + ///
successful if requestor is the insurant (kvnr == health record identifier) or the entitled + ///
representative (actorId == kvnr of requestor), i.e. a representative shall not delete entitlements + ///
of other representatives.</br> + ///
Deletion of static entitlements shall not be successful. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 204 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| Requestor is representative deleting an entitlement of another representative | 403 | accessDenied || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Entitlement to delete does not exist | 404 | noResource || + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Parameter _actorId_ refers to a static entitlement| 409 | requestMismatch || + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The addressed assignment is removed from the associated policy || + ///
| A log-entry for the operation exists | successful operation only | + ///
+ /// Health Record Identifier. + /// user agent information + /// OK + /// A server side error occurred. + public virtual System.Threading.Tasks.Task DeleteEntitlementAsync(string actorId, string x_insurantid, string x_useragent) + { + return DeleteEntitlementAsync(actorId, x_insurantid, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (deleteEntitlement) Delete a single specific entitlement + /// + /// + /// Delete one existing entitlement.</br> + ///
This operation is limited to entitled users of role oid_versicherter. + ///
+ ///
**Client**:</br> + ///
The client shall not delete static entilements. The client of a representative shall not delete + ///
entitlements of other representatives. + ///
+ ///
**Provider**:</br> + ///
The addressed entitlement shall be finally removed from the SecureAdminStorage.</br> + ///
Deletion of entitlements addressing a kvnr (actorId = kvnr, oid = oid_versicherter) shall only be + ///
successful if requestor is the insurant (kvnr == health record identifier) or the entitled + ///
representative (actorId == kvnr of requestor), i.e. a representative shall not delete entitlements + ///
of other representatives.</br> + ///
Deletion of static entitlements shall not be successful. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 204 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ | 403 | invalidOid || + ///
| Requestor is representative deleting an entitlement of another representative | 403 | accessDenied || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Entitlement to delete does not exist | 404 | noResource || + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Parameter _actorId_ refers to a static entitlement| 409 | requestMismatch || + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The addressed assignment is removed from the associated policy || + ///
| A log-entry for the operation exists | successful operation only | + ///
+ /// Health Record Identifier. + /// user agent information + /// OK + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task DeleteEntitlementAsync(string actorId, string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + if (actorId == null) + throw new System.ArgumentNullException("actorId"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("DELETE"); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/basic/api/v1/entitlements/{actorId}" + urlBuilder_.Append("epa/basic/api/v1/entitlements/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(actorId, System.Globalization.CultureInfo.InvariantCulture))); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 204) + { + return; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Bad Request.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 404) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Not found.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new EntitlementManagementException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (setEntitlementPs) Set a single entitlement with proof of audit evidence + /// + /// + /// Set an entitlement with predefined validity period for the requesting user in a + ///
treatment situation.</br> + ///
This operation is limited to users of the "Allowed usergroups for entitlements with proof of audit". + ///
+ ///
**Client**:</br> + ///
A client shall use this operation in a patient presence situation only, i.e. in case + ///
the vsdm update service provides a proof of audit as result of a validation procedure + ///
of a physical health insurance card (eGK) of the health record owner. + ///
+ ///
+ ///
**Provider**:</br> + ///
This operation does not require an existing entitlement for the requesting user. Instead, + ///
an entitlement for this user shall be the result of this operation. + ///
+ ///
The lack of an existing entitlement for this operation is substituted by verifiable + ///
evidence (JWT) associated to the health record owner acting as health record owner's explicit + ///
permission for the requesting user to establish a new entitlement. + ///
+ ///
The operation shall count the number of failed comparison check of _hcv_ values + ///
and also _kvnr_ for each user (telematik-id). + ///
In case of more than 5 failed comparison checks (5 checks for each counter) within 1 hour + ///
the operation shall be aborted. + ///
+ ///
The received JWT shall be passed to the HSM for entitlement verification, using rule _rr3_. + ///
+ ///
The HSM rule verifies JWT signature, _actorID_, encryption of _kvnr_ (associated health record) and claims + ///
in a CMAC secured result _actorId_, _kvnr_ and _validTo_ (_validTo_ is applied by HSM according to + ///
user role). HSM verifies also consistence of requestor properties vs claims in JWT signature + ///
and audit evidence. + ///
+ ///
The entitlement management enforces the requirements for rate limiting. + ///
+ ///
The CMAC secured result shall be completed with the following data: + ///
- _oid_ of the entitled user (from JWT or request context) + ///
- _displayName_ of the entitled user (from JWT or request context) + ///
- _issued-at_ current system time + ///
- _issued-actorId_ of requestor (from request context) + ///
- _issued-displayName_ of requestor (from request context) + ///
+ ///
The completed entitlement shall NOT be stored and cause operation abortion in cases: + ///
- _oid_ is not in the list of allowed usergroups (role) + ///
- _actorId_ is referenced by a Blocked User Policy assignment + ///
- _actorId_ is referenced by a Deny List assignment + ///
+ ///
- if _enforce_hcv_check_ == true or _hcv_ value of JWT and _hcv_ from hsm rule _rr3_ are both available: + ///
- _hcv_ value of JWT does not match _hcv_ from hsm rule _rr3_ + ///
- _x-insurantid_ does not match _kvnr_ from hsm rule _rr3_ + ///
+ ///
If an existing and stored entitlement addressing the same user exists and if this stored + ///
entitlement indicates a _validTo_ which is in the future of the new entitlement's _validTo_, + ///
then the existing entitlement shall be kept, else the completed new entitlement shall be stored, + ///
encrypted by SecureAdminStorageKey of the health record.</br> + ///
If the new entitlement is stored, a possibly existing entitlement is deleted automatically.</br> + ///
All above are success cases for this operation. + ///
The response of the operation shall return the current _validTo_ setting as information. + ///
+ ///
The addressed user of the request shall be entitled after successful operation. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 201 || even if an existing entitlement is kept due to longer validity | + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor role is not in the list of allowed usergroups | 403 | invalidOid || + ///
| Token verification failed | 403 | invalidToken || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| hcv value of jwt does not exist | 409 | hcvMissing || + ///
| request claims _actorId_ and _actorId_ is referenced by a Blocked User Policy assignment | 409 | requestMismatch || + ///
| request claims _actorId_ and _actorId_ is referenced by a Deny List assignment | 409 | requestMismatch || + ///
| Rate limiting | 423 | locked|| + ///
| to many failed attempts | 423 | locked | _hcv_ check limit | + ///
| to many failed attempts | 423 | locked | _kvnr_ check limit | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The valid and completed entitlement is stored in SecureDataStorage | a possible existing entitlement with earlier _validTo_ is replaced | + ///
| The user addressed by the new entitlement is entitled | successful operation only | + ///
| A log-entry for the operation exists | successful operation only | + ///
| The raw-data of the operation is collected and associated to _useragent_ | for any operation result according to gemSpec_Perf UC_A2.1 | + ///
+ /// Health Record Identifier. + /// user agent information + /// Created. User is entitled + /// A server side error occurred. + public virtual System.Threading.Tasks.Task SetEntitlementPsAsync(EntitlementRequestType body, string x_insurantid, string x_useragent) + { + return SetEntitlementPsAsync(body, x_insurantid, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (setEntitlementPs) Set a single entitlement with proof of audit evidence + /// + /// + /// Set an entitlement with predefined validity period for the requesting user in a + ///
treatment situation.</br> + ///
This operation is limited to users of the "Allowed usergroups for entitlements with proof of audit". + ///
+ ///
**Client**:</br> + ///
A client shall use this operation in a patient presence situation only, i.e. in case + ///
the vsdm update service provides a proof of audit as result of a validation procedure + ///
of a physical health insurance card (eGK) of the health record owner. + ///
+ ///
+ ///
**Provider**:</br> + ///
This operation does not require an existing entitlement for the requesting user. Instead, + ///
an entitlement for this user shall be the result of this operation. + ///
+ ///
The lack of an existing entitlement for this operation is substituted by verifiable + ///
evidence (JWT) associated to the health record owner acting as health record owner's explicit + ///
permission for the requesting user to establish a new entitlement. + ///
+ ///
The operation shall count the number of failed comparison check of _hcv_ values + ///
and also _kvnr_ for each user (telematik-id). + ///
In case of more than 5 failed comparison checks (5 checks for each counter) within 1 hour + ///
the operation shall be aborted. + ///
+ ///
The received JWT shall be passed to the HSM for entitlement verification, using rule _rr3_. + ///
+ ///
The HSM rule verifies JWT signature, _actorID_, encryption of _kvnr_ (associated health record) and claims + ///
in a CMAC secured result _actorId_, _kvnr_ and _validTo_ (_validTo_ is applied by HSM according to + ///
user role). HSM verifies also consistence of requestor properties vs claims in JWT signature + ///
and audit evidence. + ///
+ ///
The entitlement management enforces the requirements for rate limiting. + ///
+ ///
The CMAC secured result shall be completed with the following data: + ///
- _oid_ of the entitled user (from JWT or request context) + ///
- _displayName_ of the entitled user (from JWT or request context) + ///
- _issued-at_ current system time + ///
- _issued-actorId_ of requestor (from request context) + ///
- _issued-displayName_ of requestor (from request context) + ///
+ ///
The completed entitlement shall NOT be stored and cause operation abortion in cases: + ///
- _oid_ is not in the list of allowed usergroups (role) + ///
- _actorId_ is referenced by a Blocked User Policy assignment + ///
- _actorId_ is referenced by a Deny List assignment + ///
+ ///
- if _enforce_hcv_check_ == true or _hcv_ value of JWT and _hcv_ from hsm rule _rr3_ are both available: + ///
- _hcv_ value of JWT does not match _hcv_ from hsm rule _rr3_ + ///
- _x-insurantid_ does not match _kvnr_ from hsm rule _rr3_ + ///
+ ///
If an existing and stored entitlement addressing the same user exists and if this stored + ///
entitlement indicates a _validTo_ which is in the future of the new entitlement's _validTo_, + ///
then the existing entitlement shall be kept, else the completed new entitlement shall be stored, + ///
encrypted by SecureAdminStorageKey of the health record.</br> + ///
If the new entitlement is stored, a possibly existing entitlement is deleted automatically.</br> + ///
All above are success cases for this operation. + ///
The response of the operation shall return the current _validTo_ setting as information. + ///
+ ///
The addressed user of the request shall be entitled after successful operation. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 201 || even if an existing entitlement is kept due to longer validity | + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Requestor role is not in the list of allowed usergroups | 403 | invalidOid || + ///
| Token verification failed | 403 | invalidToken || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| hcv value of jwt does not exist | 409 | hcvMissing || + ///
| request claims _actorId_ and _actorId_ is referenced by a Blocked User Policy assignment | 409 | requestMismatch || + ///
| request claims _actorId_ and _actorId_ is referenced by a Deny List assignment | 409 | requestMismatch || + ///
| Rate limiting | 423 | locked|| + ///
| to many failed attempts | 423 | locked | _hcv_ check limit | + ///
| to many failed attempts | 423 | locked | _kvnr_ check limit | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The valid and completed entitlement is stored in SecureDataStorage | a possible existing entitlement with earlier _validTo_ is replaced | + ///
| The user addressed by the new entitlement is entitled | successful operation only | + ///
| A log-entry for the operation exists | successful operation only | + ///
| The raw-data of the operation is collected and associated to _useragent_ | for any operation result according to gemSpec_Perf UC_A2.1 | + ///
+ /// Health Record Identifier. + /// user agent information + /// Created. User is entitled + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task SetEntitlementPsAsync(EntitlementRequestType body, string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + if (body == null) + throw new System.ArgumentNullException("body"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + var json_ = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(body, JsonSerializerSettings); + var content_ = new System.Net.Http.ByteArrayContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/basic/api/v1/ps/entitlements" + urlBuilder_.Append("epa/basic/api/v1/ps/entitlements"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 201) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Bad Request.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 404) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Not found.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 423) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Locked.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new EntitlementManagementException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (getBlockedUserPolicyAssignments) get a list of blocked users + /// + /// + /// Get a list of actual set assignments of the blocked user policy.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle. + ///
+ ///
**Provider**:</br> + ///
The returned list shall contain only all assignments of the blocked user policy.</br> + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not oid_versicherter_ or _oid_ombudsstelle_| 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// user agent information + /// Ok. Returns a list of policy assignments + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetBlockedUserPolicyAssignmentsAsync(string x_insurantid, string x_useragent) + { + return GetBlockedUserPolicyAssignmentsAsync(x_insurantid, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getBlockedUserPolicyAssignments) get a list of blocked users + /// + /// + /// Get a list of actual set assignments of the blocked user policy.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle. + ///
+ ///
**Provider**:</br> + ///
The returned list shall contain only all assignments of the blocked user policy.</br> + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not oid_versicherter_ or _oid_ombudsstelle_| 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// user agent information + /// Ok. Returns a list of policy assignments + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetBlockedUserPolicyAssignmentsAsync(string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/basic/api/v1/blockedusers" + urlBuilder_.Append("epa/basic/api/v1/blockedusers"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Bad Request.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 404) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Not found.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new EntitlementManagementException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (setBlockedUserPolicyAssignment) add a user to the blocked user policy + /// + /// + /// Set a new assignment for the blocked user policy.</br> + ///
The user addressed by the policy assignment can not be entitled by any means, a possibly existing + ///
entitlement is lost.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle. + ///
+ ///
**Client**:</br> + ///
A client shall set assignments for users of the allowed roles for + ///
user blocking only.</br> + ///
+ ///
**Provider**:</br> + ///
A valid new assignment shall be added to the blocked user policy. + ///
+ ///
Each new valid assigment shall be extended by a timestamp (_at_ = current date and time) + ///
by the server. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 201 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ or _oid_ombudsstelle_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| The assignment parameter _oid_ is not in the list of allowd oids | 409 | requestMismatch || + ///
| The assignment does yet exist (same _actorId_) | 409 | requestMismatch | avoid duplicates | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The policy assignment is extended with the timestamp and stored in SecureDataStorage || + ///
| An existing entitlement for the addressed user of the assignment is deleted || + ///
| An eMail is sent to the insurant, including information about the blocked user policy change| if eMail address is available | + ///
| A log-entry for the operation exists | all operation results | + ///
+ /// Health Record Identifier. + /// user agent information + /// Created + /// A server side error occurred. + public virtual System.Threading.Tasks.Task SetBlockedUserPolicyAssignmentAsync(BlockedUserPolicyAssignmentType body, string x_insurantid, string x_useragent) + { + return SetBlockedUserPolicyAssignmentAsync(body, x_insurantid, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (setBlockedUserPolicyAssignment) add a user to the blocked user policy + /// + /// + /// Set a new assignment for the blocked user policy.</br> + ///
The user addressed by the policy assignment can not be entitled by any means, a possibly existing + ///
entitlement is lost.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle. + ///
+ ///
**Client**:</br> + ///
A client shall set assignments for users of the allowed roles for + ///
user blocking only.</br> + ///
+ ///
**Provider**:</br> + ///
A valid new assignment shall be added to the blocked user policy. + ///
+ ///
Each new valid assigment shall be extended by a timestamp (_at_ = current date and time) + ///
by the server. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 201 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ or _oid_ombudsstelle_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| The assignment parameter _oid_ is not in the list of allowd oids | 409 | requestMismatch || + ///
| The assignment does yet exist (same _actorId_) | 409 | requestMismatch | avoid duplicates | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The policy assignment is extended with the timestamp and stored in SecureDataStorage || + ///
| An existing entitlement for the addressed user of the assignment is deleted || + ///
| An eMail is sent to the insurant, including information about the blocked user policy change| if eMail address is available | + ///
| A log-entry for the operation exists | all operation results | + ///
+ /// Health Record Identifier. + /// user agent information + /// Created + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task SetBlockedUserPolicyAssignmentAsync(BlockedUserPolicyAssignmentType body, string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + if (body == null) + throw new System.ArgumentNullException("body"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + var json_ = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(body, JsonSerializerSettings); + var content_ = new System.Net.Http.ByteArrayContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/basic/api/v1/blockedusers" + urlBuilder_.Append("epa/basic/api/v1/blockedusers"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 201) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Bad Request.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 404) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Not found.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new EntitlementManagementException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (getBlockedUserPolicyAssignment) get a particular blocked user + /// + /// + /// Get one particular assignment of the blocked user policy.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle . + ///
+ ///
**Client**:</br> + ///
no recommendations. + ///
+ ///
**Provider**:</br> + ///
The addressed assigment shall be returned. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not oid_versicherter_ or _oid_ombudsstelle_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Resource for _telematikid_ does not exist | 404 | noResource || + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// TelematikID + /// user agent information + /// Ok. + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetBlockedUserPolicyAssignmentAsync(string x_insurantid, string telematikid, string x_useragent) + { + return GetBlockedUserPolicyAssignmentAsync(x_insurantid, telematikid, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (getBlockedUserPolicyAssignment) get a particular blocked user + /// + /// + /// Get one particular assignment of the blocked user policy.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle . + ///
+ ///
**Client**:</br> + ///
no recommendations. + ///
+ ///
**Provider**:</br> + ///
The addressed assigment shall be returned. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 200 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not oid_versicherter_ or _oid_ombudsstelle_ | 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Resource for _telematikid_ does not exist | 404 | noResource || + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| none || + ///
+ /// Health Record Identifier. + /// TelematikID + /// user agent information + /// Ok. + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetBlockedUserPolicyAssignmentAsync(string x_insurantid, string telematikid, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + if (telematikid == null) + throw new System.ArgumentNullException("telematikid"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/basic/api/v1/blockedusers/{telematikid}" + urlBuilder_.Append("epa/basic/api/v1/blockedusers/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(telematikid, System.Globalization.CultureInfo.InvariantCulture))); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Bad Request.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 404) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Not found.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new EntitlementManagementException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// (deleteBlockedUserPolicyAssignment) remove a user from the blocked user policy + /// + /// + /// Delete one existing assignment of the blocked user policy.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle. + ///
+ ///
**Client**:</br> + ///
no recommendations. + ///
+ ///
**Provider**:</br> + ///
The addressed assigment shall be removed from the policy. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 204 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ or _oid_ombudsstelle_| 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Assignment (_telematikid_) does not exist | 404 | noResource || + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The addressed assignment is removed from the associated policy || + ///
| An eMail is sent to the insurant, including information about the blocked user policy change| if eMail address is available | + ///
| A log-entry for the operation exists | all operation results | + ///
+ /// Health Record Identifier. + /// TelematikID + /// user agent information + /// OK. Assignment deleted + /// A server side error occurred. + public virtual System.Threading.Tasks.Task DeleteBlockedUserPolicyAssignmentAsync(string x_insurantid, string telematikid, string x_useragent) + { + return DeleteBlockedUserPolicyAssignmentAsync(x_insurantid, telematikid, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// (deleteBlockedUserPolicyAssignment) remove a user from the blocked user policy + /// + /// + /// Delete one existing assignment of the blocked user policy.</br> + ///
This operation is limited to entitled users of role oid_versicherter and oid_ombudsstelle. + ///
+ ///
**Client**:</br> + ///
no recommendations. + ///
+ ///
**Provider**:</br> + ///
The addressed assigment shall be removed from the policy. + ///
+ ///
| Conditions | Status code | Error code | Remarks | + ///
|------------|-------------|------------|---------| + ///
| Successful operation | 204 ||| + ///
| Request does not match schema | 400 | malformedRequest || + ///
| Requestor not authorized | 403 | invalAuth | no user session with valid ID-Token available | + ///
| Device registration does not exist | 403 | unregisteredDevice | if requestor role is oid_versicherter only | + ///
| Requestor has no valid entitlement | 403 | notEntitled || + ///
| Requestor role is not _oid_versicherter_ or _oid_ombudsstelle_| 403 | invalidOid || + ///
| Health record does not exist | 404 | noHealthRecord | _insurantid_ unknown | + ///
| Assignment (_telematikid_) does not exist | 404 | noResource || + ///
| Health record is not in state ACTIVATED | 409 | statusMismatch | (see 'Retry interval') | + ///
| Any other error | 500 | internalError | (see 'Retry interval') | + ///
+ ///
</br> + ///
| Postconditions | Remarks | + ///
|---------------------------------------|---------| + ///
| The addressed assignment is removed from the associated policy || + ///
| An eMail is sent to the insurant, including information about the blocked user policy change| if eMail address is available | + ///
| A log-entry for the operation exists | all operation results | + ///
+ /// Health Record Identifier. + /// TelematikID + /// user agent information + /// OK. Assignment deleted + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task DeleteBlockedUserPolicyAssignmentAsync(string x_insurantid, string telematikid, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + if (telematikid == null) + throw new System.ArgumentNullException("telematikid"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("DELETE"); + + var urlBuilder_ = new System.Text.StringBuilder(); + + // Operation Path: "epa/basic/api/v1/blockedusers/{telematikid}" + urlBuilder_.Append("epa/basic/api/v1/blockedusers/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(telematikid, System.Globalization.CultureInfo.InvariantCulture))); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 204) + { + return; + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Bad Request.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Forbidden.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 404) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Not found.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 409) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Conflict.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new EntitlementManagementException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new EntitlementManagementException("Internal Server Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new EntitlementManagementException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + protected struct ObjectResponseResult + { + public ObjectResponseResult(T responseObject, string responseText) + { + this.Object = responseObject; + this.Text = responseText; + } + + public T Object { get; } + + public string Text { get; } + } + + public bool ReadResponseAsString { get; set; } + + protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken) + { + if (response == null || response.Content == null) + { + return new ObjectResponseResult(default(T), string.Empty); + } + + if (ReadResponseAsString) + { + var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + var typedBody = System.Text.Json.JsonSerializer.Deserialize(responseText, JsonSerializerSettings); + return new ObjectResponseResult(typedBody, responseText); + } + catch (System.Text.Json.JsonException exception) + { + var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; + throw new EntitlementManagementException(message, (int)response.StatusCode, responseText, headers, exception); + } + } + else + { + try + { + using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) + { + var typedBody = await System.Text.Json.JsonSerializer.DeserializeAsync(responseStream, JsonSerializerSettings, cancellationToken).ConfigureAwait(false); + return new ObjectResponseResult(typedBody, string.Empty); + } + } + catch (System.Text.Json.JsonException exception) + { + var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; + throw new EntitlementManagementException(message, (int)response.StatusCode, string.Empty, headers, exception); + } + } + } + + private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) + { + if (value == null) + { + return ""; + } + + if (value is System.Enum) + { + var name = System.Enum.GetName(value.GetType(), value); + if (name != null) + { + var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name); + if (field != null) + { + var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) + as System.Runtime.Serialization.EnumMemberAttribute; + if (attribute != null) + { + return attribute.Value != null ? attribute.Value : name; + } + } + + var converted = System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo)); + return converted == null ? string.Empty : converted; + } + } + else if (value is bool) + { + return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant(); + } + else if (value is byte[]) + { + return System.Convert.ToBase64String((byte[]) value); + } + else if (value is string[]) + { + return string.Join(",", (string[])value); + } + else if (value.GetType().IsArray) + { + var valueArray = (System.Array)value; + var valueTextArray = new string[valueArray.Length]; + for (var i = 0; i < valueArray.Length; i++) + { + valueTextArray[i] = ConvertToString(valueArray.GetValue(i), cultureInfo); + } + return string.Join(",", valueTextArray); + } + + var result = System.Convert.ToString(value, cultureInfo); + return result == null ? "" : result; + } + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class ActorIdType + { + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// "A JSON Web Token (JWT) with following format build according to RFC-7515:</br> + ///
base64url (protected_header) + '.' + base64url (payload) + '.' + base64url (signature)"</br> + ///
- Content for ePA-FdV originated entitlements:</br> + ///
- protected_header contains: + ///
- "typ": "JWT" + ///
- "alg": "ES256" + ///
- "x5c": signature certificate (C.CH.SIG) + ///
- payload claims: + ///
- "iat": issued at timestamp + ///
- "exp": expiry timestamp (always iat + 20min) + ///
- "insurantId": the health record identifier this entitlement is assoctiated to + ///
- "actorId": Telematik-Id or KVNR + ///
- "oid": value of professionOID + ///
- "displayName": name according to actorId + ///
- "validTo": Expiry date-time of entitlement in format according to rfc3339 + ///
- signature contains token signature + ///
- Content for PS originated entitlements:</br> + ///
- protected_header contains: + ///
- "typ": "JWT" + ///
- "alg": "ES256" or "PS256" + ///
- "x5c": signature certificate (C.HCI.AUT from smc-b of requestor) + ///
- payload claims: + ///
- "iat": issued at timestamp + ///
- "exp": expiry timestamp (always iat + 20min) + ///
- "auditEvidence": proof-of-audit received from VSDM Service ('Prüfziffer des VSDM Prüfungsnachweises') + ///
- "hcv": optional if _enforce_hcv_check_ == false; hash check value generated by PS according to A_27352-* + ///
- signature contains token signature + ///
+ ///
+ [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class EntitlementRequestType + { + + [System.Text.Json.Serialization.JsonPropertyName("jwt")] + public string Jwt { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class EntitlementRequestRepType : EntitlementRequestType + { + + [System.Text.Json.Serialization.JsonPropertyName("email")] + public string Email { get; set; } + + } + + /// + /// Properties of one specific entitlement + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class EntitlementClaimsResponseType + { + + [System.Text.Json.Serialization.JsonPropertyName("actorId")] + public string ActorId { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("oid")] + public string Oid { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("displayName")] + public string DisplayName { get; set; } + + /// + /// End of validity + /// + + [System.Text.Json.Serialization.JsonPropertyName("validTo")] + public System.DateTime ValidTo { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("issued")] + public Issued Issued { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// validTo element of one specific entitlement + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class ValidToResponseType + { + /// + /// End of validity + /// + + [System.Text.Json.Serialization.JsonPropertyName("validTo")] + public System.DateTime ValidTo { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Properties of one specific user + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class BlockedUserPolicyAssignmentType + { + + [System.Text.Json.Serialization.JsonPropertyName("actorId")] + public string ActorId { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("oid")] + public string Oid { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("displayName")] + public string DisplayName { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class BlockedUserPolicyAssignmentResponseType : BlockedUserPolicyAssignmentType + { + /// + /// Creation timestamp + /// + + [System.Text.Json.Serialization.JsonPropertyName("at")] + public System.DateTime At { get; set; } + + } + + /// + /// Error object with additional information about the occurred error + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class ErrorType + { + /// + /// Error condition specifier + /// + + [System.Text.Json.Serialization.JsonPropertyName("errorCode")] + public string ErrorCode { get; set; } + + /// + /// Additional details regarding the error condition (if applicable) + /// + + [System.Text.Json.Serialization.JsonPropertyName("errorDetail")] + public string ErrorDetail { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body + { + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response + { + + [System.Text.Json.Serialization.JsonPropertyName("data")] + public System.Collections.Generic.ICollection Data { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response2 + { + + [System.Text.Json.Serialization.JsonPropertyName("data")] + public System.Collections.Generic.ICollection Data { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Issued + { + /// + /// Creation time timestamp + /// + + [System.Text.Json.Serialization.JsonPropertyName("at")] + public System.DateTime At { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("actorId")] + public string ActorId { get; set; } + + [System.Text.Json.Serialization.JsonPropertyName("displayName")] + public string DisplayName { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [System.Text.Json.Serialization.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + + + [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class EntitlementManagementException : System.Exception + { + public int StatusCode { get; private set; } + + public string Response { get; private set; } + + public System.Collections.Generic.IReadOnlyDictionary> Headers { get; private set; } + + public EntitlementManagementException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Exception innerException) + : base(message + "\n\nStatus: " + statusCode + "\nResponse: \n" + ((response == null) ? "(null)" : response.Substring(0, response.Length >= 512 ? 512 : response.Length)), innerException) + { + StatusCode = statusCode; + Response = response; + Headers = headers; + } + + public override string ToString() + { + return string.Format("HTTP Response: \n\n{0}\n\n{1}", Response, base.ToString()); + } + } + + [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class EntitlementManagementException : EntitlementManagementException + { + public TResult Result { get; private set; } + + public EntitlementManagementException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, TResult result, System.Exception innerException) + : base(message, statusCode, response, headers, innerException) + { + Result = result; + } + } + +} + +#pragma warning restore 108 +#pragma warning restore 114 +#pragma warning restore 472 +#pragma warning restore 612 +#pragma warning restore 1573 +#pragma warning restore 1591 +#pragma warning restore 8073 +#pragma warning restore 3016 +#pragma warning restore 8600 +#pragma warning restore 8602 +#pragma warning restore 8603 +#pragma warning restore 8604 +#pragma warning restore 8625 \ No newline at end of file diff --git a/lib-vau-csharp-test/EpaApiClients/EntitlementManagement/nswag.json b/lib-vau-csharp-test/EpaApiClients/EntitlementManagement/nswag.json new file mode 100644 index 0000000..3d9d65f --- /dev/null +++ b/lib-vau-csharp-test/EpaApiClients/EntitlementManagement/nswag.json @@ -0,0 +1,57 @@ +{ + "runtime": "net80", + "documentGenerator": { + "fromDocument": { + "url": "https://raw.githubusercontent.com/gematik/ePA-Basic/refs/heads/ePA-3.0.5/src/openapi/I_Entitlement_Management.yaml", + "newLineBehavior": "Auto" + } + }, + "codeGenerators": { + "openApiToCSharpClient": { + "generateClientClasses": true, + "generateDtoTypes": true, + "injectHttpClient": true, + "disposeHttpClient": false, + "generateExceptionClasses": true, + "exceptionClass": "EntitlementManagementException", + "wrapDtoExceptions": true, + "useHttpClientCreationMethod": false, + "httpClientType": "System.Net.Http.HttpClient", + "useHttpRequestMessageCreationMethod": false, + "useBaseUrl": false, + "generateBaseUrlProperty": false, + "generateSyncMethods": false, + "exposeJsonSerializerSettings": false, + "generateClientInterfaces": true, + "clientClassAccessModifier": "public", + "typeAccessModifier": "public", + "generateContractsOutput": false, + "parameterDateTimeFormat": "s", + "generateUpdateJsonSerializerSettingsMethod": true, + "serializeTypeInformation": false, + "queryNullValue": "", + "className": "EntitlementManagementClient", + "operationGenerationMode": "MultipleClientsFromOperationId", + "generateOptionalParameters": false, + "generateJsonMethods": false, + "wrapResponses": false, + "generateResponseClasses": true, + "responseClass": "EntitlementManagementResponse", + "requiredPropertiesMustBeDefined": true, + "dateType": "System.DateTime", + "dateTimeType": "System.DateTime", + "timeType": "System.TimeSpan", + "timeSpanType": "System.TimeSpan", + "generateDefaultValues": true, + "generateDataAnnotations": false, + "excludedTypeNames": [], + "handleReferences": false, + "namespace": "lib_vau_csharp_test.EpaApiClients.EntitlementManagement", + "generateImmutableArrayProperties": false, + "generateImmutableDictionaryProperties": false, + "output": "EntitlementManagementClient.cs", + "jsonLibrary": "SystemTextJson", + "jsonSerializerSettingsTransformationMethod": null + } + } +} diff --git a/lib-vau-csharp-test/EpaDeploymentTest.cs b/lib-vau-csharp-test/EpaDeploymentTest.cs index e10a80b..2f1078e 100644 --- a/lib-vau-csharp-test/EpaDeploymentTest.cs +++ b/lib-vau-csharp-test/EpaDeploymentTest.cs @@ -12,12 +12,11 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - * For additional notes and disclaimer from gematik and in case of changes by gematik find details in the "Readme" file. */ using lib_vau_csharp; using lib_vau_csharp.crypto; + using NUnit.Framework; using System; using System.Collections.Generic; @@ -26,19 +25,18 @@ using System.Text; using System.Threading.Tasks; +using lib_vau_csharp.util; + namespace lib_vau_csharp_test { + [Explicit] public class EpaDeploymentTest { - private static string epaUrl = "http://localhost:443/"; private static string HEADER_VAU_CID = "VAU-CID"; private static string HEADER_VAU = "VAU"; private static HttpClient Client = new HttpClient(); private VauClientStateMachine vauClientStateMachine; - private static String GET_VAUSTATUS = "GET /VAU-Status HTTP/1.1\r\nAccept: application / json\r\n\r\n"; - private static MediaTypeWithQualityHeaderValue cborType = new MediaTypeWithQualityHeaderValue("application/cbor"); - private static MediaTypeWithQualityHeaderValue octetType = new MediaTypeWithQualityHeaderValue("application/octet-stream"); private String epaCID = ""; [SetUp] @@ -48,7 +46,7 @@ public void Setup() Kem.initializeKem(Kem.KemEngines.AesEngine, Kem.KEYSIZE_256); } - // [Test] + [Test] public async Task TestEpaDeployment() { await DoHandshake(); @@ -58,36 +56,32 @@ public async Task TestEpaDeployment() private async Task DoHandshake() { var message1Encoded = vauClientStateMachine.generateMessage1(); - byte[] message2Encoded = await sendStreamAsPOST(epaUrl + HEADER_VAU, message1Encoded, cborType); + byte[] message2Encoded = await SendStreamAsPost(Constants.EpaDeploymentUrl + HEADER_VAU, message1Encoded, MediaTypeHeader.Cbor); byte[] message3Encoded = vauClientStateMachine.receiveMessage2(message2Encoded); - byte[] message4Encoded = await sendStreamAsPOST(epaUrl + epaCID, message3Encoded, cborType); - vauClientStateMachine.receiveMessage4(message4Encoded); + byte[] message4Encoded = await SendStreamAsPost(Constants.EpaDeploymentUrl + epaCID, message3Encoded, MediaTypeHeader.Cbor); + vauClientStateMachine.receiveMessage4(message4Encoded); } - private async Task DoMessageTest() + private async Task DoMessageTest() { - byte[] encrypted = vauClientStateMachine.EncryptVauMessage(Encoding.ASCII.GetBytes(GET_VAUSTATUS)); - byte[] message5Encoded = await sendStreamAsPOST(epaUrl + epaCID, encrypted, octetType); + byte[] encrypted = vauClientStateMachine.EncryptVauMessage(Encoding.ASCII.GetBytes(VauRequest.Status)); + byte[] message5Encoded = await SendStreamAsPost(Constants.EpaDeploymentUrl + epaCID, encrypted, MediaTypeHeader.Octet); byte[] pDecodedMessage = vauClientStateMachine.DecryptVauMessage(message5Encoded); Console.WriteLine($"Client received VAU Status: \r\n{Encoding.UTF8.GetString(pDecodedMessage)}"); } - private void handleCID(HttpResponseMessage response) + private void HandleCid(HttpResponseMessage response) { IEnumerable cidHeader = new List(); if (response?.Headers?.TryGetValues(HEADER_VAU_CID, out cidHeader) ?? false) { string[] vecStr = (string[])cidHeader; - #if (NET8_0_OR_GREATER || NETSTANDARD2_0_OR_GREATER) - epaCID = vecStr[0].StartsWith('/') ? vecStr[0].Remove(0, 1) : vecStr[0]; - #else epaCID = vecStr[0].StartsWith("/") ? vecStr[0].Remove(0, 1) : vecStr[0]; - #endif } } - private async Task sendStreamAsPOST(String url, byte[] messageEncoded, MediaTypeWithQualityHeaderValue mediaType) + private async Task SendStreamAsPost(String url, byte[] messageEncoded, MediaTypeWithQualityHeaderValue mediaType) { var content = new ByteArrayContent(messageEncoded); content.Headers.ContentType = mediaType; @@ -97,9 +91,9 @@ private async Task sendStreamAsPOST(String url, byte[] messageEncoded, M { throw new Exception(response.ReasonPhrase); } - handleCID(response); + HandleCid(response); byte[] bytes = await response.Content.ReadAsByteArrayAsync(); return bytes; } } -} +} \ No newline at end of file diff --git a/lib-vau-csharp-test/HandShakeTests.cs b/lib-vau-csharp-test/HandShakeTests.cs index 61e40a3..2832ffe 100644 --- a/lib-vau-csharp-test/HandShakeTests.cs +++ b/lib-vau-csharp-test/HandShakeTests.cs @@ -12,18 +12,16 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - * For additional notes and disclaimer from gematik and in case of changes by gematik find details in the "Readme" file. */ using lib_vau_csharp; using lib_vau_csharp.data; using NUnit.Framework; -using NUnit.Framework.Legacy; using System; -using System.Text; +using System.Net.Http; +using System.Threading.Tasks; namespace lib_vau_csharp_test { @@ -52,11 +50,10 @@ public void Setup() vauServer = new VauServer(url, signedPublicVauKeys, Constants.Keys.EccKyberKeyPair); _ = vauServer.StartAsync(); - } [TearDown] - public static void ShutdownServer() + public void ShutdownServer() { if (vauServer != null) { @@ -65,14 +62,15 @@ public static void ShutdownServer() } [Test] - public static void TestSendingMessagesThroughChannel() + public async Task TestSendingMessagesThroughChannel() { - vauClient = new VauClient(); - bool handshakeSucceeded = vauClient.DoHandshake(url).Result; + var httpClient = new HttpClient { BaseAddress = new Uri(url) }; + var vauClient = new VauClient(httpClient); + await vauClient.DoHandshake(); - ClassicAssert.IsTrue(handshakeSucceeded); - bool messagesExchanged = vauClient.SendMessage(url, Encoding.UTF8.GetBytes("Hello World!")).Result; - ClassicAssert.IsTrue(messagesExchanged); + var replyMessage = await vauClient.SendMessage("Hello World!"u8.ToArray()); + Assert.That(replyMessage.Content, Is.Not.Null); + Console.WriteLine(await replyMessage.Content.ReadAsStringAsync()); } } } \ No newline at end of file diff --git a/lib-vau-csharp-test/VauClientTest.cs b/lib-vau-csharp-test/VauClientTest.cs new file mode 100644 index 0000000..96820d5 --- /dev/null +++ b/lib-vau-csharp-test/VauClientTest.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections; +using System.Net.Http; +using System.Threading.Tasks; + +using lib_vau_csharp; +using lib_vau_csharp_test.EpaApiClients.Auth; +using lib_vau_csharp_test.EpaApiClients.EntitlementManagement; + +using Microsoft.Extensions.DependencyInjection; + +using NUnit.Framework; + +using ErrorType = lib_vau_csharp_test.EpaApiClients.EntitlementManagement.ErrorType; + +namespace lib_vau_csharp_test +{ + [Explicit("Needs running epa deployment.")] + public class VauClientTest + { + private VauClient vauClient; + + [SetUp] + public void Setup() + { + var vauClientHttpClient = new HttpClient { BaseAddress = Constants.EpaDeploymentUrl }; + vauClient = new VauClient(vauClientHttpClient); + } + + [Test] + public async Task ConnectionIdIsSetAfterHandshake() + { + await vauClient.DoHandshake(); + + Assert.That(vauClient.ConnectionId, Is.Not.Null); + } + + [Test] + public async Task CanGetStatus() + { + await vauClient.DoHandshake(); + var vauStatus = await vauClient.GetStatus(); + + Assert.That(vauStatus, Is.Not.Null); + } + + [Test] + public async Task VauHttpClientHandlerDoesDecryptionAndEncryptionWhenCallingAnApiMethod() + { + var vauHttpClientHandler = new VauHttpClientHandler(new ReturnInstanceVauClientProvider(vauClient, true)); + var httpClient = new HttpClient(vauHttpClientHandler) { BaseAddress = Constants.EpaDeploymentUrl }; + + var authorizationServiceClient = new AuthorizationServiceClient(httpClient); + var response = await authorizationServiceClient.GetNonceAsync("Test/1.0"); + + Console.WriteLine(response.Nonce); + } + + [Test] + public void UsageWitIHttpClientFactory() + { + var services = new ServiceCollection(); + services.AddTransient(); + services.AddSingleton(); + services.AddHttpClient("VAU").ConfigurePrimaryHttpMessageHandler(); + services.AddTransient(sp => + { + var httpClientFactory = sp.GetService(); + var httpClient = httpClientFactory.CreateClient("VAU"); + httpClient.BaseAddress = Constants.EpaDeploymentUrl; + return ActivatorUtilities.CreateInstance(sp, httpClient); + }); + + var sp = services.BuildServiceProvider(); + + var entitlementManagementClient = sp.GetService(); + var request = new EntitlementRequestType { Jwt = "An invalid JWT" }; + Assert.ThrowsAsync>(() => entitlementManagementClient.SetEntitlementPsAsync(request, "Z123456783", "Test/1.0")); + } + + [Test] + [TestCaseSource(nameof(ThrowingMethods))] + public void ThrowsInvalidOperationExceptionIfHandshakeWasNotPerformed(Func method, string methodName) + { + Assert.ThrowsAsync(() => method(), $"Expected method {methodName} to throw an InvalidOperationException."); + } + + private static IEnumerable ThrowingMethods() + { + var client = new VauClient(new HttpClient()); + + yield return new TestCaseData(() => client.DecryptResponse(new HttpResponseMessage()), nameof(client.DecryptResponse)); + yield return new TestCaseData(() => client.EncryptRequest(new HttpRequestMessage { RequestUri = new Uri("https://example.com") }), nameof(client.EncryptRequest)); + yield return new TestCaseData(() => client.GetStatus(), nameof(client.GetStatus)); + yield return new TestCaseData(() => client.SendMessage([]), nameof(client.SendMessage)); + } + + private class ReturnInstanceVauClientProvider(VauClient vauClient, bool doHandshake = false) : IVauClientProvider + { + public async Task GetVauClient(Uri uri) + { + if (doHandshake) + await vauClient.DoHandshake(); + + return vauClient; + } + } + + private class VauClientProviderSingleInstance(IHttpClientFactory httpClientFactory) : IVauClientProvider + { + private VauClient vauClient; + + public async Task GetVauClient(Uri uri) + { + if (vauClient != null) + return vauClient; + + var httpClient = httpClientFactory.CreateClient(); + httpClient.BaseAddress = new Uri(uri.GetLeftPart(UriPartial.Authority)); //Extract record system url + + vauClient = new VauClient(httpClient); + await vauClient.DoHandshake(); + return vauClient; + } + } + } +} \ No newline at end of file diff --git a/lib-vau-csharp-test/lib-vau-csharp-test.csproj b/lib-vau-csharp-test/lib-vau-csharp-test.csproj index a386f43..de25cba 100644 --- a/lib-vau-csharp-test/lib-vau-csharp-test.csproj +++ b/lib-vau-csharp-test/lib-vau-csharp-test.csproj @@ -3,7 +3,7 @@ net48;net80 false - 10.0 + latest @@ -33,6 +33,12 @@ + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/lib-vau-csharp/IVauClientProvider.cs b/lib-vau-csharp/IVauClientProvider.cs new file mode 100644 index 0000000..c35e942 --- /dev/null +++ b/lib-vau-csharp/IVauClientProvider.cs @@ -0,0 +1,34 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Threading.Tasks; + +namespace lib_vau_csharp +{ + /// + /// Implement this interface to provide with an instance of . + /// + public interface IVauClientProvider + { + /// + /// Gets an instance of for the given that is immediately usable i.e. is connected to the VAU. + /// May return null in case requests should not use the VAU. + /// + /// The full uri for the request. + /// An instance of or null + /// + Task GetVauClient(Uri uri); + } +} \ No newline at end of file diff --git a/lib-vau-csharp/VauClient.cs b/lib-vau-csharp/VauClient.cs index 5ab66d7..56521a3 100644 --- a/lib-vau-csharp/VauClient.cs +++ b/lib-vau-csharp/VauClient.cs @@ -12,87 +12,191 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - * For additional notes and disclaimer from gematik and in case of changes by gematik find details in the "Readme" file. */ using lib_vau_csharp.data; +using lib_vau_csharp.util; using lib_vau_csharp.exceptions; + using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading.Tasks; - namespace lib_vau_csharp { + [DebuggerDisplay("ConnectionId: {ConnectionId}")] public class VauClient { - readonly VauClientStateMachine vauClientStateMachine; - ConnectionId Cid; + private static readonly JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.KebabCaseUpper }; + + private readonly HttpClient httpClient; + private readonly VauClientStateMachine vauClientStateMachine; + + public AbstractVauStateMachine VauStateMachine => vauClientStateMachine; + + public ConnectionId ConnectionId { get; private set; } - public VauClient() + /// + /// Create a new instance of the class. + /// + /// A that is configured to communicate with a record system, i.e. has the proper base address set. + /// + public VauClient(HttpClient httpClient) { + this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + vauClientStateMachine = new VauClientStateMachine(); } - public async Task DoHandshake(string baseUrl) + /// + /// Perform handshake with the VAU. + /// + /// + public async Task DoHandshake() { - using (var client = new HttpClient()) - { - byte[] message3Encoded = await DoHandShakeStage1(baseUrl, client); - return await DoHandShakeStage2(baseUrl, client, message3Encoded); - } + if (ConnectionId != null) + throw new InvalidOperationException("Connection has already been established."); + + byte[] message3Encoded = await DoHandShakeStage1(); + await DoHandShakeStage2(message3Encoded); + } + + /// + /// Gets the VAU status for the current instance. + /// + /// An instance of . + /// Thrown in case the current instance is not connected to a VAU. + /// + public async Task GetStatus() + { + EnsureConnected(); + + using var response = await SendMessage(Encoding.UTF8.GetBytes(VauRequest.Status)).ConfigureAwait(false); + using var stream = await response.EnsureSuccessStatusCode().Content.ReadAsStreamAsync(); + return JsonSerializer.Deserialize(stream, JsonSerializerOptions); + } + + public async Task SendMessage(byte[] message) + { + if (message == null) + throw new ArgumentNullException(nameof(message)); + + EnsureConnected(); + + byte[] cborEncodedMessage = vauClientStateMachine.EncryptVauMessage(message); + using var content = new ByteArrayContent(cborEncodedMessage); + content.Headers.ContentType = MediaTypeHeader.Octet; + var response = await httpClient.PostAsync(ConnectionId.Cid, content).ConfigureAwait(false); + byte[] serverMessageEncoded = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); + string responseMessage = Encoding.UTF8.GetString(vauClientStateMachine.DecryptVauMessage(serverMessageEncoded)); + + VauResponse.Parse(responseMessage, response); + return response; } - public async Task DoHandShakeStage1(string baseUrl, HttpClient client) + /// + /// Encrypts the given to send to the VAU. + /// + /// The request to encrypt. + /// + /// Thrown in case the current instance is not connected to a VAU. + public async Task EncryptRequest(HttpRequestMessage httpRequest) => await EncryptRequest(httpRequest, httpRequest.RequestUri).ConfigureAwait(false); + + /// + /// Encrypts the given to send to the VAU using the provided . + /// + /// The request to encrypt. + /// The uri to send the to. + /// + /// Thrown in case the current instance is not connected to a VAU. + public async Task EncryptRequest(HttpRequestMessage httpRequest, Uri uri) + { + if (httpRequest == null) + throw new ArgumentNullException(nameof(httpRequest)); + if (uri == null) + throw new ArgumentNullException(nameof(uri)); + + EnsureConnected(); + + string request = await VauRequest.Create(httpRequest, uri); + + byte[] cborEncodedMessage = vauClientStateMachine.EncryptVauMessage(Encoding.UTF8.GetBytes(request)); + + var content = new ByteArrayContent(cborEncodedMessage); + content.Headers.ContentType = MediaTypeHeader.Octet; + + httpRequest.Headers.Accept.Add(MediaTypeHeader.Octet); + httpRequest.Content = content; + httpRequest.Method = HttpMethod.Post; + } + + /// + /// Decrypts the given received from the VAU. + /// + /// + /// + /// Thrown in case the current instance is not connected to a VAU. + public async Task DecryptResponse(HttpResponseMessage response) + { + if (response == null) + throw new ArgumentNullException(nameof(response)); + + EnsureConnected(); + + byte[] encryptedResponse = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); + + string decryptedResponse = Encoding.UTF8.GetString(vauClientStateMachine.DecryptVauMessage(encryptedResponse)); + + VauResponse.Parse(decryptedResponse, response); + } + + private async Task DoHandShakeStage1() { var message1Encoded = vauClientStateMachine.generateMessage1(); var content = new ByteArrayContent(message1Encoded); - content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/cbor"); - var response = await client.PostAsync(baseUrl + "VAU", content); + content.Headers.ContentType = MediaTypeHeader.Cbor; + + using var response = await httpClient.PostAsync("VAU", content).ConfigureAwait(false); - var message2Encoded = await response.Content.ReadAsByteArrayAsync(); + var message2Encoded = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); - IEnumerable cidArray; - if (!response.Headers.TryGetValues("VAU-CID", out cidArray)) + if (!response.Headers.TryGetValues("VAU-CID", out IEnumerable cidArray)) { throw new VauProxyException("Failed to retrieve CID from Header."); } var cid = cidArray.First(); - Cid = new ConnectionId(cid); + ConnectionId = new ConnectionId(cid); return vauClientStateMachine.receiveMessage2(message2Encoded); } - public async Task DoHandShakeStage2(string baseUrl, HttpClient client, byte[] message3Encoded) + private async Task DoHandShakeStage2(byte[] message3Encoded) { var content2 = new ByteArrayContent(message3Encoded); - content2.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/cbor"); + content2.Headers.ContentType = MediaTypeHeader.Cbor; - var response2 = await client.PostAsync(baseUrl + Cid.Cid, content2); + using var response2 = await httpClient.PostAsync(ConnectionId.Cid, content2).ConfigureAwait(false); - byte[] message4Encoded = await response2.Content.ReadAsByteArrayAsync(); + byte[] message4Encoded = await response2.Content.ReadAsByteArrayAsync().ConfigureAwait(false); vauClientStateMachine.receiveMessage4(message4Encoded); - return true; } - public async Task SendMessage(string baseUrl, byte[] message) + private void EnsureConnected() { - using (var client = new HttpClient()) - { - byte[] cborEncodedMessage = vauClientStateMachine.EncryptVauMessage(message); - var content = new ByteArrayContent(cborEncodedMessage); - content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); - var response = await client.PostAsync(baseUrl + Cid.Cid, content); - byte[] serverMessageEncoded = await response.Content.ReadAsByteArrayAsync(); - string serverMessage = Encoding.UTF8.GetString(vauClientStateMachine.DecryptVauMessage(serverMessageEncoded)); - Console.WriteLine($"Client received ServerMessage: {serverMessage}"); - return response.StatusCode == System.Net.HttpStatusCode.OK; - } + if (ConnectionId == null) + throw new InvalidOperationException($"No connection has been established, call {nameof(DoHandshake)} first."); } } -} + + public record VauStatus(string VauType, string VauVersion, string UserAuthentication, [property: JsonPropertyName("KeyID")] string KeyId, string ConnectionStart) + { + public bool IsTelematikIdAuthenticated(string telematikId) => UserAuthentication.Contains(telematikId); + } +} \ No newline at end of file diff --git a/lib-vau-csharp/VauHttpClientHandler.cs b/lib-vau-csharp/VauHttpClientHandler.cs new file mode 100644 index 0000000..f46d0c6 --- /dev/null +++ b/lib-vau-csharp/VauHttpClientHandler.cs @@ -0,0 +1,66 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +namespace lib_vau_csharp +{ + /// + /// An that transparently encrypts s send to a record system and subsequently + /// decrypts the . + /// + /// + /// Note that this handler sets property to false, so that calls to API methods like + /// SendAuthorizationRequestSC that return 302 don't automatically call the supplied location url. + /// Take this into account when configuring record system urls, as redirections from http to https won't work. + /// + public class VauHttpClientHandler : HttpClientHandler + { + private readonly IVauClientProvider vauClientProvider; + + /// + /// Creates a new instance of + /// + /// An implementation of that provides the handler with an instance of + /// that is used to encrypt requests and decrypts responses. + /// + /// + public VauHttpClientHandler(IVauClientProvider vauClientProvider) + { + this.vauClientProvider = vauClientProvider ?? throw new ArgumentNullException(nameof(vauClientProvider)); + + AllowAutoRedirect = false; + } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var vauClient = await vauClientProvider.GetVauClient(request.RequestUri).ConfigureAwait(false); + if (vauClient == null) + return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + + await vauClient.EncryptRequest(request).ConfigureAwait(false); + + request.RequestUri = new Uri(request.RequestUri!.GetLeftPart(UriPartial.Authority) + vauClient.ConnectionId.Cid); + + var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + + await vauClient.DecryptResponse(response).ConfigureAwait(false); + + return response; + } + } +} \ No newline at end of file diff --git a/lib-vau-csharp/VauRequest.cs b/lib-vau-csharp/VauRequest.cs new file mode 100644 index 0000000..1d6d677 --- /dev/null +++ b/lib-vau-csharp/VauRequest.cs @@ -0,0 +1,62 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; + +namespace lib_vau_csharp +{ + public class VauRequest + { + private const string CrLf = "\r\n"; + + public const string Status = "GET /VAU-Status HTTP/1.1\r\nAccept: application / json\r\n\r\n"; + + /// + /// Creates the inner http request to send to the VAU from the provided . + /// + /// + /// + /// + /// + public static async Task Create(HttpRequestMessage httpRequestMessage, Uri uri) + { + if (httpRequestMessage == null) + throw new ArgumentNullException(nameof(httpRequestMessage)); + if (uri == null) + throw new ArgumentNullException(nameof(uri)); + + string headers = String.Join(CrLf, httpRequestMessage.Headers.Select(x => $"{x.Key}: {x.Value.First()}")); + + string payload = null, contentHeaders = null; + if (httpRequestMessage.Content != null ) + { + payload = await httpRequestMessage.Content.ReadAsStringAsync().ConfigureAwait(false); + contentHeaders = String.Join(CrLf, httpRequestMessage.Content.Headers.Select(x => $"{x.Key}: {x.Value.First()}")); + } + + string request = $"{httpRequestMessage.Method.Method} {uri.LocalPath} HTTP/{httpRequestMessage.Version}{CrLf}" + + $"{headers}{CrLf}" + + $"{contentHeaders}" + + $"{CrLf}{CrLf}"; + + if (payload != null) + request += payload; + + return request; + } + } +} \ No newline at end of file diff --git a/lib-vau-csharp/VauResponse.cs b/lib-vau-csharp/VauResponse.cs new file mode 100644 index 0000000..8c83157 --- /dev/null +++ b/lib-vau-csharp/VauResponse.cs @@ -0,0 +1,87 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Linq; +using System.Net; +using System.Net.Http; + +using lib_vau_csharp.util; + +namespace lib_vau_csharp +{ + public class VauResponse + { + private const int StatusCodeIndex = 1; + private const int ReasonPhraseIndex = 2; + + private static readonly char[] HeaderSplit = [':']; + + /// + /// Parses the given into the given . + /// + /// + /// + /// + public static void Parse(string decryptedResponse, HttpResponseMessage httpResponseMessage) + { + if (decryptedResponse == null) + throw new ArgumentNullException(nameof(decryptedResponse)); + if (httpResponseMessage == null) + throw new ArgumentNullException(nameof(httpResponseMessage)); + + var lines = decryptedResponse.ReadLines().ToList(); + + int contentIndex = 0; + + for (int i = 0; i < lines.Count; i++) + { + string line = lines[i]; + if (i == 0) + { + if (line.StartsWith("HTTP")) + { + string[] status = lines[0].Split(' '); + if (Enum.TryParse(status[StatusCodeIndex], true, out HttpStatusCode statusCode)) + httpResponseMessage.StatusCode = statusCode; + + httpResponseMessage.ReasonPhrase = status[ReasonPhraseIndex]; + } + else + { + //Not sure if we can get here in a production env, the TestSendingMessagesThroughChannel test expects this work though + break; + } + } + + if (String.IsNullOrWhiteSpace(line)) + { + contentIndex = i + 1; + break; + } + + string[] headerNameValue = line.Split(HeaderSplit, 2); + string name = headerNameValue[0].Trim(); + + if (HttpResponseHeaderNames.All.Contains(name)) + { + string value = headerNameValue[1].Trim(); + httpResponseMessage.Headers.Add(name, value); + } + } + + httpResponseMessage.Content = contentIndex < lines.Count ? new StringContent(String.Join(String.Empty, lines.Skip(contentIndex))) : null; + } + } +} \ No newline at end of file diff --git a/lib-vau-csharp/lib-vau-csharp.csproj b/lib-vau-csharp/lib-vau-csharp.csproj index 2989075..1b71ac1 100644 --- a/lib-vau-csharp/lib-vau-csharp.csproj +++ b/lib-vau-csharp/lib-vau-csharp.csproj @@ -3,15 +3,21 @@ netstandard2.0;net80 lib_vau_csharp + latest + - + + + + + \ No newline at end of file diff --git a/lib-vau-csharp/util/Extensions.cs b/lib-vau-csharp/util/Extensions.cs new file mode 100644 index 0000000..82360b0 --- /dev/null +++ b/lib-vau-csharp/util/Extensions.cs @@ -0,0 +1,32 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.IO; + +namespace lib_vau_csharp.util +{ + internal static class Extensions + { + internal static IEnumerable ReadLines(this string text) + { + var reader = new StringReader(text ?? String.Empty); + while (reader.ReadLine() is { } line) + { + yield return line; + } + } + } +} \ No newline at end of file diff --git a/lib-vau-csharp/util/HttpResponseHeaderNames.cs b/lib-vau-csharp/util/HttpResponseHeaderNames.cs new file mode 100644 index 0000000..e6a17fd --- /dev/null +++ b/lib-vau-csharp/util/HttpResponseHeaderNames.cs @@ -0,0 +1,117 @@ +/* + * Source: https://stackoverflow.com/a/11037206 + * Licensed under CC BY-SA 3.0: https://creativecommons.org/licenses/by-sa/3.0/ + */ + +using System.Collections.Generic; +using System.Linq; + +namespace lib_vau_csharp.util +{ + /// + /// Contains the standard set of headers applicable to an HTTP response. + /// + internal static class HttpResponseHeaderNames + { + public static readonly HashSet All = new HashSet(typeof(HttpResponseHeaderNames).GetFields().Select(p => p.Name)); + + ///What partial content range types this server supports + public const string AcceptRanges = "Accept-Ranges"; + + ///The age the object has been in a proxy cache in seconds + public const string Age = "Age"; + + ///Valid actions for a specified resource. To be used for a 405 Method not allowed + public const string Allow = "Allow"; + + ///Tells all caching mechanisms from server to client whether they may cache this object. It is measured in seconds + public const string CacheControl = "Cache-Control"; + + ///Options that are desired for the connection[17] + public const string Connection = "Connection"; + + ///The type of encoding used on the data. See HTTP compression. + public const string ContentEncoding = "Content-Encoding"; + + ///The language the content is in + public const string ContentLanguage = "Content-Language"; + + ///The length of the response body in octets (8-bit bytes) + public const string ContentLength = "Content-Length"; + + ///An alternate location for the returned data + public const string ContentLocation = "Content-Location"; + + ///A Base64-encoded binary MD5 sum of the content of the response + public const string ContentMD5 = "Content-MD5"; + + ///An opportunity to raise a File Download dialogue box for a known MIME type with binary format or suggest a filename for dynamic content. Quotes are necessary with special characters. + public const string ContentDisposition = "Content-Disposition"; + + ///Where in a full body message this partial message belongs + public const string ContentRange = "Content-Range"; + + ///The MIME type of this content + public const string ContentType = "Content-Type"; + + ///The date and time that the message was sent + public const string Date = "Date"; + + ///An identifier for a specific version of a resource, often a message digest + public const string ETag = "ETag"; + + ///Gives the date/time after which the response is considered stale + public const string Expires = "Expires"; + + ///The last modified date for the requested object, inRFC 2822 format + public const string LastModified = "Last-Modified"; + + ///Used to express a typed relationship with another resource, where the relation type is defined by RFC 5988 + public const string Link = "Link"; + + ///Used in redirection, or when a new resource has been created. + public const string Location = "Location"; + + ///This header is supposed to set P3P policy, in the form of P3P:CP=your_compact_policy. However, P3P did not take off,[22] most browsers have never fully implemented it, a lot of websites set this header with fake policy text, that was enough to fool browsers the existence of P3P policy and grant permissions for third party cookies. + public const string P3P = "P3P"; + + ///Implementation-specific headers that may have various effects anywhere along the request-response chain. + public const string Pragma = "Pragma"; + + ///Request authentication to access the proxy. + public const string ProxyAuthenticate = "Proxy-Authenticate"; + + ///Used in redirection, or when a new resource has been created. This refresh redirects after 5 seconds. This is a proprietary, non-standard header extension introduced by Netscape and supported by most web browsers. + public const string Refresh = "Refresh"; + + ///If an entity is temporarily unavailable, this instructs the client to try again after a specified period of time (seconds). + public const string RetryAfter = "Retry-After"; + + ///A name for the server + public const string Server = "Server"; + + ///an HTTP cookie + public const string SetCookie = "Set-Cookie"; + + ///A HSTS Policy informing the HTTP client how long to cache the HTTPS only policy and whether this applies to subdomains. + public const string StrictTransportSecurity = "Strict-Transport-Security"; + + ///The Trailer general field value indicates that the given set of header fields is present in the trailer of a message encoded with chunked transfer-coding. + public const string Trailer = "Trailer"; + + ///The form of encoding used to safely transfer the entity to the user. Currently defined methods are:chunked, compress, deflate, gzip, identity. + public const string TransferEncoding = "Transfer-Encoding"; + + ///Tells downstream proxies how to match future request headers to decide whether the cached response can be used rather than requesting a fresh one from the origin server. + public const string Vary = "Vary"; + + ///Informs the client of proxies through which the response was sent. + public const string Via = "Via"; + + ///A general warning about possible problems with the entity body. + public const string Warning = "Warning"; + + ///Indicates the authentication scheme that should be used to access the requested entity. + public const string WWWAuthenticate = "WWW-Authenticate"; + } +} \ No newline at end of file diff --git a/lib-vau-csharp/util/IsExternalInit.cs b/lib-vau-csharp/util/IsExternalInit.cs new file mode 100644 index 0000000..0f18f53 --- /dev/null +++ b/lib-vau-csharp/util/IsExternalInit.cs @@ -0,0 +1,20 @@ +#if NETSTANDARD2_0 +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.ComponentModel; + +// ReSharper disable once CheckNamespace +namespace System.Runtime.CompilerServices +{ + /// + /// Reserved to be used by the compiler for tracking metadata. + /// This class should not be used by developers in source code. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + internal static class IsExternalInit + { + } +} +#endif \ No newline at end of file diff --git a/lib-vau-csharp/util/MediaTypeHeader.cs b/lib-vau-csharp/util/MediaTypeHeader.cs new file mode 100644 index 0000000..103a957 --- /dev/null +++ b/lib-vau-csharp/util/MediaTypeHeader.cs @@ -0,0 +1,27 @@ +/* + * Copyright 2024 gematik GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System.Net.Http.Headers; +using System.Net.Mime; + +namespace lib_vau_csharp.util +{ + internal static class MediaTypeHeader + { + public static readonly MediaTypeWithQualityHeaderValue Cbor = new MediaTypeWithQualityHeaderValue("application/cbor"); + public static readonly MediaTypeWithQualityHeaderValue Octet = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Octet); + } +} \ No newline at end of file From 747241c7577103f2856f7b1459cf16ee22de7a6f Mon Sep 17 00:00:00 2001 From: dennis-gr Date: Fri, 22 Aug 2025 13:27:48 +0200 Subject: [PATCH 2/8] Override Tostring in ConnectionId Fix test method name --- lib-vau-csharp-test/VauClientTest.cs | 2 +- lib-vau-csharp/data/ConnectionId.cs | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lib-vau-csharp-test/VauClientTest.cs b/lib-vau-csharp-test/VauClientTest.cs index 96820d5..a32b584 100644 --- a/lib-vau-csharp-test/VauClientTest.cs +++ b/lib-vau-csharp-test/VauClientTest.cs @@ -57,7 +57,7 @@ public async Task VauHttpClientHandlerDoesDecryptionAndEncryptionWhenCallingAnAp } [Test] - public void UsageWitIHttpClientFactory() + public void UsageWithIHttpClientFactory() { var services = new ServiceCollection(); services.AddTransient(); diff --git a/lib-vau-csharp/data/ConnectionId.cs b/lib-vau-csharp/data/ConnectionId.cs index 10d8fd1..66160b9 100644 --- a/lib-vau-csharp/data/ConnectionId.cs +++ b/lib-vau-csharp/data/ConnectionId.cs @@ -22,7 +22,7 @@ namespace lib_vau_csharp.data { public class ConnectionId { - public string Cid { get; private set; } + public string Cid { get; } public ConnectionId(string cid) { Cid = cid; @@ -32,6 +32,8 @@ public static ConnectionId CreateRandom() { return new ConnectionId((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond).ToString()); } + + public override string ToString() => Cid; } } From f42b2ea47e55587af41f268d03e83e8646a75d69 Mon Sep 17 00:00:00 2001 From: dennis-gr Date: Tue, 26 Aug 2025 09:16:32 +0200 Subject: [PATCH 3/8] Updated parsing of VAU responses: * Read the content from the byte array, without converting it to string first which might cause unexpected changes to the result * Headers are now correctly added to both HttpResponseMessage and HttpContent Added note to README regarding usage with record system --- README.md | 5 + lib-vau-csharp-test/Constants.cs | 3 +- .../Medication/MedicationServiceClient.cs | 7418 +++++++++++++++++ .../EpaApiClients/Medication/nswag.json | 56 + ...ientTest.GetMedicationListPdf.verified.txt | 100 + lib-vau-csharp-test/VauClientTest.cs | 37 +- .../lib-vau-csharp-test.csproj | 2 + lib-vau-csharp/VauClient.cs | 25 +- lib-vau-csharp/VauResponse.cs | 55 +- lib-vau-csharp/util/Extensions.cs | 32 - .../util/HttpResponseHeaderNames.cs | 5 +- 11 files changed, 7666 insertions(+), 72 deletions(-) create mode 100644 lib-vau-csharp-test/EpaApiClients/Medication/MedicationServiceClient.cs create mode 100644 lib-vau-csharp-test/EpaApiClients/Medication/nswag.json create mode 100644 lib-vau-csharp-test/VauClientTest.GetMedicationListPdf.verified.txt delete mode 100644 lib-vau-csharp/util/Extensions.cs diff --git a/README.md b/README.md index 729c984..244ef1d 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,11 @@ Diese wird in VauMessage 4 gespeichert und zurück zum Client geschickt. Der Client öffnet die Nachricht, entschlüsselt die Ciphertext-KeyConfirmation und vergleicht wieder den erhalten Hash mit selbst berechneten. Erst dann ist der Handshake abgeschlossen. +## Nutzung mit den APIs des Aktensystems + +Unter Verwendung der Klasse `VauHttpClientHandler` lassen sich Aufrufe des Aktensystems via `HttpClient` transparent ver- und entschlüsseln. Die Tests in der Datei [VauClientTest.cs](lib-vau-csharp-test/VauClientTest.cs) +zeigen beispielhaft, wie diese Klasse mit von [NSwag](https://github.com/RicoSuter/NSwag) generierten Clients genutzt werden kann. + ## License Copyright 2024 gematik GmbH diff --git a/lib-vau-csharp-test/Constants.cs b/lib-vau-csharp-test/Constants.cs index 7a71121..ab91fd2 100644 --- a/lib-vau-csharp-test/Constants.cs +++ b/lib-vau-csharp-test/Constants.cs @@ -22,10 +22,9 @@ using lib_vau_csharp_test.util; using lib_vau_csharp.data; -using lib_vau_csharp_test.util; + using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; -using System.IO; namespace lib_vau_csharp_test { diff --git a/lib-vau-csharp-test/EpaApiClients/Medication/MedicationServiceClient.cs b/lib-vau-csharp-test/EpaApiClients/Medication/MedicationServiceClient.cs new file mode 100644 index 0000000..2b4fdfd --- /dev/null +++ b/lib-vau-csharp-test/EpaApiClients/Medication/MedicationServiceClient.cs @@ -0,0 +1,7418 @@ +//---------------------- +// +// Generated using the NSwag toolchain v14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0)) (http://NSwag.org) +// +//---------------------- + +#pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended." +#pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." +#pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?' +#pragma warning disable 612 // Disable "CS0612 '...' is obsolete" +#pragma warning disable 649 // Disable "CS0649 Field is never assigned to, and will always have its default value null" +#pragma warning disable 1573 // Disable "CS1573 Parameter '...' has no matching param tag in the XML comment for ... +#pragma warning disable 1591 // Disable "CS1591 Missing XML comment for publicly visible type or member ..." +#pragma warning disable 8073 // Disable "CS8073 The result of the expression is always 'false' since a value of type 'T' is never equal to 'null' of type 'T?'" +#pragma warning disable 3016 // Disable "CS3016 Arrays as attribute arguments is not CLS-compliant" +#pragma warning disable 8600 // Disable "CS8600 Converting null literal or possible null value to non-nullable type" +#pragma warning disable 8602 // Disable "CS8602 Dereference of a possibly null reference" +#pragma warning disable 8603 // Disable "CS8603 Possible null reference return" +#pragma warning disable 8604 // Disable "CS8604 Possible null reference argument for parameter" +#pragma warning disable 8625 // Disable "CS8625 Cannot convert null literal to non-nullable reference type" +#pragma warning disable 8765 // Disable "CS8765 Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes)." + +namespace Mauve.Erezept.API.EpaServiceClients.MedicationService +{ + using System = global::System; + + [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class MedicationServiceClient + { + #pragma warning disable 8618 + private string _baseUrl; + #pragma warning restore 8618 + + private System.Net.Http.HttpClient _httpClient; + private static System.Lazy _settings = new System.Lazy(CreateSerializerSettings, true); + private System.Text.Json.JsonSerializerOptions _instanceSettings; + + #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + public MedicationServiceClient(System.Net.Http.HttpClient httpClient) + #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. + { + _httpClient = httpClient; + Initialize(); + } + + private static System.Text.Json.JsonSerializerOptions CreateSerializerSettings() + { + var settings = new System.Text.Json.JsonSerializerOptions(); + UpdateJsonSerializerSettings(settings); + return settings; + } + + protected System.Text.Json.JsonSerializerOptions JsonSerializerSettings { get { return _instanceSettings ?? _settings.Value; } } + + static partial void UpdateJsonSerializerSettings(System.Text.Json.JsonSerializerOptions settings); + + partial void Initialize(); + + partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url); + partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); + partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); + + /// + /// Get CapabilityStatement + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// OK + /// A server side error occurred. + public virtual System.Threading.Tasks.Task MetadataAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept? accept, _format? _format) + { + return MetadataAsync(x_Request_ID, x_insurantid, x_useragent, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Get CapabilityStatement + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// OK + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task MetadataAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept? accept, _format? _format, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/metadata" + urlBuilder_.Append("epa/medication/api/v1/fhir/metadata"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Search for Medication + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// Reverse include other resources + /// Resource.id + /// Resource.meta.lastUpdated + /// Medication.identifier + /// Medication.code + /// Medication.status + /// Medication.ingredient.item as CodeableConcept + /// Search successful + /// A server side error occurred. + public virtual System.Threading.Tasks.Task MedicationAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept2? accept, _format2? _format, string _count, int? _offset, string _total, string _revinclude, string _id, System.DateTime? _lastUpdated, string identifier, string code, string status, string ingredient_code) + { + return MedicationAsync(x_Request_ID, x_insurantid, x_useragent, accept, _format, _count, _offset, _total, _revinclude, _id, _lastUpdated, identifier, code, status, ingredient_code, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Search for Medication + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// Reverse include other resources + /// Resource.id + /// Resource.meta.lastUpdated + /// Medication.identifier + /// Medication.code + /// Medication.status + /// Medication.ingredient.item as CodeableConcept + /// Search successful + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task MedicationAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept2? accept, _format2? _format, string _count, int? _offset, string _total, string _revinclude, string _id, System.DateTime? _lastUpdated, string identifier, string code, string status, string ingredient_code, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Medication" + urlBuilder_.Append("epa/medication/api/v1/fhir/Medication"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_revinclude != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_revinclude")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_revinclude, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_id != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_id")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_id, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_lastUpdated != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_lastUpdated")).Append('=').Append(System.Uri.EscapeDataString(_lastUpdated.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (identifier != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("identifier")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(identifier, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (code != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("code")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(code, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (status != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("status")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(status, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (ingredient_code != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("ingredient-code")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(ingredient_code, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid query parameter(s)", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// History for all Medication + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// History for type retrieved + /// A server side error occurred. + public virtual System.Threading.Tasks.Task HistoryAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string _count, int? _offset, string _total, Accept3? accept, _format3? _format) + { + return HistoryAsync(x_Request_ID, x_insurantid, x_useragent, _count, _offset, _total, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// History for all Medication + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// History for type retrieved + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task HistoryAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string _count, int? _offset, string _total, Accept3? accept, _format3? _format, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Medication/_history" + urlBuilder_.Append("epa/medication/api/v1/fhir/Medication/_history"); + urlBuilder_.Append('?'); + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Read a specific Medication + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Medication successfully read + /// A server side error occurred. + public virtual System.Threading.Tasks.Task Medication2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept4? accept, _format4? _format) + { + return Medication2Async(x_Request_ID, x_insurantid, x_useragent, id, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Read a specific Medication + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Medication successfully read + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task Medication2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept4? accept, _format4? _format, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Medication/{id}" + urlBuilder_.Append("epa/medication/api/v1/fhir/Medication/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// History of a specific Medication + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// History retrieved + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept5? accept, _format5? _format, string _count, int? _offset, string _total) + { + return History2Async(x_Request_ID, x_insurantid, x_useragent, id, accept, _format, _count, _offset, _total, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// History of a specific Medication + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// History retrieved + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept5? accept, _format5? _format, string _count, int? _offset, string _total, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Medication/{id}/_history" + urlBuilder_.Append("epa/medication/api/v1/fhir/Medication/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/_history"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Read version of Medication + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// Version ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Medication version read + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History3Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, string vid, Accept6? accept, _format6? _format) + { + return History3Async(x_Request_ID, x_insurantid, x_useragent, id, vid, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Read version of Medication + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// Version ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Medication version read + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History3Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, string vid, Accept6? accept, _format6? _format, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + if (vid == null) + throw new System.ArgumentNullException("vid"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Medication/{id}/_history/{vid}" + urlBuilder_.Append("epa/medication/api/v1/fhir/Medication/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/_history/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(vid, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Search for MedicationRequest + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// Including other resources + /// Reverse include other resources + /// Resource.id + /// Resource.meta.lastUpdated + /// MedicationRequest.identifier + /// MedicationRequest.authoredOn + /// MedicationRequest.status + /// MedicationRequest.requester + /// MedicationRequest.medication as Reference + /// Search successful + /// A server side error occurred. + public virtual System.Threading.Tasks.Task MedicationRequestAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept7? accept, _format7? _format, string _count, int? _offset, string _total, string _include, string _revinclude, string _id, System.DateTime? _lastUpdated, string identifier, System.DateTime? authoredon, string status, System.Uri requester, System.Uri medication) + { + return MedicationRequestAsync(x_Request_ID, x_insurantid, x_useragent, accept, _format, _count, _offset, _total, _include, _revinclude, _id, _lastUpdated, identifier, authoredon, status, requester, medication, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Search for MedicationRequest + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// Including other resources + /// Reverse include other resources + /// Resource.id + /// Resource.meta.lastUpdated + /// MedicationRequest.identifier + /// MedicationRequest.authoredOn + /// MedicationRequest.status + /// MedicationRequest.requester + /// MedicationRequest.medication as Reference + /// Search successful + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task MedicationRequestAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept7? accept, _format7? _format, string _count, int? _offset, string _total, string _include, string _revinclude, string _id, System.DateTime? _lastUpdated, string identifier, System.DateTime? authoredon, string status, System.Uri requester, System.Uri medication, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/MedicationRequest" + urlBuilder_.Append("epa/medication/api/v1/fhir/MedicationRequest"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_include != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_include")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_include, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_revinclude != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_revinclude")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_revinclude, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_id != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_id")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_id, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_lastUpdated != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_lastUpdated")).Append('=').Append(System.Uri.EscapeDataString(_lastUpdated.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (identifier != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("identifier")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(identifier, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (authoredon != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("authoredon")).Append('=').Append(System.Uri.EscapeDataString(authoredon.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (status != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("status")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(status, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (requester != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("requester")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(requester, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (medication != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("medication")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(medication, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid query parameter(s)", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// History for all MedicationRequest + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// History for type retrieved + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History4Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string _count, int? _offset, string _total, Accept8? accept, _format8? _format) + { + return History4Async(x_Request_ID, x_insurantid, x_useragent, _count, _offset, _total, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// History for all MedicationRequest + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// History for type retrieved + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History4Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string _count, int? _offset, string _total, Accept8? accept, _format8? _format, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/MedicationRequest/_history" + urlBuilder_.Append("epa/medication/api/v1/fhir/MedicationRequest/_history"); + urlBuilder_.Append('?'); + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Read a specific MedicationRequest + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// MedicationRequest successfully read + /// A server side error occurred. + public virtual System.Threading.Tasks.Task MedicationRequest2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept9? accept, _format9? _format) + { + return MedicationRequest2Async(x_Request_ID, x_insurantid, x_useragent, id, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Read a specific MedicationRequest + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// MedicationRequest successfully read + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task MedicationRequest2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept9? accept, _format9? _format, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/MedicationRequest/{id}" + urlBuilder_.Append("epa/medication/api/v1/fhir/MedicationRequest/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// History of a specific MedicationRequest + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// History retrieved + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History5Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept10? accept, _format10? _format, string _count, int? _offset, string _total) + { + return History5Async(x_Request_ID, x_insurantid, x_useragent, id, accept, _format, _count, _offset, _total, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// History of a specific MedicationRequest + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// History retrieved + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History5Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept10? accept, _format10? _format, string _count, int? _offset, string _total, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/MedicationRequest/{id}/_history" + urlBuilder_.Append("epa/medication/api/v1/fhir/MedicationRequest/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/_history"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Read version of MedicationRequest + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// Version ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// MedicationRequest version read + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History6Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, string vid, Accept11? accept, _format11? _format) + { + return History6Async(x_Request_ID, x_insurantid, x_useragent, id, vid, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Read version of MedicationRequest + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// Version ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// MedicationRequest version read + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History6Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, string vid, Accept11? accept, _format11? _format, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + if (vid == null) + throw new System.ArgumentNullException("vid"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/MedicationRequest/{id}/_history/{vid}" + urlBuilder_.Append("epa/medication/api/v1/fhir/MedicationRequest/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/_history/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(vid, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Search for MedicationDispense + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// Including other resources + /// Resource.id + /// Resource.meta.lastUpdated + /// MedicationDispense.identifier + /// MedicationDispense.whenHandedOver + /// MedicationDispense.authorizingPrescription + /// MedicationDispense.performer.actor + /// MedicationDispense.status + /// MedicationDispense.medication as Reference + /// Search successful + /// A server side error occurred. + public virtual System.Threading.Tasks.Task MedicationDispenseAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept12? accept, _format12? _format, string _count, int? _offset, string _total, string _include, string _id, System.DateTime? _lastUpdated, string identifier, System.DateTime? whenhandedover, System.Uri prescription, System.Uri performer, string status, System.Uri medication) + { + return MedicationDispenseAsync(x_Request_ID, x_insurantid, x_useragent, accept, _format, _count, _offset, _total, _include, _id, _lastUpdated, identifier, whenhandedover, prescription, performer, status, medication, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Search for MedicationDispense + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// Including other resources + /// Resource.id + /// Resource.meta.lastUpdated + /// MedicationDispense.identifier + /// MedicationDispense.whenHandedOver + /// MedicationDispense.authorizingPrescription + /// MedicationDispense.performer.actor + /// MedicationDispense.status + /// MedicationDispense.medication as Reference + /// Search successful + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task MedicationDispenseAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept12? accept, _format12? _format, string _count, int? _offset, string _total, string _include, string _id, System.DateTime? _lastUpdated, string identifier, System.DateTime? whenhandedover, System.Uri prescription, System.Uri performer, string status, System.Uri medication, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/MedicationDispense" + urlBuilder_.Append("epa/medication/api/v1/fhir/MedicationDispense"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_include != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_include")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_include, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_id != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_id")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_id, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_lastUpdated != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_lastUpdated")).Append('=').Append(System.Uri.EscapeDataString(_lastUpdated.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (identifier != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("identifier")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(identifier, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (whenhandedover != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("whenhandedover")).Append('=').Append(System.Uri.EscapeDataString(whenhandedover.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (prescription != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("prescription")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(prescription, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (performer != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("performer")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(performer, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (status != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("status")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(status, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (medication != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("medication")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(medication, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid query parameter(s)", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// History for all MedicationDispense + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// History for type retrieved + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History7Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string _count, int? _offset, string _total, Accept13? accept, _format13? _format) + { + return History7Async(x_Request_ID, x_insurantid, x_useragent, _count, _offset, _total, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// History for all MedicationDispense + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// History for type retrieved + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History7Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string _count, int? _offset, string _total, Accept13? accept, _format13? _format, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/MedicationDispense/_history" + urlBuilder_.Append("epa/medication/api/v1/fhir/MedicationDispense/_history"); + urlBuilder_.Append('?'); + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Read a specific MedicationDispense + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// MedicationDispense successfully read + /// A server side error occurred. + public virtual System.Threading.Tasks.Task MedicationDispense2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept14? accept, _format14? _format) + { + return MedicationDispense2Async(x_Request_ID, x_insurantid, x_useragent, id, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Read a specific MedicationDispense + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// MedicationDispense successfully read + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task MedicationDispense2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept14? accept, _format14? _format, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/MedicationDispense/{id}" + urlBuilder_.Append("epa/medication/api/v1/fhir/MedicationDispense/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// History of a specific MedicationDispense + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// History retrieved + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History8Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept15? accept, _format15? _format, string _count, int? _offset, string _total) + { + return History8Async(x_Request_ID, x_insurantid, x_useragent, id, accept, _format, _count, _offset, _total, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// History of a specific MedicationDispense + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// History retrieved + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History8Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept15? accept, _format15? _format, string _count, int? _offset, string _total, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/MedicationDispense/{id}/_history" + urlBuilder_.Append("epa/medication/api/v1/fhir/MedicationDispense/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/_history"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Read version of MedicationDispense + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// Version ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// MedicationDispense version read + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History9Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, string vid, Accept16? accept, _format16? _format) + { + return History9Async(x_Request_ID, x_insurantid, x_useragent, id, vid, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Read version of MedicationDispense + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// Version ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// MedicationDispense version read + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History9Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, string vid, Accept16? accept, _format16? _format, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + if (vid == null) + throw new System.ArgumentNullException("vid"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/MedicationDispense/{id}/_history/{vid}" + urlBuilder_.Append("epa/medication/api/v1/fhir/MedicationDispense/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/_history/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(vid, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Search for Organization + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// Reverse include other resources + /// Resource.id + /// Resource.meta.lastUpdated + /// Organization.identifier + /// Organization.name | Organization.alias + /// Search successful + /// A server side error occurred. + public virtual System.Threading.Tasks.Task OrganizationAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept17? accept, _format17? _format, string _count, int? _offset, string _total, string _revinclude, string _id, System.DateTime? _lastUpdated, string identifier, string name) + { + return OrganizationAsync(x_Request_ID, x_insurantid, x_useragent, accept, _format, _count, _offset, _total, _revinclude, _id, _lastUpdated, identifier, name, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Search for Organization + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// Reverse include other resources + /// Resource.id + /// Resource.meta.lastUpdated + /// Organization.identifier + /// Organization.name | Organization.alias + /// Search successful + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task OrganizationAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept17? accept, _format17? _format, string _count, int? _offset, string _total, string _revinclude, string _id, System.DateTime? _lastUpdated, string identifier, string name, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Organization" + urlBuilder_.Append("epa/medication/api/v1/fhir/Organization"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_revinclude != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_revinclude")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_revinclude, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_id != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_id")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_id, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_lastUpdated != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_lastUpdated")).Append('=').Append(System.Uri.EscapeDataString(_lastUpdated.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (identifier != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("identifier")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(identifier, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (name != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("name")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(name, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid query parameter(s)", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// History for all Organization + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// History for type retrieved + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History10Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string _count, int? _offset, string _total, Accept18? accept, _format18? _format) + { + return History10Async(x_Request_ID, x_insurantid, x_useragent, _count, _offset, _total, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// History for all Organization + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// History for type retrieved + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History10Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string _count, int? _offset, string _total, Accept18? accept, _format18? _format, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Organization/_history" + urlBuilder_.Append("epa/medication/api/v1/fhir/Organization/_history"); + urlBuilder_.Append('?'); + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Read a specific Organization + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Organization successfully read + /// A server side error occurred. + public virtual System.Threading.Tasks.Task Organization2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept19? accept, _format19? _format) + { + return Organization2Async(x_Request_ID, x_insurantid, x_useragent, id, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Read a specific Organization + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Organization successfully read + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task Organization2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept19? accept, _format19? _format, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Organization/{id}" + urlBuilder_.Append("epa/medication/api/v1/fhir/Organization/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// History of a specific Organization + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// History retrieved + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History11Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept20? accept, _format20? _format, string _count, int? _offset, string _total) + { + return History11Async(x_Request_ID, x_insurantid, x_useragent, id, accept, _format, _count, _offset, _total, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// History of a specific Organization + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// History retrieved + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History11Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept20? accept, _format20? _format, string _count, int? _offset, string _total, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Organization/{id}/_history" + urlBuilder_.Append("epa/medication/api/v1/fhir/Organization/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/_history"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Read version of Organization + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// Version ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Organization version read + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History12Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, string vid, Accept21? accept, _format21? _format) + { + return History12Async(x_Request_ID, x_insurantid, x_useragent, id, vid, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Read version of Organization + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// Version ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Organization version read + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History12Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, string vid, Accept21? accept, _format21? _format, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + if (vid == null) + throw new System.ArgumentNullException("vid"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Organization/{id}/_history/{vid}" + urlBuilder_.Append("epa/medication/api/v1/fhir/Organization/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/_history/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(vid, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Search for Practitioner + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// Reverse include other resources + /// Resource.id + /// Resource.meta.lastUpdated + /// Practitioner.identifier + /// Practitioner.name + /// Search successful + /// A server side error occurred. + public virtual System.Threading.Tasks.Task PractitionerAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept22? accept, _format22? _format, string _count, int? _offset, string _total, string _revinclude, string _id, System.DateTime? _lastUpdated, string identifier, string name) + { + return PractitionerAsync(x_Request_ID, x_insurantid, x_useragent, accept, _format, _count, _offset, _total, _revinclude, _id, _lastUpdated, identifier, name, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Search for Practitioner + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// Reverse include other resources + /// Resource.id + /// Resource.meta.lastUpdated + /// Practitioner.identifier + /// Practitioner.name + /// Search successful + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task PractitionerAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept22? accept, _format22? _format, string _count, int? _offset, string _total, string _revinclude, string _id, System.DateTime? _lastUpdated, string identifier, string name, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Practitioner" + urlBuilder_.Append("epa/medication/api/v1/fhir/Practitioner"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_revinclude != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_revinclude")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_revinclude, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_id != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_id")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_id, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_lastUpdated != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_lastUpdated")).Append('=').Append(System.Uri.EscapeDataString(_lastUpdated.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (identifier != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("identifier")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(identifier, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (name != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("name")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(name, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid query parameter(s)", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// History for all Practitioner + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// History for type retrieved + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History13Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string _count, int? _offset, string _total, Accept23? accept, _format23? _format) + { + return History13Async(x_Request_ID, x_insurantid, x_useragent, _count, _offset, _total, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// History for all Practitioner + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// History for type retrieved + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History13Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string _count, int? _offset, string _total, Accept23? accept, _format23? _format, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Practitioner/_history" + urlBuilder_.Append("epa/medication/api/v1/fhir/Practitioner/_history"); + urlBuilder_.Append('?'); + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Read a specific Practitioner + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Practitioner successfully read + /// A server side error occurred. + public virtual System.Threading.Tasks.Task Practitioner2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept24? accept, _format24? _format) + { + return Practitioner2Async(x_Request_ID, x_insurantid, x_useragent, id, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Read a specific Practitioner + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Practitioner successfully read + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task Practitioner2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept24? accept, _format24? _format, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Practitioner/{id}" + urlBuilder_.Append("epa/medication/api/v1/fhir/Practitioner/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// History of a specific Practitioner + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// History retrieved + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History14Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept25? accept, _format25? _format, string _count, int? _offset, string _total) + { + return History14Async(x_Request_ID, x_insurantid, x_useragent, id, accept, _format, _count, _offset, _total, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// History of a specific Practitioner + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// History retrieved + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History14Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept25? accept, _format25? _format, string _count, int? _offset, string _total, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Practitioner/{id}/_history" + urlBuilder_.Append("epa/medication/api/v1/fhir/Practitioner/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/_history"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Read version of Practitioner + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// Version ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Practitioner version read + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History15Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, string vid, Accept26? accept, _format26? _format) + { + return History15Async(x_Request_ID, x_insurantid, x_useragent, id, vid, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Read version of Practitioner + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// Version ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Practitioner version read + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History15Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, string vid, Accept26? accept, _format26? _format, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + if (vid == null) + throw new System.ArgumentNullException("vid"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/Practitioner/{id}/_history/{vid}" + urlBuilder_.Append("epa/medication/api/v1/fhir/Practitioner/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/_history/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(vid, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Search for PractitionerRole + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// Including other resources + /// Reverse include other resources + /// Resource.id + /// Resource.meta.lastUpdated + /// PractitionerRole.identifier + /// PractitionerRole.practitioner + /// PractitionerRole.organization + /// Search successful + /// A server side error occurred. + public virtual System.Threading.Tasks.Task PractitionerRoleAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept27? accept, _format27? _format, string _count, int? _offset, string _total, string _include, string _revinclude, string _id, System.DateTime? _lastUpdated, string identifier, System.Uri practitioner, System.Uri organization) + { + return PractitionerRoleAsync(x_Request_ID, x_insurantid, x_useragent, accept, _format, _count, _offset, _total, _include, _revinclude, _id, _lastUpdated, identifier, practitioner, organization, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Search for PractitionerRole + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// Including other resources + /// Reverse include other resources + /// Resource.id + /// Resource.meta.lastUpdated + /// PractitionerRole.identifier + /// PractitionerRole.practitioner + /// PractitionerRole.organization + /// Search successful + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task PractitionerRoleAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept27? accept, _format27? _format, string _count, int? _offset, string _total, string _include, string _revinclude, string _id, System.DateTime? _lastUpdated, string identifier, System.Uri practitioner, System.Uri organization, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/PractitionerRole" + urlBuilder_.Append("epa/medication/api/v1/fhir/PractitionerRole"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_include != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_include")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_include, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_revinclude != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_revinclude")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_revinclude, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_id != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_id")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_id, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_lastUpdated != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_lastUpdated")).Append('=').Append(System.Uri.EscapeDataString(_lastUpdated.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (identifier != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("identifier")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(identifier, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (practitioner != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("practitioner")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(practitioner, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (organization != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("organization")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(organization, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid query parameter(s)", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// History for all PractitionerRole + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// History for type retrieved + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History16Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string _count, int? _offset, string _total, Accept28? accept, _format28? _format) + { + return History16Async(x_Request_ID, x_insurantid, x_useragent, _count, _offset, _total, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// History for all PractitionerRole + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// History for type retrieved + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History16Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string _count, int? _offset, string _total, Accept28? accept, _format28? _format, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/PractitionerRole/_history" + urlBuilder_.Append("epa/medication/api/v1/fhir/PractitionerRole/_history"); + urlBuilder_.Append('?'); + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Read a specific PractitionerRole + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// PractitionerRole successfully read + /// A server side error occurred. + public virtual System.Threading.Tasks.Task PractitionerRole2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept29? accept, _format29? _format) + { + return PractitionerRole2Async(x_Request_ID, x_insurantid, x_useragent, id, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Read a specific PractitionerRole + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// PractitionerRole successfully read + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task PractitionerRole2Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept29? accept, _format29? _format, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/PractitionerRole/{id}" + urlBuilder_.Append("epa/medication/api/v1/fhir/PractitionerRole/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// History of a specific PractitionerRole + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// History retrieved + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History17Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept30? accept, _format30? _format, string _count, int? _offset, string _total) + { + return History17Async(x_Request_ID, x_insurantid, x_useragent, id, accept, _format, _count, _offset, _total, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// History of a specific PractitionerRole + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// With _count, the client can specify the maximum number of elements to be included on one page of the response. This means the Medication Service limits the result set to this maximum specified number. If no value for _count is provided, the default value set is 25. + /// This URL parameter indicates the (zero-based) offset of the first returned element in the collection. If no value for _offset is provided, the default value set is 0. + /// This parameter controls whether and how the AuditEvent Service returns the total number of search results. + /// History retrieved + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History17Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, Accept30? accept, _format30? _format, string _count, int? _offset, string _total, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/PractitionerRole/{id}/_history" + urlBuilder_.Append("epa/medication/api/v1/fhir/PractitionerRole/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/_history"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_total != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_total")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_total, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Read version of PractitionerRole + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// Version ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// PractitionerRole version read + /// A server side error occurred. + public virtual System.Threading.Tasks.Task History18Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, string vid, Accept31? accept, _format31? _format) + { + return History18Async(x_Request_ID, x_insurantid, x_useragent, id, vid, accept, _format, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Read version of PractitionerRole + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Resource ID + /// Version ID + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// PractitionerRole version read + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task History18Async(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, string id, string vid, Accept31? accept, _format31? _format, System.Threading.CancellationToken cancellationToken) + { + if (id == null) + throw new System.ArgumentNullException("id"); + + if (vid == null) + throw new System.ArgumentNullException("vid"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/PractitionerRole/{id}/_history/{vid}" + urlBuilder_.Append("epa/medication/api/v1/fhir/PractitionerRole/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/_history/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(vid, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 410) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Resource was deleted", status_, responseText_, headers_, null); + } + else + if (status_ == 423) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("If the insurant objected to the medication process or objected to the submission of prescription and dispensation data into the ePA system, the Medication Service is locked.", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// System-level FHIR Operation $provide-prescription-erp + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Successful operation + /// A server side error occurred. + public virtual System.Threading.Tasks.Task ProvidePrescriptionErpAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, object body) + { + return ProvidePrescriptionErpAsync(x_Request_ID, x_insurantid, x_useragent, body, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// System-level FHIR Operation $provide-prescription-erp + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Successful operation + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task ProvidePrescriptionErpAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, object body, System.Threading.CancellationToken cancellationToken) + { + if (body == null) + throw new System.ArgumentNullException("body"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + var json_ = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(body, JsonSerializerSettings); + var content_ = new System.Net.Http.ByteArrayContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/fhir+json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/fhir+json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/provide-prescription-erp" + urlBuilder_.Append("epa/medication/api/v1/fhir/provide-prescription-erp"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// System-level FHIR Operation $cancel-prescription-erp + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Successful operation + /// A server side error occurred. + public virtual System.Threading.Tasks.Task CancelPrescriptionErpAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, object body) + { + return CancelPrescriptionErpAsync(x_Request_ID, x_insurantid, x_useragent, body, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// System-level FHIR Operation $cancel-prescription-erp + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Successful operation + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task CancelPrescriptionErpAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, object body, System.Threading.CancellationToken cancellationToken) + { + if (body == null) + throw new System.ArgumentNullException("body"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + var json_ = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(body, JsonSerializerSettings); + var content_ = new System.Net.Http.ByteArrayContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/fhir+json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/fhir+json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/cancel-prescription-erp" + urlBuilder_.Append("epa/medication/api/v1/fhir/cancel-prescription-erp"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// System-level FHIR Operation $provide-dispensation-erp + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Successful operation + /// A server side error occurred. + public virtual System.Threading.Tasks.Task ProvideDispensationErpAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, object body) + { + return ProvideDispensationErpAsync(x_Request_ID, x_insurantid, x_useragent, body, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// System-level FHIR Operation $provide-dispensation-erp + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Successful operation + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task ProvideDispensationErpAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, object body, System.Threading.CancellationToken cancellationToken) + { + if (body == null) + throw new System.ArgumentNullException("body"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + var json_ = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(body, JsonSerializerSettings); + var content_ = new System.Net.Http.ByteArrayContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/fhir+json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/fhir+json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/provide-dispensation-erp" + urlBuilder_.Append("epa/medication/api/v1/fhir/provide-dispensation-erp"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// System-level FHIR Operation $cancel-dispensation-erp + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Successful operation + /// A server side error occurred. + public virtual System.Threading.Tasks.Task CancelDispensationErpAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, object body) + { + return CancelDispensationErpAsync(x_Request_ID, x_insurantid, x_useragent, body, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// System-level FHIR Operation $cancel-dispensation-erp + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// Successful operation + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task CancelDispensationErpAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, object body, System.Threading.CancellationToken cancellationToken) + { + if (body == null) + throw new System.ArgumentNullException("body"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + var json_ = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(body, JsonSerializerSettings); + var content_ = new System.Net.Http.ByteArrayContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/fhir+json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/fhir+json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/cancel-dispensation-erp" + urlBuilder_.Append("epa/medication/api/v1/fhir/cancel-dispensation-erp"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// System-level FHIR Operation $medication-list + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Limit the search to this date. Can specify upper or lower limits and periods by providing an upper and a lower limit. + /// Limit the result bundle to this many entries. To get more entries request the next page. + /// Defines the offset of the first entry in the collection. + /// Successful operation + /// A server side error occurred. + public virtual System.Threading.Tasks.Task MedicationListAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept32? accept, _format32? _format, string date, int? _count, int? _offset) + { + return MedicationListAsync(x_Request_ID, x_insurantid, x_useragent, accept, _format, date, _count, _offset, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// System-level FHIR Operation $medication-list + /// + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// The Accept header indicates the format in which the client wishes to receive the FHIR response — supported values are application/fhir+json and application/fhir+xml + /// Specify alternative response formats by their MIME-types (when a client is unable acccess accept: header) + /// Limit the search to this date. Can specify upper or lower limits and periods by providing an upper and a lower limit. + /// Limit the result bundle to this many entries. To get more entries request the next page. + /// Defines the offset of the first entry in the collection. + /// Successful operation + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task MedicationListAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, Accept32? accept, _format32? _format, string date, int? _count, int? _offset, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + + if (accept != null) + request_.Headers.TryAddWithoutValidation("Accept", ConvertToString(accept, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/api/v1/fhir/medication-list" + urlBuilder_.Append("epa/medication/api/v1/fhir/medication-list"); + urlBuilder_.Append('?'); + if (_format != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_format")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_format, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (date != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("date")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(date, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_count != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_count")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_count, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (_offset != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("_offset")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(_offset, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Invalid request", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// OK + /// A server side error occurred. + public virtual System.Threading.Tasks.Task RenderEMLAsHTMLAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent) + { + return RenderEMLAsHTMLAsync(x_Request_ID, x_insurantid, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// OK + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task RenderEMLAsHTMLAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("text/html")); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/render/v1/eml/xhtml" + urlBuilder_.Append("epa/medication/render/v1/eml/xhtml"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new MedicationServiceException("Unknown or invalid search parameter(s)", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// OK + /// A server side error occurred. + public virtual System.Threading.Tasks.Task RenderEMLAsPDFAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent) + { + return RenderEMLAsPDFAsync(x_Request_ID, x_insurantid, x_useragent, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// UUID of the request message + /// Health Record Identifier + /// user agent information + /// OK + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task RenderEMLAsPDFAsync(System.Guid? x_Request_ID, string x_insurantid, string x_useragent, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + + if (x_Request_ID != null) + request_.Headers.TryAddWithoutValidation("X-Request-ID", ConvertToString(x_Request_ID, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_insurantid == null) + throw new System.ArgumentNullException("x_insurantid"); + request_.Headers.TryAddWithoutValidation("x-insurantid", ConvertToString(x_insurantid, System.Globalization.CultureInfo.InvariantCulture)); + + if (x_useragent == null) + throw new System.ArgumentNullException("x_useragent"); + request_.Headers.TryAddWithoutValidation("x-useragent", ConvertToString(x_useragent, System.Globalization.CultureInfo.InvariantCulture)); + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/pdf")); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "epa/medication/render/v1/eml/pdf" + urlBuilder_.Append("epa/medication/render/v1/eml/pdf"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200 || status_ == 206) + { + var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false); + var fileResponse_ = new FileResponse(status_, headers_, responseStream_, null, response_); + disposeClient_ = false; disposeResponse_ = false; // response and client are disposed by FileResponse + return fileResponse_; + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state UNKNOWN or INITIALIZED", status_, responseText_, headers_, null); + } + else + if (status_ == 400) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new MedicationServiceException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new MedicationServiceException("Unknown or invalid search parameter(s)", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 403) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Device registration does not exist", status_, responseText_, headers_, null); + } + else + if (status_ == 409) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Health record is in state SUSPENDED", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("Any other error", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new MedicationServiceException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + protected struct ObjectResponseResult + { + public ObjectResponseResult(T responseObject, string responseText) + { + this.Object = responseObject; + this.Text = responseText; + } + + public T Object { get; } + + public string Text { get; } + } + + public bool ReadResponseAsString { get; set; } + + protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken) + { + if (response == null || response.Content == null) + { + return new ObjectResponseResult(default(T), string.Empty); + } + + if (ReadResponseAsString) + { + var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + var typedBody = System.Text.Json.JsonSerializer.Deserialize(responseText, JsonSerializerSettings); + return new ObjectResponseResult(typedBody, responseText); + } + catch (System.Text.Json.JsonException exception) + { + var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; + throw new MedicationServiceException(message, (int)response.StatusCode, responseText, headers, exception); + } + } + else + { + try + { + using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) + { + var typedBody = await System.Text.Json.JsonSerializer.DeserializeAsync(responseStream, JsonSerializerSettings, cancellationToken).ConfigureAwait(false); + return new ObjectResponseResult(typedBody, string.Empty); + } + } + catch (System.Text.Json.JsonException exception) + { + var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; + throw new MedicationServiceException(message, (int)response.StatusCode, string.Empty, headers, exception); + } + } + } + + private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) + { + if (value == null) + { + return ""; + } + + if (value is System.Enum) + { + var name = System.Enum.GetName(value.GetType(), value); + if (name != null) + { + var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name); + if (field != null) + { + var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) + as System.Runtime.Serialization.EnumMemberAttribute; + if (attribute != null) + { + return attribute.Value != null ? attribute.Value : name; + } + } + + var converted = System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo)); + return converted == null ? string.Empty : converted; + } + } + else if (value is bool) + { + return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant(); + } + else if (value is byte[]) + { + return System.Convert.ToBase64String((byte[]) value); + } + else if (value is string[]) + { + return string.Join(",", (string[])value); + } + else if (value.GetType().IsArray) + { + var valueArray = (System.Array)value; + var valueTextArray = new string[valueArray.Length]; + for (var i = 0; i < valueArray.Length; i++) + { + valueTextArray[i] = ConvertToString(valueArray.GetValue(i), cultureInfo); + } + return string.Join(",", valueTextArray); + } + + var result = System.Convert.ToString(value, cultureInfo); + return result == null ? "" : result; + } + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept2 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format2 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept3 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format3 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept4 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format4 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept5 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format5 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept6 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format6 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept7 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format7 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept8 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format8 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept9 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format9 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept10 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format10 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept11 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format11 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept12 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format12 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept13 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format13 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept14 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format14 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept15 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format15 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept16 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format16 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept17 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format17 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept18 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format18 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept19 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format19 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept20 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format20 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept21 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format21 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept22 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format22 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept23 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format23 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept24 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format24 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept25 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format25 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept26 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format26 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept27 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format27 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept28 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format28 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept29 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format29 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept30 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format30 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept31 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format31 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Accept32 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum _format32 + { + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+json")] + Application_fhir_json = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"application/fhir+xml")] + Application_fhir_xml = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class FileResponse : System.IDisposable + { + private System.IDisposable _client; + private System.IDisposable _response; + + public int StatusCode { get; private set; } + + public System.Collections.Generic.IReadOnlyDictionary> Headers { get; private set; } + + public System.IO.Stream Stream { get; private set; } + + public bool IsPartial + { + get { return StatusCode == 206; } + } + + public FileResponse(int statusCode, System.Collections.Generic.IReadOnlyDictionary> headers, System.IO.Stream stream, System.IDisposable client, System.IDisposable response) + { + StatusCode = statusCode; + Headers = headers; + Stream = stream; + _client = client; + _response = response; + } + + public void Dispose() + { + Stream.Dispose(); + if (_response != null) + _response.Dispose(); + if (_client != null) + _client.Dispose(); + } + } + + + [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class MedicationServiceException : System.Exception + { + public int StatusCode { get; private set; } + + public string Response { get; private set; } + + public System.Collections.Generic.IReadOnlyDictionary> Headers { get; private set; } + + public MedicationServiceException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Exception innerException) + : base(message + "\n\nStatus: " + statusCode + "\nResponse: \n" + ((response == null) ? "(null)" : response.Substring(0, response.Length >= 512 ? 512 : response.Length)), innerException) + { + StatusCode = statusCode; + Response = response; + Headers = headers; + } + + public override string ToString() + { + return string.Format("HTTP Response: \n\n{0}\n\n{1}", Response, base.ToString()); + } + } + + [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class MedicationServiceException : MedicationServiceException + { + public TResult Result { get; private set; } + + public MedicationServiceException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, TResult result, System.Exception innerException) + : base(message, statusCode, response, headers, innerException) + { + Result = result; + } + } + +} + +#pragma warning restore 108 +#pragma warning restore 114 +#pragma warning restore 472 +#pragma warning restore 612 +#pragma warning restore 1573 +#pragma warning restore 1591 +#pragma warning restore 8073 +#pragma warning restore 3016 +#pragma warning restore 8600 +#pragma warning restore 8602 +#pragma warning restore 8603 +#pragma warning restore 8604 +#pragma warning restore 8625 \ No newline at end of file diff --git a/lib-vau-csharp-test/EpaApiClients/Medication/nswag.json b/lib-vau-csharp-test/EpaApiClients/Medication/nswag.json new file mode 100644 index 0000000..55c7433 --- /dev/null +++ b/lib-vau-csharp-test/EpaApiClients/Medication/nswag.json @@ -0,0 +1,56 @@ +{ + "runtime": "Net80", + "documentGenerator": { + "fromDocument": { + "url": "https://gemspec.gematik.de/ig/fhir/epa-medication/1.1.5/epa-medication-service-client.openapi.yaml", + "newLineBehavior": "Auto" + } + }, + "codeGenerators": { + "openApiToCSharpClient": { + "generateClientClasses": true, + "generateDtoTypes": true, + "injectHttpClient": true, + "disposeHttpClient": false, + "generateExceptionClasses": true, + "exceptionClass": "MedicationServiceException", + "wrapDtoExceptions": true, + "useHttpClientCreationMethod": false, + "httpClientType": "System.Net.Http.HttpClient", + "useHttpRequestMessageCreationMethod": false, + "useBaseUrl": true, + "generateBaseUrlProperty": true, + "generateSyncMethods": false, + "exposeJsonSerializerSettings": false, + "clientClassAccessModifier": "public", + "typeAccessModifier": "public", + "generateContractsOutput": false, + "parameterDateTimeFormat": "s", + "generateUpdateJsonSerializerSettingsMethod": true, + "serializeTypeInformation": false, + "queryNullValue": "", + "className": "MedicationServiceClient", + "operationGenerationMode": "MultipleClientsFromOperationId", + "generateOptionalParameters": false, + "generateJsonMethods": false, + "wrapResponses": false, + "generateResponseClasses": true, + "responseClass": "MedicationServicerResponse", + "namespace": "lib_vau_csharp_test.EpaApiClients.Medication", + "requiredPropertiesMustBeDefined": true, + "dateType": "System.DateTime", + "dateTimeType": "System.DateTime", + "timeType": "System.TimeSpan", + "timeSpanType": "System.TimeSpan", + "generateDefaultValues": true, + "generateDataAnnotations": true, + "excludedTypeNames": [], + "handleReferences": false, + "generateImmutableArrayProperties": false, + "generateImmutableDictionaryProperties": false, + "output": "MedicationServiceClient.cs", + "jsonLibrary": "SystemTextJson", + "jsonSerializerSettingsTransformationMethod": null + } + } +} \ No newline at end of file diff --git a/lib-vau-csharp-test/VauClientTest.GetMedicationListPdf.verified.txt b/lib-vau-csharp-test/VauClientTest.GetMedicationListPdf.verified.txt new file mode 100644 index 0000000..cf42f03 --- /dev/null +++ b/lib-vau-csharp-test/VauClientTest.GetMedicationListPdf.verified.txt @@ -0,0 +1,100 @@ +{ + Information: { + Producer: iText® 5.5.13.4 ©2000-2024 iText Group NV (AGPL-version), + Title: Medikationsliste, + CreationDate: DateTimeOffset_1, + ModifiedDate: DateTimeOffset_1 + }, + Pages: [ + { + Rotation: { + Value: 90, + SwapsAxis: true, + Radians: -1.5707963267949 + }, + Text: +Verordnung +sdatum +Dispensierd +atum +Wirkstoffname Wirkst +ärke +Arzneimittelbez +eichnung +Form Dosiera +ngabe/ +Gebrau +chsanw +eisung +PZN Verordner abgebende +Apotheke + +01.07.2024 22.07.2024 - 03953522 +Metoprolol- +ratiopharm® +100 mg +Tabletten +TAB 1-0-1 03953522 Dr. Max +Manfred +Mustermann +Arztpraxis Dr. +Mustermann +Arztpraxis Dr. +Mustermann + +01.07.2024 25.07.2024 +Ibuprofen +(substance) +400 mg 10019621 +IBU-ratiopharm +400mg akut +Schmerztablette +n +Ibuprofen +(substance) +TAB 1-0-1 10019621 Dr. Max +Manfred +Mustermann +Arztpraxis Dr. +Mustermann +Arztpraxis Dr. +Mustermann + +13.01.2024 14.01.2024 - 10019621 +IBU-ratiopharm +400mg akut +Schmerztablette +n +1-0-1 10019621 Dr. Max +Manfred +Mustermann +Arztpraxis Dr. +Mustermann +Arztpraxis Dr. +Mustermann + +12.01.2024 16.02.2024 +Doxorubicin +85 mg +Doxorubicin +112100 +00 +1-0-1 Dr. Max +Manfred +Mustermann +Arztpraxis Dr. +Mustermann +Arztpraxis Dr. +Mustermann + +01.01.2024 17.01.2024 - 1-0-1 Dr. Max +Manfred +Mustermann +Arztpraxis Dr. +Mustermann +Arztpraxis Dr. +Mustermann + + } + ] +} \ No newline at end of file diff --git a/lib-vau-csharp-test/VauClientTest.cs b/lib-vau-csharp-test/VauClientTest.cs index a32b584..1b92f38 100644 --- a/lib-vau-csharp-test/VauClientTest.cs +++ b/lib-vau-csharp-test/VauClientTest.cs @@ -4,13 +4,20 @@ using System.Threading.Tasks; using lib_vau_csharp; + using lib_vau_csharp_test.EpaApiClients.Auth; using lib_vau_csharp_test.EpaApiClients.EntitlementManagement; +using Mauve.Erezept.API.EpaServiceClients.MedicationService; + using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; +using VerifyNUnit; + +using VerifyTests; + using ErrorType = lib_vau_csharp_test.EpaApiClients.EntitlementManagement.ErrorType; namespace lib_vau_csharp_test @@ -20,6 +27,9 @@ public class VauClientTest { private VauClient vauClient; + [OneTimeSetUp] + public void InitVerifyPdfPig() => VerifyPdfPig.Initialize(); + [SetUp] public void Setup() { @@ -64,12 +74,12 @@ public void UsageWithIHttpClientFactory() services.AddSingleton(); services.AddHttpClient("VAU").ConfigurePrimaryHttpMessageHandler(); services.AddTransient(sp => - { - var httpClientFactory = sp.GetService(); - var httpClient = httpClientFactory.CreateClient("VAU"); - httpClient.BaseAddress = Constants.EpaDeploymentUrl; - return ActivatorUtilities.CreateInstance(sp, httpClient); - }); + { + var httpClientFactory = sp.GetService(); + var httpClient = httpClientFactory.CreateClient("VAU"); + httpClient.BaseAddress = Constants.EpaDeploymentUrl; + return ActivatorUtilities.CreateInstance(sp, httpClient); + }); var sp = services.BuildServiceProvider(); @@ -85,10 +95,23 @@ public void ThrowsInvalidOperationExceptionIfHandshakeWasNotPerformed(Func Assert.ThrowsAsync(() => method(), $"Expected method {methodName} to throw an InvalidOperationException."); } + [Test(Description = "Expects medication data to be imported.")] + public async Task GetMedicationListPdf() + { + var vauHttpClientHandler = new VauHttpClientHandler(new ReturnInstanceVauClientProvider(vauClient, true)); + var httpClient = new HttpClient(vauHttpClientHandler) { BaseAddress = Constants.EpaDeploymentUrl }; + + var medicationServiceClient = new MedicationServiceClient(httpClient); + + using FileResponse response = await medicationServiceClient.RenderEMLAsPDFAsync(Guid.NewGuid(), "Z123456783", "Test/1.0"); + + await Verifier.Verify(response.Stream, "pdf"); + } + private static IEnumerable ThrowingMethods() { var client = new VauClient(new HttpClient()); - + yield return new TestCaseData(() => client.DecryptResponse(new HttpResponseMessage()), nameof(client.DecryptResponse)); yield return new TestCaseData(() => client.EncryptRequest(new HttpRequestMessage { RequestUri = new Uri("https://example.com") }), nameof(client.EncryptRequest)); yield return new TestCaseData(() => client.GetStatus(), nameof(client.GetStatus)); diff --git a/lib-vau-csharp-test/lib-vau-csharp-test.csproj b/lib-vau-csharp-test/lib-vau-csharp-test.csproj index de25cba..6f775dc 100644 --- a/lib-vau-csharp-test/lib-vau-csharp-test.csproj +++ b/lib-vau-csharp-test/lib-vau-csharp-test.csproj @@ -39,6 +39,8 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + diff --git a/lib-vau-csharp/VauClient.cs b/lib-vau-csharp/VauClient.cs index 56521a3..f6c7dcd 100644 --- a/lib-vau-csharp/VauClient.cs +++ b/lib-vau-csharp/VauClient.cs @@ -34,12 +34,12 @@ namespace lib_vau_csharp public class VauClient { private static readonly JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.KebabCaseUpper }; - + private readonly HttpClient httpClient; private readonly VauClientStateMachine vauClientStateMachine; public AbstractVauStateMachine VauStateMachine => vauClientStateMachine; - + public ConnectionId ConnectionId { get; private set; } /// @@ -62,7 +62,7 @@ public async Task DoHandshake() { if (ConnectionId != null) throw new InvalidOperationException("Connection has already been established."); - + byte[] message3Encoded = await DoHandShakeStage1(); await DoHandShakeStage2(message3Encoded); } @@ -94,9 +94,9 @@ public async Task SendMessage(byte[] message) content.Headers.ContentType = MediaTypeHeader.Octet; var response = await httpClient.PostAsync(ConnectionId.Cid, content).ConfigureAwait(false); byte[] serverMessageEncoded = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); - string responseMessage = Encoding.UTF8.GetString(vauClientStateMachine.DecryptVauMessage(serverMessageEncoded)); - - VauResponse.Parse(responseMessage, response); + var decryptedResponse = vauClientStateMachine.DecryptVauMessage(serverMessageEncoded); + + VauResponse.Parse(decryptedResponse, response); return response; } @@ -107,7 +107,7 @@ public async Task SendMessage(byte[] message) /// /// Thrown in case the current instance is not connected to a VAU. public async Task EncryptRequest(HttpRequestMessage httpRequest) => await EncryptRequest(httpRequest, httpRequest.RequestUri).ConfigureAwait(false); - + /// /// Encrypts the given to send to the VAU using the provided . /// @@ -150,19 +150,18 @@ public async Task DecryptResponse(HttpResponseMessage response) EnsureConnected(); byte[] encryptedResponse = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); - - string decryptedResponse = Encoding.UTF8.GetString(vauClientStateMachine.DecryptVauMessage(encryptedResponse)); - + byte[] decryptedResponse = vauClientStateMachine.DecryptVauMessage(encryptedResponse); + VauResponse.Parse(decryptedResponse, response); } - + private async Task DoHandShakeStage1() { var message1Encoded = vauClientStateMachine.generateMessage1(); var content = new ByteArrayContent(message1Encoded); content.Headers.ContentType = MediaTypeHeader.Cbor; - + using var response = await httpClient.PostAsync("VAU", content).ConfigureAwait(false); var message2Encoded = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); @@ -194,7 +193,7 @@ private void EnsureConnected() throw new InvalidOperationException($"No connection has been established, call {nameof(DoHandshake)} first."); } } - + public record VauStatus(string VauType, string VauVersion, string UserAuthentication, [property: JsonPropertyName("KeyID")] string KeyId, string ConnectionStart) { public bool IsTelematikIdAuthenticated(string telematikId) => UserAuthentication.Contains(telematikId); diff --git a/lib-vau-csharp/VauResponse.cs b/lib-vau-csharp/VauResponse.cs index 8c83157..993590b 100644 --- a/lib-vau-csharp/VauResponse.cs +++ b/lib-vau-csharp/VauResponse.cs @@ -13,9 +13,12 @@ */ using System; -using System.Linq; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.IO; using System.Net; using System.Net.Http; +using System.Text; using lib_vau_csharp.util; @@ -26,6 +29,8 @@ public class VauResponse private const int StatusCodeIndex = 1; private const int ReasonPhraseIndex = 2; + private const int CrLfLength = 2; + private static readonly char[] HeaderSplit = [':']; /// @@ -34,54 +39,70 @@ public class VauResponse /// /// /// - public static void Parse(string decryptedResponse, HttpResponseMessage httpResponseMessage) + public static void Parse(byte[] decryptedResponse, HttpResponseMessage httpResponseMessage) { if (decryptedResponse == null) throw new ArgumentNullException(nameof(decryptedResponse)); if (httpResponseMessage == null) throw new ArgumentNullException(nameof(httpResponseMessage)); - var lines = decryptedResponse.ReadLines().ToList(); + using var memoryStream = new MemoryStream(decryptedResponse); + using var reader = new StreamReader(memoryStream); + + int bytesRead = 0; //Keep track of the number of bytes read from the stream to read the content later, since not all responses contain a 'Content-Length-ä header which we could use otherwise + int i = 0; - int contentIndex = 0; + var contentHeaders = new Dictionary(); - for (int i = 0; i < lines.Count; i++) + while (bytesRead < memoryStream.Length) { - string line = lines[i]; - if (i == 0) + string line = reader.ReadLine(); + bytesRead += Encoding.UTF8.GetByteCount(line) + CrLfLength; + + if (i++ == 0) { if (line.StartsWith("HTTP")) { - string[] status = lines[0].Split(' '); + string[] status = line.Split(' '); if (Enum.TryParse(status[StatusCodeIndex], true, out HttpStatusCode statusCode)) httpResponseMessage.StatusCode = statusCode; - httpResponseMessage.ReasonPhrase = status[ReasonPhraseIndex]; - } - else - { - //Not sure if we can get here in a production env, the TestSendingMessagesThroughChannel test expects this work though - break; + httpResponseMessage.ReasonPhrase = status[ReasonPhraseIndex]; + continue; } + + //Not sure if we can get here in a production env, the TestSendingMessagesThroughChannel test expects this work though + break; } if (String.IsNullOrWhiteSpace(line)) { - contentIndex = i + 1; break; } string[] headerNameValue = line.Split(HeaderSplit, 2); string name = headerNameValue[0].Trim(); - if (HttpResponseHeaderNames.All.Contains(name)) + if (HttpResponseHeaderNames.IsContentHeader(name)) + { + contentHeaders.Add(name, headerNameValue[1].Trim()); + } + else if (HttpResponseHeaderNames.All.Contains(name)) { string value = headerNameValue[1].Trim(); httpResponseMessage.Headers.Add(name, value); } } - httpResponseMessage.Content = contentIndex < lines.Count ? new StringContent(String.Join(String.Empty, lines.Skip(contentIndex))) : null; + long contentSize = memoryStream.Length - bytesRead; + if (contentSize <= 0) + return; + + httpResponseMessage.Content = new ByteArrayContent(decryptedResponse, bytesRead, (int)contentSize); + foreach (var contentHeader in contentHeaders) + { + httpResponseMessage.Content.Headers.Add(contentHeader.Key, contentHeader.Value.Trim()); + } } } } \ No newline at end of file diff --git a/lib-vau-csharp/util/Extensions.cs b/lib-vau-csharp/util/Extensions.cs deleted file mode 100644 index 82360b0..0000000 --- a/lib-vau-csharp/util/Extensions.cs +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.IO; - -namespace lib_vau_csharp.util -{ - internal static class Extensions - { - internal static IEnumerable ReadLines(this string text) - { - var reader = new StringReader(text ?? String.Empty); - while (reader.ReadLine() is { } line) - { - yield return line; - } - } - } -} \ No newline at end of file diff --git a/lib-vau-csharp/util/HttpResponseHeaderNames.cs b/lib-vau-csharp/util/HttpResponseHeaderNames.cs index e6a17fd..0d429a5 100644 --- a/lib-vau-csharp/util/HttpResponseHeaderNames.cs +++ b/lib-vau-csharp/util/HttpResponseHeaderNames.cs @@ -3,6 +3,7 @@ * Licensed under CC BY-SA 3.0: https://creativecommons.org/licenses/by-sa/3.0/ */ +using System; using System.Collections.Generic; using System.Linq; @@ -13,7 +14,9 @@ namespace lib_vau_csharp.util /// internal static class HttpResponseHeaderNames { - public static readonly HashSet All = new HashSet(typeof(HttpResponseHeaderNames).GetFields().Select(p => p.Name)); + public static readonly HashSet All = new HashSet(typeof(HttpResponseHeaderNames).GetFields().Select(p => p.GetValue(null) as string)); + + public static bool IsContentHeader(string headerName) => headerName.StartsWith("Content", StringComparison.OrdinalIgnoreCase); ///What partial content range types this server supports public const string AcceptRanges = "Accept-Ranges"; From 0998c25a65f70a155b105bead07845475f240c74 Mon Sep 17 00:00:00 2001 From: dennis-gr Date: Wed, 12 Nov 2025 14:22:51 +0100 Subject: [PATCH 4/8] Removed AssemblyInfo, since InternalsVisibleTo can be defined in .csproj Restored heders --- lib-vau-csharp-test/EpaDeploymentTest.cs | 2 ++ lib-vau-csharp-test/HandShakeTests.cs | 2 ++ lib-vau-csharp/Properties/AssemblyInfo.cs | 22 ---------------------- lib-vau-csharp/lib-vau-csharp.csproj | 2 +- 4 files changed, 5 insertions(+), 23 deletions(-) delete mode 100644 lib-vau-csharp/Properties/AssemblyInfo.cs diff --git a/lib-vau-csharp-test/EpaDeploymentTest.cs b/lib-vau-csharp-test/EpaDeploymentTest.cs index 2f1078e..486f0bf 100644 --- a/lib-vau-csharp-test/EpaDeploymentTest.cs +++ b/lib-vau-csharp-test/EpaDeploymentTest.cs @@ -12,6 +12,8 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. + * + * For additional notes and disclaimer from gematik and in case of changes by gematik find details in the "Readme" file. */ using lib_vau_csharp; diff --git a/lib-vau-csharp-test/HandShakeTests.cs b/lib-vau-csharp-test/HandShakeTests.cs index 2832ffe..31a6678 100644 --- a/lib-vau-csharp-test/HandShakeTests.cs +++ b/lib-vau-csharp-test/HandShakeTests.cs @@ -12,6 +12,8 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. + * + * For additional notes and disclaimer from gematik and in case of changes by gematik find details in the "Readme" file. */ using lib_vau_csharp; diff --git a/lib-vau-csharp/Properties/AssemblyInfo.cs b/lib-vau-csharp/Properties/AssemblyInfo.cs deleted file mode 100644 index 309662c..0000000 --- a/lib-vau-csharp/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,22 +0,0 @@ - -/* - * Copyright 2025 gematik GmbH - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * For additional notes and disclaimer from gematik and in case of changes by gematik find details in the "Readme" file. - */ - -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("lib-vau-csharp-test")] diff --git a/lib-vau-csharp/lib-vau-csharp.csproj b/lib-vau-csharp/lib-vau-csharp.csproj index 1b71ac1..0cacebe 100644 --- a/lib-vau-csharp/lib-vau-csharp.csproj +++ b/lib-vau-csharp/lib-vau-csharp.csproj @@ -13,7 +13,7 @@ - + From 2f80b5e6bc20f738a67819bc1b1c68930a87be86 Mon Sep 17 00:00:00 2001 From: dennis-gr Date: Thu, 20 Nov 2025 12:59:33 +0100 Subject: [PATCH 5/8] Only add CrLf to content headers string if not empty Fixed spelling Updated test result --- .../VauClientTest.GetMedicationListPdf.verified.txt | 13 ++++--------- lib-vau-csharp/VauRequest.cs | 4 +++- lib-vau-csharp/VauResponse.cs | 2 +- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/lib-vau-csharp-test/VauClientTest.GetMedicationListPdf.verified.txt b/lib-vau-csharp-test/VauClientTest.GetMedicationListPdf.verified.txt index cf42f03..7592900 100644 --- a/lib-vau-csharp-test/VauClientTest.GetMedicationListPdf.verified.txt +++ b/lib-vau-csharp-test/VauClientTest.GetMedicationListPdf.verified.txt @@ -29,12 +29,7 @@ eisung PZN Verordner abgebende Apotheke -01.07.2024 22.07.2024 - 03953522 -Metoprolol- -ratiopharm® -100 mg -Tabletten -TAB 1-0-1 03953522 Dr. Max +01.07.2024 22.07.2024 - 1-0-1 Dr. Max Manfred Mustermann Arztpraxis Dr. @@ -73,7 +68,7 @@ Mustermann Arztpraxis Dr. Mustermann -12.01.2024 16.02.2024 +12.01.2024 17.01.2024 Doxorubicin 85 mg Doxorubicin @@ -87,7 +82,7 @@ Mustermann Arztpraxis Dr. Mustermann -01.01.2024 17.01.2024 - 1-0-1 Dr. Max +01.01.2024 16.02.2024 - 1-0-1 Dr. Max Manfred Mustermann Arztpraxis Dr. @@ -97,4 +92,4 @@ Mustermann } ] -} \ No newline at end of file +} diff --git a/lib-vau-csharp/VauRequest.cs b/lib-vau-csharp/VauRequest.cs index 1d6d677..667f045 100644 --- a/lib-vau-csharp/VauRequest.cs +++ b/lib-vau-csharp/VauRequest.cs @@ -46,12 +46,14 @@ public static async Task Create(HttpRequestMessage httpRequestMessage, U { payload = await httpRequestMessage.Content.ReadAsStringAsync().ConfigureAwait(false); contentHeaders = String.Join(CrLf, httpRequestMessage.Content.Headers.Select(x => $"{x.Key}: {x.Value.First()}")); + if (contentHeaders.Length > 0) + contentHeaders += CrLf; } string request = $"{httpRequestMessage.Method.Method} {uri.LocalPath} HTTP/{httpRequestMessage.Version}{CrLf}" + $"{headers}{CrLf}" + $"{contentHeaders}" + - $"{CrLf}{CrLf}"; + $"{CrLf}"; if (payload != null) request += payload; diff --git a/lib-vau-csharp/VauResponse.cs b/lib-vau-csharp/VauResponse.cs index 993590b..76e6d95 100644 --- a/lib-vau-csharp/VauResponse.cs +++ b/lib-vau-csharp/VauResponse.cs @@ -49,7 +49,7 @@ public static void Parse(byte[] decryptedResponse, HttpResponseMessage httpRespo using var memoryStream = new MemoryStream(decryptedResponse); using var reader = new StreamReader(memoryStream); - int bytesRead = 0; //Keep track of the number of bytes read from the stream to read the content later, since not all responses contain a 'Content-Length-ä header which we could use otherwise + int bytesRead = 0; //Keep track of the number of bytes read from the stream to read the content later, since not all responses contain a 'Content-Length' header which we could use otherwise int i = 0; var contentHeaders = new Dictionary(); From a23a1e10ce851221bf06f539bf52df0a995d5629 Mon Sep 17 00:00:00 2001 From: dennis-gr Date: Wed, 26 Nov 2025 10:24:27 +0100 Subject: [PATCH 6/8] Only try to decrypt response if status code indicates success --- lib-vau-csharp/VauHttpClientHandler.cs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/lib-vau-csharp/VauHttpClientHandler.cs b/lib-vau-csharp/VauHttpClientHandler.cs index f46d0c6..9d684a5 100644 --- a/lib-vau-csharp/VauHttpClientHandler.cs +++ b/lib-vau-csharp/VauHttpClientHandler.cs @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -43,7 +43,7 @@ public VauHttpClientHandler(IVauClientProvider vauClientProvider) { this.vauClientProvider = vauClientProvider ?? throw new ArgumentNullException(nameof(vauClientProvider)); - AllowAutoRedirect = false; + AllowAutoRedirect = false; } protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) @@ -58,9 +58,12 @@ protected override async Task SendAsync(HttpRequestMessage var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); - await vauClient.DecryptResponse(response).ConfigureAwait(false); + if (response.IsSuccessStatusCode) + { + await vauClient.DecryptResponse(response).ConfigureAwait(false); + } return response; } } -} \ No newline at end of file +} From ffa3953595d8ddf1770212ca4d59c1449cd337a8 Mon Sep 17 00:00:00 2001 From: dennis-gr Date: Tue, 16 Dec 2025 11:31:16 +0100 Subject: [PATCH 7/8] Remove "x-insurantid" header --- lib-vau-csharp/VauHttpClientHandler.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/lib-vau-csharp/VauHttpClientHandler.cs b/lib-vau-csharp/VauHttpClientHandler.cs index 9d684a5..01505e2 100644 --- a/lib-vau-csharp/VauHttpClientHandler.cs +++ b/lib-vau-csharp/VauHttpClientHandler.cs @@ -55,6 +55,7 @@ protected override async Task SendAsync(HttpRequestMessage await vauClient.EncryptRequest(request).ConfigureAwait(false); request.RequestUri = new Uri(request.RequestUri!.GetLeftPart(UriPartial.Authority) + vauClient.ConnectionId.Cid); + request.Headers.Remove("x-insurantid"); //A_25244 var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); From 6012e20fceb3a988d0c4f919db578d137e32cc2b Mon Sep 17 00:00:00 2001 From: dennis-gr Date: Tue, 16 Dec 2025 13:19:00 +0100 Subject: [PATCH 8/8] Fix build for C# 14 (overload resolution of Reverse extension method): use BinaryPrimitives.ReverseEndianness instead, pass existing array --- lib-vau-csharp/AbstractVauStateMachine.cs | 7 ++++--- lib-vau-csharp/crypto/AesGcm.cs | 10 +++++----- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/lib-vau-csharp/AbstractVauStateMachine.cs b/lib-vau-csharp/AbstractVauStateMachine.cs index 76d1cf3..0f4c7ed 100644 --- a/lib-vau-csharp/AbstractVauStateMachine.cs +++ b/lib-vau-csharp/AbstractVauStateMachine.cs @@ -21,6 +21,7 @@ using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using System; +using System.Buffers.Binary; using System.Linq; namespace lib_vau_csharp @@ -50,15 +51,15 @@ public virtual byte[] EncryptVauMessage(byte[] plaintext) byte puByte = (byte)(isPu ? 1 : 0); byte requestByte = GetRequestByte(); long requestCounter = GetRequestCounter(); - byte[] requestCounterBytes = BitConverter.GetBytes(requestCounter).Reverse().ToArray(); - byte[][] headerBytes = new byte[][] { new byte[] { versionByte }, new byte[] { puByte }, new byte[] { requestByte }, requestCounterBytes, KeyId }; + byte[] requestCounterBytes = BitConverter.GetBytes(BinaryPrimitives.ReverseEndianness(requestCounter)); + byte[][] headerBytes = [[versionByte], [puByte], [requestByte], requestCounterBytes, KeyId]; byte[] header = Arrays.ConcatenateAll(headerBytes); byte[] random = new byte[4]; new SecureRandom().NextBytes(random); AesGcm aesGcm = new AesGcm(); - aesGcm.initAESForEncryption(random, requestCounter, header, encryptionVauKey); + aesGcm.initAESForEncryption(random, requestCounterBytes, header, encryptionVauKey); byte[] ciphertext = aesGcm.encryptData(plaintext); byte[][] concatBytes = new byte[][] { header, aesGcm.ivValue, ciphertext }; byte[] bytes = Arrays.ConcatenateAll(concatBytes); diff --git a/lib-vau-csharp/crypto/AesGcm.cs b/lib-vau-csharp/crypto/AesGcm.cs index 5d150b4..23e5dd2 100644 --- a/lib-vau-csharp/crypto/AesGcm.cs +++ b/lib-vau-csharp/crypto/AesGcm.cs @@ -32,7 +32,7 @@ public class AesGcm public byte[] ivValue { get; set; } public void initAESForEncryption(byte[] random, - long lCounter, + byte[] requestCounter, byte[] assocData, byte[] key) { @@ -49,7 +49,7 @@ public void initAESForEncryption(byte[] random, } KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("AES", key); - ivValue = initializeIV(random, lCounter); + ivValue = initializeIV(random, requestCounter); var aes_parameters = new AeadParameters(keyParam, 128, ivValue, assocData); m_encCipher.Init(true, aes_parameters); m_decCipher.Init(false, aes_parameters); @@ -78,7 +78,7 @@ public void initAESForDecryption(byte[] iv, m_decCipher.Init(false, aes_parameters); } - private static byte[] initializeIV(byte[] random, long lCounter) + private static byte[] initializeIV(byte[] random, byte[] requestCounter) { // A_24628 -> 32 Bit Random + 64 Bit Verschlüsselungszähler if (random?.Length != 4) @@ -86,8 +86,8 @@ private static byte[] initializeIV(byte[] random, long lCounter) throw new ArgumentNullException(nameof(random), "Invalid random value!"); } - byte[] counter = BitConverter.GetBytes(lCounter).Reverse().ToArray(); // A_24629, A_24631 -> 64 Bit encryption counter - return random.Concat(counter).ToArray(); // A_24628 -> concat random and counter + // A_24629, A_24631 -> 64 Bit encryption counter + return random.Concat(requestCounter).ToArray(); // A_24628 -> concat random and counter } public byte[] encryptData(byte[] clearText)