repo_name
stringlengths 1
52
| repo_creator
stringclasses 6
values | programming_language
stringclasses 4
values | code
stringlengths 0
9.68M
| num_lines
int64 1
234k
|
---|---|---|---|---|
aws-sdk-net | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 Amazon.Runtime.Internal;
using Amazon.Util;
using AWSSDK.Extensions.CrtIntegration;
using Moq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Xunit;
namespace CrtIntegrationTests
{
/// <summary>
/// Tests for the mapping between the SDK's <see cref="IRequest" /> and CRT's <see cref="Aws.Crt.Http.HttpRequest"/>
/// </summary>
public class RequestConverterTests
{
[Fact]
public void ConvertToCrtRequestTest()
{
var mock = new Mock<IRequest>();
mock.SetupAllProperties();
mock.SetupGet(x => x.Headers).Returns(new Dictionary<string, string>
{
{ HeaderKeys.ContentLengthHeader, "13" },
{ HeaderKeys.ContentTypeHeader, "application/x-www-form-urlencoded"},
{ HeaderKeys.XAmzRegionSetHeader, "us-east-1" }, // should not be passed into CRT
{ HeaderKeys.XAmzSecurityTokenHeader, "token" } // should not be passed into CRT
});
var sdkRequest = mock.Object;
sdkRequest.HttpMethod = "POST";
sdkRequest.ResourcePath = "/resource";
sdkRequest.Content = Encoding.ASCII.GetBytes("Param1=value1");
sdkRequest.Endpoint = new Uri("https://amazonaws.com/");
var crtRequest = CrtHttpRequestConverter.ConvertToCrtRequest(sdkRequest);
// Verify that all expected properties made it to the CRT request
Assert.Equal("https://amazonaws.com/resource", crtRequest.Uri);
Assert.Equal("POST", crtRequest.Method);
Assert.Equal("Param1=value1", new StreamReader(crtRequest.BodyStream).ReadToEnd());
// Verify that we're correctly stripping CRT-managed headers
Assert.Equal(2, crtRequest.Headers.Length);
Assert.Equal(HeaderKeys.ContentLengthHeader, crtRequest.Headers[0].Name);
Assert.Equal("13", crtRequest.Headers[0].Value);
Assert.Equal(HeaderKeys.ContentTypeHeader, crtRequest.Headers[1].Name);
Assert.Equal("application/x-www-form-urlencoded", crtRequest.Headers[1].Value);
}
[Fact]
public void CopyHeadersFromCrtRequestTest()
{
var crtRequest = new Aws.Crt.Http.HttpRequest
{
Headers = new[]
{
new Aws.Crt.Http.HttpHeader("a", "a"),
new Aws.Crt.Http.HttpHeader("b", "b")
}
};
var mock = new Mock<IRequest>();
mock.SetupAllProperties();
mock.SetupGet(x => x.Headers).Returns(new Dictionary<string, string>
{
{ "c", "c" }, // this is only on the SDK request so we expect it to be replaced by "a" and "b" from CRT
});
var sdkRequest = mock.Object;
CrtHttpRequestConverter.CopyHeadersFromCrtRequest(sdkRequest, crtRequest);
// Verify that we've replaced the SDK request's headers with all of the CRT request's headers
Assert.Equal(2, sdkRequest.Headers.Count);
Assert.True(sdkRequest.Headers.ContainsKey("a"));
Assert.True(sdkRequest.Headers.ContainsKey("b"));
Assert.Equal("a", sdkRequest.Headers["a"]);
Assert.Equal("b", sdkRequest.Headers["b"]);
}
[Fact]
public void ExtractSignedHeadersTest()
{
var crtRequest = new Aws.Crt.Http.HttpRequest();
crtRequest.Headers = new Aws.Crt.Http.HttpHeader[]
{
new Aws.Crt.Http.HttpHeader("a", "a"),
new Aws.Crt.Http.HttpHeader("Authorization", "AWS4-ECDSA-P256-SHA256 Credential=accesskey/20210101/s3/aws4_request, " +
"SignedHeaders=host;x-amz-content-sha256;x-amz-date;x-amz-region-set;x-amz-security-token, Signature=signature"),
new Aws.Crt.Http.HttpHeader("b", "b"),
};
var signedHeaders = CrtHttpRequestConverter.ExtractSignedHeaders(crtRequest);
// Verify that we can extract the signed headers out of the CRT's 'Authorization' header,
// since we may use them directly later in the SDK
Assert.Equal("host;x-amz-content-sha256;x-amz-date;x-amz-region-set;x-amz-security-token", signedHeaders);
}
}
}
| 118 |
aws-sdk-net | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 Amazon;
using Amazon.Extensions.CrtIntegration;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using Aws.Crt.Auth;
using Moq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Xunit;
namespace CrtIntegrationTests
{
public class V4aSignerTests : IDisposable
{
private const string SigningTestAccessKeyId = "AKIDEXAMPLE";
private const string SigningTestSecretAccessKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
private readonly ImmutableCredentials SigningTestCredentials = new ImmutableCredentials(SigningTestAccessKeyId, SigningTestSecretAccessKey, "");
/* The public coordinates of the ecc key derived from the above credentials pair */
private const string SigningTestEccPubX = "b6618f6a65740a99e650b33b6b4b5bd0d43b176d721a3edfea7e7d2d56d936b1";
private const string SigningTestEccPubY = "865ed22a7eadc9c5cb9d2cbaca1b3699139fedc5043dc6661864218330c8e518";
private const string SigningTestHost = "example.amazonaws.com";
private const string SigningTestService = "service";
private const string SigningTestRegion = "us-east-1";
private static readonly DateTime SigningTestTimepoint = new DateTime(2015, 8, 30, 12, 36, 0, DateTimeKind.Utc);
private const int Chunk1Size = 65536;
private const int Chunk2Size = 1024;
public V4aSignerTests()
{
// Override the SDK's AWSConfigs.utcNowSource to return a fixed time to test predictable signatures
SetUtcNowSource(() => SigningTestTimepoint);
}
public void Dispose()
{
// Reset back to the SDK's usual GetUtcNow function
SetUtcNowSource((Func<DateTime>)Delegate.CreateDelegate(typeof(Func<DateTime>),
typeof(AWSConfigs).GetMethod("GetUtcNow", BindingFlags.Static | BindingFlags.NonPublic)));
}
static void SetUtcNowSource(Func<DateTime> source)
{
var field = typeof(AWSConfigs).GetField("utcNowSource", BindingFlags.Static | BindingFlags.NonPublic);
field.SetValue(null, source);
}
internal static IClientConfig BuildSigningClientConfig(string service)
{
return new TestClientConfig
{
UseHttp = false,
AuthenticationRegion = SigningTestRegion,
AuthenticationServiceName = service
};
}
internal AwsSigningConfig BuildDefaultSigningConfig(string service)
{
var config = new AwsSigningConfig
{
Algorithm = AwsSigningAlgorithm.SIGV4A,
SignedBodyHeader = AwsSignedBodyHeaderType.X_AMZ_CONTENT_SHA256,
SignatureType = AwsSignatureType.HTTP_REQUEST_VIA_HEADERS,
Region = SigningTestRegion,
Service = service,
Timestamp = new DateTimeOffset(SigningTestTimepoint),
Credentials = new Credentials(SigningTestAccessKeyId, SigningTestSecretAccessKey, "")
};
if (service == "s3")
{
config.UseDoubleUriEncode = false;
config.ShouldNormalizeUriPath = false;
}
else
{
config.UseDoubleUriEncode = true;
config.ShouldNormalizeUriPath = true;
}
return config;
}
#region HTTP signing with headers
internal static IRequest BuildHeaderRequestToSign(string resourcePath)
{
var mock = new Mock<IRequest>();
mock.SetupAllProperties();
var headers = new Dictionary<string, string>
{
{ "Content-Length", "13" },
{ "Content-Type", "application/x-www-form-urlencoded"},
};
var pathResources = new Dictionary<string, string>();
mock.SetupGet(x => x.Headers).Returns(headers);
mock.SetupGet(x => x.PathResources).Returns(pathResources);
IRequest request = mock.Object;
request.HttpMethod = "POST";
request.ResourcePath = resourcePath;
request.MarshallerVersion = 2;
request.Content = Encoding.ASCII.GetBytes("Param1=value1");
request.Endpoint = new Uri("https://" + SigningTestHost + "/");
return request;
}
internal string GetExpectedCanonicalRequestForHeaderSigningTest(string canonicalizedResourePath)
{
return String.Join('\n',
"POST",
canonicalizedResourePath,
"",
"content-length:13",
"content-type:application/x-www-form-urlencoded",
"host:example.amazonaws.com",
"x-amz-content-sha256:9095672bbd1f56dfc5b65f3e153adc8731a4a654192329106275f4c7b24d0b6e",
"x-amz-date:20150830T123600Z",
"x-amz-region-set:us-east-1",
"",
"content-length;content-type;host;x-amz-content-sha256;x-amz-date;x-amz-region-set",
"9095672bbd1f56dfc5b65f3e153adc8731a4a654192329106275f4c7b24d0b6e");
}
[Theory]
[InlineData(SigningTestService, "", "/")]
[InlineData(SigningTestService, "foo$*[]!()bar", "/foo%2524%252A%255B%255D%2521%2528%2529bar")]
[InlineData(SigningTestService, "foo bar", "/foo%2520bar")]
[InlineData(SigningTestService, "foo/bar", "/foo/bar")]
[InlineData(SigningTestService, "foo%2Fbar", "/foo%25252Fbar")]
[InlineData(SigningTestService, "foo\\bar", "/foo%255Cbar")]
[InlineData(SigningTestService, "foo&bar", "/foo%2526bar")]
[InlineData(SigningTestService, "my-object//example//photo.user", "/my-object/example/photo.user")] // should normalize
//
// Test S3 specifically since it has slightly different behavior due to UseDoubleUriEncode and ShouldNormalizeUriPath being false
//
[InlineData("s3", "", "/")]
[InlineData("s3", "foo$*[]!()bar", "/foo%24%2A%5B%5D%21%28%29bar")]
[InlineData("s3", "foo bar", "/foo%20bar")]
[InlineData("s3", "foo%2Fbar", "/foo%252Fbar")]
[InlineData("s3", "foo/bar", "/foo/bar")]
[InlineData("s3", "foo\\bar", "/foo%5Cbar")]
[InlineData("s3", "foo&bar", "/foo%26bar")]
[InlineData("s3", "my-object//example//photo.user", "/my-object//example//photo.user")] // should not normalize
public void SignRequestViaHeadersWithSigv4a(string service, string resourcePath, string canonicalizedResourcePath)
{
var signer = new CrtAWS4aSigner();
var request = BuildHeaderRequestToSign(resourcePath);
request.UseDoubleEncoding = service != "s3";
var clientConfig = BuildSigningClientConfig(service);
var result = signer.SignRequest(request, clientConfig, null, SigningTestCredentials);
string signatureValue = result.Signature;
var canonicalRequest = GetExpectedCanonicalRequestForHeaderSigningTest(canonicalizedResourcePath);
var config = BuildDefaultSigningConfig(service);
config.SignatureType = AwsSignatureType.CANONICAL_REQUEST_VIA_HEADERS;
Assert.True(AwsSigner.VerifyV4aCanonicalSigning(canonicalRequest, config, signatureValue, SigningTestEccPubX, SigningTestEccPubY));
}
#endregion
#region HTTP (pre)signing with query params
internal static IRequest BuildQueryParamRequestToSign()
{
var mock = new Mock<IRequest>();
mock.SetupAllProperties();
var headers = new Dictionary<string, string>();
mock.SetupGet(x => x.Headers).Returns(headers);
var subResources = new Dictionary<string, string>
{
{ "Param1", "value1"},
{ "Param2", "value2"}
};
mock.SetupGet(x => x.SubResources).Returns(subResources);
var request = mock.Object;
request.HttpMethod = "GET";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
request.Endpoint = new Uri("https://" + SigningTestHost + "/");
return request;
}
internal string GetExpectedCanonicalRequestForQueryParamSigningTest()
{
return String.Join('\n',
"GET",
"/",
"Param1=value1&Param2=value2&X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256&X-Amz-Credential=AKIDEXAMPLE%2F20150830%2Fservice%2Faws4_request&X-Amz-Date=20150830T123600Z&X-Amz-Region-Set=us-east-1&X-Amz-SignedHeaders=host",
"host:example.amazonaws.com",
"",
"host",
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
}
[Fact]
public void SignRequestViaQueryParamsWithSigv4a()
{
var signer = new CrtAWS4aSigner();
var request = BuildQueryParamRequestToSign();
var clientConfig = BuildSigningClientConfig("service");
var result = signer.Presign4a(request, clientConfig, null, SigningTestCredentials, "service", SigningTestRegion);
var signatureValue = result.Signature;
var canonicalRequest = GetExpectedCanonicalRequestForQueryParamSigningTest();
var config = BuildDefaultSigningConfig("service");
config.SignatureType = AwsSignatureType.CANONICAL_REQUEST_VIA_QUERY_PARAMS;
Assert.True(AwsSigner.VerifyV4aCanonicalSigning(canonicalRequest, config, signatureValue, SigningTestEccPubX, SigningTestEccPubY));
}
#endregion
#region Chunked Signing
internal IRequest BuildMockChunkedRequest()
{
var mock = new Mock<IRequest>();
mock.SetupAllProperties();
var headers = new Dictionary<string, string>
{
{ "x-amz-storage-class", "REDUCED_REDUNDANCY" },
{ "Content-Encoding", "aws-chunked" },
{ "Content-Length", (Chunk1Size + Chunk2Size).ToString() } // The SDK will adjust this and set x-amz-decoded-content-length as needed prior to CRT
};
mock.SetupGet(x => x.Headers).Returns(headers);
mock.Setup(x => x.TrailingHeaders).Returns(new Dictionary<string, string>());
mock.SetupGet(x => x.SubResources).Returns(new Dictionary<string, string>());
var request = mock.Object;
request.MarshallerVersion = 2;
request.HttpMethod = "PUT";
request.ResourcePath = "/examplebucket/chunkObject.txt";
request.Endpoint = new Uri("https://s3.amazonaws.com/");
request.UseChunkEncoding = true;
request.Content = null;
return request;
}
private MemoryStream CreateChunkStream(int streamLength)
{
return new MemoryStream(
Enumerable.Range(0, streamLength)
.Select(x => Convert.ToByte('a'))
.ToArray());
}
internal string GetExpectedCanonicalRequestForChunkedSigningTest()
{
return string.Join('\n',
"PUT",
"/examplebucket/chunkObject.txt",
"",
"content-encoding:aws-chunked",
"content-length:" + ChunkedUploadWrapperStream.ComputeChunkedContentLength(Chunk1Size + Chunk2Size, ChunkedUploadWrapperStream.V4A_SIGNATURE_LENGTH).ToString(),
"host:s3.amazonaws.com",
"x-amz-content-sha256:STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD",
"x-amz-date:20150830T123600Z",
"x-amz-decoded-content-length:" + (Chunk1Size + Chunk2Size).ToString(),
"x-amz-region-set:us-east-1",
"x-amz-storage-class:REDUCED_REDUNDANCY",
"",
"content-encoding;content-length;host;x-amz-content-sha256;x-amz-date;x-amz-decoded-content-length;x-amz-region-set;x-amz-storage-class",
"STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD");
}
internal string GetExpectedCanonicalRequestForChunkedTrailersSigningTest()
{
var trailingHeaders = new Dictionary<string, string>
{
{ "x-amz-foo", "bar" }
};
return string.Join('\n',
"PUT",
"/examplebucket/chunkObject.txt",
"",
"content-encoding:aws-chunked",
"content-length:" + ChunkedUploadWrapperStream.ComputeChunkedContentLength(Chunk1Size + Chunk2Size,
ChunkedUploadWrapperStream.V4A_SIGNATURE_LENGTH,
trailingHeaders,
CoreChecksumAlgorithm.NONE).ToString(),
"host:s3.amazonaws.com",
"x-amz-content-sha256:STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD-TRAILER",
"x-amz-date:20150830T123600Z",
"x-amz-decoded-content-length:" + (Chunk1Size + Chunk2Size).ToString(),
"x-amz-region-set:us-east-1",
"x-amz-storage-class:REDUCED_REDUNDANCY",
"x-amz-trailer:x-amz-foo",
"",
"content-encoding;content-length;host;x-amz-content-sha256;x-amz-date;x-amz-decoded-content-length;x-amz-region-set;x-amz-storage-class;x-amz-trailer",
"STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD-TRAILER");
}
private string BuildV4aChunkedStringToSignHelper(AWS4aSigningResult headerResult, string previousSignature, int chunkSize)
{
return ChunkedUploadWrapperStream.BuildChunkedStringToSign(
"AWS4-ECDSA-P256-SHA256-PAYLOAD",
headerResult.ISO8601DateTime,
headerResult.Scope,
previousSignature.TrimEnd('*'),
chunkSize,
CreateChunkStream(chunkSize).ToArray());
}
private string BuildV4aTrailerChunkHelper(AWS4aSigningResult headerResult, string previousSignature, IDictionary<string, string> trailingHeaders)
{
return string.Join('\n',
"AWS4-ECDSA-P256-SHA256-TRAILER",
headerResult.ISO8601DateTime,
headerResult.Scope,
previousSignature.TrimEnd('*'),
AWSSDKUtils.ToHex(AWS4Signer.ComputeHash("x-amz-foo:bar\n"), true));
}
/// <summary>
/// Tests that the SigV4a signature is valid for each chunk of a request,
/// by comparing against the signature of a handwritten canonical chunk.
/// </summary>
[Fact]
public void TestChunkedRequest()
{
var signer = new CrtAWS4aSigner();
var request = BuildMockChunkedRequest();
var clientConfig = BuildSigningClientConfig(SigningTestService);
var headerResult = signer.SignRequest(request, clientConfig, null, SigningTestCredentials);
var config = BuildDefaultSigningConfig(SigningTestService);
config.SignatureType = AwsSignatureType.CANONICAL_REQUEST_VIA_HEADERS;
config.SignedBodyValue = AWS4Signer.V4aStreamingBodySha256;
Assert.True(AwsSigner.VerifyV4aCanonicalSigning(GetExpectedCanonicalRequestForChunkedSigningTest(),
config, headerResult.Signature, SigningTestEccPubX, SigningTestEccPubY));
var chunk1Result = signer.SignChunk(CreateChunkStream(Chunk1Size), headerResult.Signature, headerResult);
Assert.True(AwsSigner.VerifyV4aSignature(BuildV4aChunkedStringToSignHelper(headerResult, headerResult.Signature, Chunk1Size),
Encoding.ASCII.GetBytes(chunk1Result), SigningTestEccPubX, SigningTestEccPubY));
var chunk2Result = signer.SignChunk(CreateChunkStream(Chunk2Size), chunk1Result, headerResult);
Assert.True(AwsSigner.VerifyV4aSignature(BuildV4aChunkedStringToSignHelper(headerResult, chunk1Result, Chunk2Size),
Encoding.ASCII.GetBytes(chunk2Result), SigningTestEccPubX, SigningTestEccPubY));
var chunk3Result = signer.SignChunk(null, chunk2Result, headerResult);
Assert.True(AwsSigner.VerifyV4aSignature(BuildV4aChunkedStringToSignHelper(headerResult, chunk2Result, 0),
Encoding.ASCII.GetBytes(chunk3Result), SigningTestEccPubX, SigningTestEccPubY));
}
/// <summary>
/// Tests that the SigV4a signature is valid for each chunk of a request with
/// trailing headers, by comparing against the signature of a handwritten
/// canonical chunk.
/// </summary>
[Fact]
public void TestChunkedRequestWithTrailingHeaders()
{
var signer = new CrtAWS4aSigner();
var request = BuildMockChunkedRequest();
request.TrailingHeaders.Add("x-amz-foo", "bar");
var clientConfig = BuildSigningClientConfig(SigningTestService);
var headerResult = signer.SignRequest(request, clientConfig, null, SigningTestCredentials);
var config = BuildDefaultSigningConfig(SigningTestService);
config.SignatureType = AwsSignatureType.CANONICAL_REQUEST_VIA_HEADERS;
config.SignedBodyValue = AWS4Signer.V4aStreamingBodySha256WithTrailer;
Assert.True(AwsSigner.VerifyV4aCanonicalSigning(GetExpectedCanonicalRequestForChunkedTrailersSigningTest(),
config, headerResult.Signature, SigningTestEccPubX, SigningTestEccPubY));
var chunk1Result = signer.SignChunk(CreateChunkStream(Chunk1Size), headerResult.Signature, headerResult);
Assert.True(AwsSigner.VerifyV4aSignature(BuildV4aChunkedStringToSignHelper(headerResult, headerResult.Signature, Chunk1Size),
Encoding.ASCII.GetBytes(chunk1Result), SigningTestEccPubX, SigningTestEccPubY));
var chunk2Result = signer.SignChunk(CreateChunkStream(Chunk2Size), chunk1Result, headerResult);
Assert.True(AwsSigner.VerifyV4aSignature(BuildV4aChunkedStringToSignHelper(headerResult, chunk1Result, Chunk2Size),
Encoding.ASCII.GetBytes(chunk2Result), SigningTestEccPubX, SigningTestEccPubY));
var chunk3Result = signer.SignChunk(null, chunk2Result, headerResult);
Assert.True(AwsSigner.VerifyV4aSignature(BuildV4aChunkedStringToSignHelper(headerResult, chunk2Result, 0),
Encoding.ASCII.GetBytes(chunk3Result), SigningTestEccPubX, SigningTestEccPubY));
var trailerChunkResult = signer.SignTrailingHeaderChunk(request.TrailingHeaders, chunk3Result, headerResult);
Assert.True(AwsSigner.VerifyV4aSignature(BuildV4aTrailerChunkHelper(headerResult, chunk3Result, request.TrailingHeaders),
Encoding.ASCII.GetBytes(trailerChunkResult), SigningTestEccPubX, SigningTestEccPubY));
}
#endregion
}
}
| 437 |
aws-sdk-net | aws | C# | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CrtIntegrationTests")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3AE7EFD9-03B2-46D9-A1BF-4DB92691027F")]
| 20 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Xunit;
using Amazon;
using Amazon.S3;
using Amazon.Runtime;
namespace NETCore.SetupTests
{
public class ConfigurationTests
{
public ConfigurationTests()
{
}
[Fact]
public void GetProfileAndRegion()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("./TestFiles/GetProfileAndRegionTest.json");
IConfiguration config = builder.Build();
var options = config.GetAWSOptions();
Assert.Equal(RegionEndpoint.USWest2, options.Region);
Assert.Equal("myProfile", options.Profile);
Assert.Equal("myProfileLocation", options.ProfilesLocation);
IAmazonS3 client = options.CreateServiceClient<IAmazonS3>();
Assert.NotNull(client);
Assert.Equal(RegionEndpoint.USWest2, client.Config.RegionEndpoint);
}
[Fact]
public void GetRoleNameAndSessionName()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("./TestFiles/GetRoleNameAndSessionNameTest.json");
IConfiguration config = builder.Build();
var options = config.GetAWSOptions();
Assert.Equal(RegionEndpoint.USWest2, options.Region);
Assert.Equal("arn:aws:iam::123456789012:role/fake_role", options.SessionRoleArn);
Assert.Equal("TestSessionName", options.SessionName);
IAmazonS3 client = options.CreateServiceClient<IAmazonS3>();
Assert.NotNull(client);
Assert.Equal(RegionEndpoint.USWest2, client.Config.RegionEndpoint);
}
[Fact]
public void LegacyNamesTest()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("./TestFiles/LegacyNamesTest.json");
IConfiguration config = builder.Build();
var options = config.GetAWSOptions();
Assert.Equal(RegionEndpoint.USWest2, options.Region);
Assert.Equal("myProfile", options.Profile);
Assert.Equal("myProfileLocation", options.ProfilesLocation);
IAmazonS3 client = options.CreateServiceClient<IAmazonS3>();
Assert.NotNull(client);
Assert.Equal(RegionEndpoint.USWest2, client.Config.RegionEndpoint);
}
[Fact]
public void NonDefaultSectionTest()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("./TestFiles/NonDefaultSectionTest.json");
IConfiguration config = builder.Build();
var options = config.GetAWSOptions("AWSNonStandard");
Assert.Equal(RegionEndpoint.EUCentral1, options.Region);
IAmazonS3 client = options.CreateServiceClient<IAmazonS3>();
Assert.NotNull(client);
Assert.Equal(RegionEndpoint.EUCentral1, client.Config.RegionEndpoint);
}
[Fact]
public void GetClientConfigSettingsTest()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("./TestFiles/GetClientConfigSettingsTest.json");
IConfiguration config = builder.Build();
var options = config.GetAWSOptions();
Assert.Equal(RegionEndpoint.USWest2, options.Region);
Assert.True(options.DefaultClientConfig.UseHttp);
Assert.Equal(6, options.DefaultClientConfig.MaxErrorRetry);
Assert.Equal(TimeSpan.FromMilliseconds(1000), options.DefaultClientConfig.Timeout);
Assert.Equal("us-east-1", options.DefaultClientConfig.AuthenticationRegion);
Assert.Equal(DefaultConfigurationMode.Standard, options.DefaultConfigurationMode);
Assert.Equal(RequestRetryMode.Standard, options.DefaultClientConfig.RetryMode);
IAmazonS3 client = options.CreateServiceClient<IAmazonS3>();
Assert.NotNull(client);
Assert.Equal(RegionEndpoint.USWest2, client.Config.RegionEndpoint);
Assert.True(client.Config.UseHttp);
Assert.Equal(6, client.Config.MaxErrorRetry);
Assert.Equal(TimeSpan.FromMilliseconds(1000), client.Config.Timeout);
Assert.Equal("us-east-1", client.Config.AuthenticationRegion);
Assert.Equal(DefaultConfigurationMode.Standard, client.Config.DefaultConfigurationMode);
Assert.Equal(RequestRetryMode.Standard, client.Config.RetryMode);
// Verify that setting the standard mode doesn't override explicit settings of retry mode to a non-legacy mode.
options.DefaultClientConfig.RetryMode = RequestRetryMode.Adaptive;
client = options.CreateServiceClient<IAmazonS3>();
Assert.Equal(DefaultConfigurationMode.Standard, client.Config.DefaultConfigurationMode);
Assert.Equal(RequestRetryMode.Adaptive, client.Config.RetryMode);
// verify S3 config specific settings are not configured
var clientConfig = client.Config as AmazonS3Config;
Assert.NotNull(clientConfig);
Assert.False(clientConfig.ForcePathStyle);
}
[Fact]
public void GetClientConfigSettingsCaseInsensitiveTest()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("./TestFiles/GetClientConfigSettingsCaseInsensitiveTest.json");
IConfiguration config = builder.Build();
var options = config.GetAWSOptions();
Assert.True(options.DefaultClientConfig.UseHttp);
Assert.Equal(6, options.DefaultClientConfig.MaxErrorRetry);
Assert.Equal(TimeSpan.FromMilliseconds(1000), options.DefaultClientConfig.Timeout);
Assert.Equal("us-east-1", options.DefaultClientConfig.AuthenticationRegion);
Assert.Equal(DefaultConfigurationMode.Standard, options.DefaultConfigurationMode);
Assert.Equal("https://localhost:9021", options.DefaultClientConfig.ServiceURL);
IAmazonS3 client = options.CreateServiceClient<IAmazonS3>();
Assert.NotNull(client);
Assert.True(client.Config.UseHttp);
Assert.Equal(6, client.Config.MaxErrorRetry);
Assert.Equal(TimeSpan.FromMilliseconds(1000), client.Config.Timeout);
Assert.Equal("us-east-1", client.Config.AuthenticationRegion);
Assert.Equal(DefaultConfigurationMode.Standard, client.Config.DefaultConfigurationMode);
Assert.Equal(RequestRetryMode.Standard, client.Config.RetryMode);
Assert.Equal("https://localhost:9021", client.Config.ServiceURL);
// Verify that setting the standard mode doesn't override explicit settings of retry mode to a non-legacy mode.
options.DefaultClientConfig.RetryMode = RequestRetryMode.Adaptive;
client = options.CreateServiceClient<IAmazonS3>();
Assert.Equal(DefaultConfigurationMode.Standard, client.Config.DefaultConfigurationMode);
Assert.Equal(RequestRetryMode.Adaptive, client.Config.RetryMode);
}
[Fact]
public void EnableLoggingTest()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("./TestFiles/EnableLoggingTest.json");
IConfiguration config = builder.Build();
var options = config.GetAWSOptions();
Assert.Equal(RegionEndpoint.USWest2, options.Region);
Assert.Equal(LoggingOptions.Console, options.Logging.LogTo);
Assert.Equal(ResponseLoggingOption.OnError, options.Logging.LogResponses);
Assert.Equal(2000, options.Logging.LogResponsesSizeLimit);
Assert.True(options.Logging.LogMetrics);
// Create first service client to force logging settings to be applied
IAmazonS3 client = options.CreateServiceClient<IAmazonS3>();
Assert.NotNull(client);
Assert.Equal(RegionEndpoint.USWest2, client.Config.RegionEndpoint);
Assert.Equal(LoggingOptions.Console, AWSConfigs.LoggingConfig.LogTo);
Assert.Equal(ResponseLoggingOption.OnError, AWSConfigs.LoggingConfig.LogResponses);
Assert.Equal(2000, AWSConfigs.LoggingConfig.LogResponsesSizeLimit);
Assert.True(AWSConfigs.LoggingConfig.LogMetrics);
}
[Fact]
public void TestRegionFoundFromEnvironmentVariable()
{
var existingValue = Environment.GetEnvironmentVariable("AWS_REGION");
try
{
FallbackRegionFactory.Reset();
Environment.SetEnvironmentVariable("AWS_REGION", RegionEndpoint.APSouth1.SystemName);
var builder = new ConfigurationBuilder();
IConfiguration config = builder.Build();
var options = config.GetAWSOptions();
IAmazonS3 client = options.CreateServiceClient<IAmazonS3>();
Assert.Equal(RegionEndpoint.APSouth1, client.Config.RegionEndpoint);
}
finally
{
Environment.SetEnvironmentVariable("AWS_REGION", existingValue);
FallbackRegionFactory.Reset();
}
}
[Fact]
public void ClientConfigTypeOverloadTest()
{
var config = new ConfigurationBuilder()
.AddJsonFile("./TestFiles/GetClientConfigSettingsTest.json")
.Build();
var options = config.GetAWSOptions<AmazonS3Config>();
Assert.Equal(RegionEndpoint.USWest2, options.Region);
Assert.True(options.DefaultClientConfig.UseHttp);
Assert.Equal(6, options.DefaultClientConfig.MaxErrorRetry);
Assert.Equal(TimeSpan.FromMilliseconds(1000), options.DefaultClientConfig.Timeout);
Assert.Equal("us-east-1", options.DefaultClientConfig.AuthenticationRegion);
Assert.Equal(DefaultConfigurationMode.Standard, options.DefaultConfigurationMode);
var client = options.CreateServiceClient<IAmazonS3>();
Assert.NotNull(client);
Assert.Equal(RegionEndpoint.USWest2, client.Config.RegionEndpoint);
Assert.True(client.Config.UseHttp);
Assert.Equal(6, client.Config.MaxErrorRetry);
Assert.Equal(TimeSpan.FromMilliseconds(1000), client.Config.Timeout);
Assert.Equal("us-east-1", client.Config.AuthenticationRegion);
Assert.Equal(DefaultConfigurationMode.Standard, client.Config.DefaultConfigurationMode);
Assert.Equal(RequestRetryMode.Standard, client.Config.RetryMode);
// Verify that setting the standard mode doesn't override explicit settings of retry mode to a non-legacy mode.
options.DefaultClientConfig.RetryMode = RequestRetryMode.Adaptive;
client = options.CreateServiceClient<IAmazonS3>();
Assert.Equal(DefaultConfigurationMode.Standard, client.Config.DefaultConfigurationMode);
Assert.Equal(RequestRetryMode.Adaptive, client.Config.RetryMode);
// verify S3 config specific settings are configured
var clientConfig = client.Config as AmazonS3Config;
Assert.NotNull(clientConfig);
Assert.True(clientConfig.ForcePathStyle);
}
}
}
| 252 |
aws-sdk-net | aws | C# | using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Amazon;
using Amazon.S3;
using Amazon.Extensions.NETCore.Setup;
using Moq;
using System;
namespace DependencyInjectionTests
{
public class DependencyInjectionTests
{
[Fact]
public void InjectS3ClientWithDefaultConfig()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("./TestFiles/GetClientConfigSettingsTest.json");
IConfiguration config = builder.Build();
ServiceCollection services = new ServiceCollection();
services.AddDefaultAWSOptions(config.GetAWSOptions());
services.AddAWSService<IAmazonS3>();
var serviceProvider = services.BuildServiceProvider();
var controller = ActivatorUtilities.CreateInstance<TestController>(serviceProvider);
Assert.NotNull(controller.S3Client);
Assert.Equal(RegionEndpoint.USWest2, controller.S3Client.Config.RegionEndpoint);
}
[Fact]
public void InjectS3ClientWithoutDefaultConfig()
{
ServiceCollection services = new ServiceCollection();
services.AddAWSService<IAmazonS3>(new AWSOptions {Region = RegionEndpoint.USEast1 });
var serviceProvider = services.BuildServiceProvider();
var controller = ActivatorUtilities.CreateInstance<TestController>(serviceProvider);
Assert.NotNull(controller.S3Client);
Assert.Equal(RegionEndpoint.USEast1, controller.S3Client.Config.RegionEndpoint);
}
[Fact]
public void InjectS3ClientWithOverridingConfig()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("./TestFiles/GetClientConfigSettingsTest.json");
IConfiguration config = builder.Build();
ServiceCollection services = new ServiceCollection();
services.AddDefaultAWSOptions(config.GetAWSOptions());
services.AddAWSService<IAmazonS3>(new AWSOptions {Region = RegionEndpoint.EUCentral1 });
var serviceProvider = services.BuildServiceProvider();
var controller = ActivatorUtilities.CreateInstance<TestController>(serviceProvider);
Assert.NotNull(controller.S3Client);
Assert.Equal(RegionEndpoint.EUCentral1, controller.S3Client.Config.RegionEndpoint);
}
[Fact]
public void TryAddServiceDontOverrideWhenAlreadySetup()
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("./TestFiles/GetClientConfigSettingsTest.json");
IConfiguration config = builder.Build();
ServiceCollection services = new ServiceCollection();
var mockS3 = Mock.Of<IAmazonS3>();
services.AddSingleton(mockS3);
services.AddDefaultAWSOptions(config.GetAWSOptions());
services.TryAddAWSService<IAmazonS3>(new AWSOptions { Region = RegionEndpoint.EUCentral1 });
var serviceProvider = services.BuildServiceProvider();
var controller = ActivatorUtilities.CreateInstance<TestController>(serviceProvider);
var s3 = controller.S3Client;
Assert.NotNull(s3);
Assert.True(s3.GetType() == mockS3.GetType());
}
[Fact]
public void CreateAWSOptionsWithFunction()
{
var expectRegion = RegionEndpoint.APSouth1;
var expectProfile = "MockProfile";
var services = new ServiceCollection();
services.AddSingleton(new AWSSetting
{
Region = expectRegion,
Profile = expectProfile
});
services.AddDefaultAWSOptions(sp=> {
var setting = sp.GetRequiredService<AWSSetting>();
return new AWSOptions
{
Region = setting.Region,
Profile = setting.Profile
};
});
var serviceProvider = services.BuildServiceProvider();
var awsOptions = serviceProvider.GetRequiredService<AWSOptions>();
Assert.NotNull(awsOptions);
Assert.Equal(expectRegion, awsOptions.Region);
Assert.Equal(expectProfile, awsOptions.Profile);
}
[Fact]
public void InjectS3ClientWithFactoryBuiltConfig()
{
var expectRegion = RegionEndpoint.APSouth1;
var expectProfile = "MockProfile";
var services = new ServiceCollection();
services.AddSingleton(new AWSSetting
{
Region = expectRegion,
Profile = expectProfile
});
services.AddDefaultAWSOptions(sp => {
var setting = sp.GetRequiredService<AWSSetting>();
return new AWSOptions
{
Region = setting.Region,
Profile = setting.Profile
};
});
services.AddAWSService<IAmazonS3>();
var serviceProvider = services.BuildServiceProvider();
var controller = ActivatorUtilities.CreateInstance<TestController>(serviceProvider);
Assert.NotNull(controller.S3Client);
Assert.Equal(expectRegion, controller.S3Client.Config.RegionEndpoint);
}
public class TestController
{
public IAmazonS3 S3Client { get; private set; }
public TestController(IAmazonS3 s3Client)
{
S3Client = s3Client;
}
}
internal class AWSSetting {
public RegionEndpoint Region { get; set; }
public string Profile { get; set; }
}
}
}
| 168 |
aws-sdk-net | aws | C# | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DependencyInjectionTests")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2c63da02-eb94-443a-a986-b0e2ca5fa558")]
| 20 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
namespace ServiceClientGenerator
{
/// <summary>
/// Parses the command line into argument settings controlling the
/// sdk code generator.
/// </summary>
internal class CommandArguments
{
/// <summary>
/// Takes the command line arguments, fuses them with any response file that may also have
/// been specified, and parses them.
/// </summary>
/// <param name="cmdlineArgs">The set of arguments supplied to the program</param>
/// <returns></returns>
public static CommandArguments Parse(string[] cmdlineArgs)
{
var arguments = new CommandArguments();
arguments.Process(cmdlineArgs);
return arguments;
}
/// <summary>
/// Set if an error is encountered whilst parsing arguments.
/// </summary>
public string Error { get; private set; }
/// <summary>
/// <para>
/// The collection of options parsed from the command line.
/// These arguments exist on the command line as individual entries
/// prefixed with '-' or '/'. Options can be set in a response file
/// and indicated with a '@' prefix, in which case the contents
/// of the file will be read and inserted into the same relative
/// location in the arguments to parse (allowing for later
/// arguments to override).
/// </para>
/// <para>
/// Options not specified on the command line are set from internal
/// defaults.
/// </para>
/// </summary>
public GeneratorOptions ParsedOptions { get; private set; }
private CommandArguments()
{
ParsedOptions = new GeneratorOptions();
}
private void Process(IEnumerable<string> cmdlineArgs)
{
// walk the supplied command line looking for any response file(s), indicated using
// @filename, and fuse into one logical set of arguments we can parse
var argsToParse = new List<string>();
foreach (var a in cmdlineArgs)
{
if (a.StartsWith("@", StringComparison.OrdinalIgnoreCase))
AddResponseFileArguments(a.Substring(1), argsToParse);
else
argsToParse.Add(a);
}
if (string.IsNullOrEmpty(Error))
{
for (var argIndex = 0; argIndex < argsToParse.Count; argIndex++)
{
if (!IsSwitch(argsToParse[argIndex])) continue;
var argDeclaration = FindArgDeclaration(argsToParse[argIndex]);
if (argDeclaration != null)
{
if (argDeclaration.HasValue)
argIndex++;
if (argIndex < argsToParse.Count)
argDeclaration.Parse(this, argsToParse[argIndex]);
else
Error = "Expected value for argument: " + argDeclaration.OptionName;
}
else
Error = "Unrecognised argument: " + argsToParse[argIndex];
if (!string.IsNullOrEmpty(Error))
break;
}
}
}
private void AddResponseFileArguments(string responseFile, ICollection<string> args)
{
try
{
// Response file format is one argument (plus optional value)
// per line. Comments can be used by putting # as the first char.
using (var s = new StreamReader(ResolvePath(responseFile)))
{
var line = s.ReadLine();
while (line != null)
{
if (line.Length != 0 && line[0] != '#')
{
// trying to be flexible here and allow for lines with or without keyword
// prefix in the response file
var keywordEnd = line.IndexOf(' ');
var keyword = keywordEnd > 0 ? line.Substring(0, keywordEnd) : line;
if (ArgumentPrefixes.Any(prefix => keyword.StartsWith(prefix.ToString(CultureInfo.InvariantCulture))))
args.Add(keyword);
else
args.Add(ArgumentPrefixes[0] + keyword);
if (keywordEnd > 0)
{
keywordEnd++;
if (keywordEnd < line.Length)
{
var value = line.Substring(keywordEnd).Trim(' ');
if (!string.IsNullOrEmpty(value))
args.Add(value);
}
}
}
line = s.ReadLine();
}
}
}
catch (Exception e)
{
Error = string.Format("Caught exception processing response file {0} - {1}", responseFile, e.Message);
}
}
delegate void ParseArgument(CommandArguments arguments, string argValue = null);
class ArgDeclaration
{
public string OptionName { get; set; }
public string ShortName { get; set; }
public bool HasValue { get; set; }
public ParseArgument Parse { get; set; }
public string HelpText { get; set; }
public string HelpExample { get; set; }
}
static readonly ArgDeclaration[] ArgumentsTable =
{
new ArgDeclaration
{
OptionName = "verbose",
ShortName = "v",
Parse = (arguments, argValue) => arguments.ParsedOptions.Verbose = true,
HelpText = "Enable verbose output."
},
new ArgDeclaration
{
OptionName = "waitonexit",
ShortName = "w",
Parse = (arguments, argValue) => arguments.ParsedOptions.WaitOnExit = true,
HelpText = "Pauses waiting for a keypress after code generation completes."
},
new ArgDeclaration
{
OptionName = "manifest",
ShortName = "m",
HasValue = true,
Parse = (arguments, argValue) => arguments.ParsedOptions.Manifest = argValue,
HelpText = "The name and location of the control manifest listing all supported services for generation."
},
new ArgDeclaration
{
OptionName = "versions",
ShortName = "vs",
HasValue = true,
Parse = (arguments, argValue) => arguments.ParsedOptions.Versions = argValue,
HelpText = "The name and location of the manifest listing versions of all supported services."
},
new ArgDeclaration
{
OptionName = "modelsfolder",
ShortName = "mf",
HasValue = true,
Parse = (arguments, argValue) => arguments.ParsedOptions.ModelsFolder = argValue,
HelpText = "The location of the folder containing the service model files."
},
new ArgDeclaration
{
OptionName = "sdkroot",
ShortName = "sdk",
HasValue = true,
Parse = (arguments, argValue) => arguments.ParsedOptions.SdkRootFolder = argValue,
HelpText = "The root folder beneath which the source and test code for the SDK is arranged."
},
new ArgDeclaration
{
OptionName = "servicemodels",
ShortName = "sm",
HasValue = true,
Parse = (arguments, argValue) => arguments.ParsedOptions.ServiceModels = argValue,
HelpText = "Collection of one or more service model identifiers, separated by the ';' character.\n"
+ "If specified only these service(s) will be generated. The values specified are matched with\n"
+ "the 'model' entry values in the service manifest file."
},
new ArgDeclaration
{
OptionName = "skipremoveorphanscleanup",
ShortName = "sro",
Parse = (arguments, argValue) => arguments.ParsedOptions.SkipRemoveOrphanCleanup = true,
HelpText = "Allows disabling orphaned shape and service cleanup. Useful to set if you \n" +
"a) specify ServiceModels and b) don't want to remove previously generated services." +
"This is often the case in a development environment."
},
new ArgDeclaration
{
OptionName = "clean",
ShortName = "c",
Parse = (arguments, argValue) => arguments.ParsedOptions.Clean = true,
HelpText = "Deletes all content in the 'Generated' subfolder for services prior to generation.\n"
+ "The default behavior is to keep existing generated content."
},
new ArgDeclaration
{
OptionName = "createvsix",
ShortName = "cvx",
Parse = (arguments, argValue) => arguments.ParsedOptions.CreateCodeAnalysisVsixAssets = true,
HelpText = "Creates a VSIX project and manifest for code analysis"
},
new ArgDeclaration
{
OptionName = "self.modelpath",
Parse = (arguments, argValue) => arguments.ParsedOptions.SelfServiceModel = argValue,
HasValue = true,
HelpText = "Path to service model for self service."
},
new ArgDeclaration
{
OptionName = "self.basename",
Parse = (arguments, argValue) => arguments.ParsedOptions.SelfServiceBaseName = argValue,
HasValue = true,
HelpText = "Self Service base name used for namespace and client name."
},
new ArgDeclaration
{
OptionName = "self.endpoint-prefix",
Parse = (arguments, argValue) => arguments.ParsedOptions.SelfServiceEndpointPrefix = argValue,
HasValue = true,
HelpText = "Endpoint prefix for self service."
},
new ArgDeclaration
{
OptionName = "self.sig-v4-service-name",
Parse = (arguments, argValue) => arguments.ParsedOptions.SelfServiceSigV4Name = argValue,
HasValue = true,
HelpText = "Sig V4 service signing name."
}
};
static readonly char[] ArgumentPrefixes = { '-', '/' };
/// <summary>
/// Returns true if the supplied value has a argument prefix indicator, marking it as
/// an argumentkeyword.
/// </summary>
/// <param name="argument"></param>
/// <returns></returns>
static bool IsSwitch(string argument)
{
return ArgumentPrefixes.Any(c => argument.StartsWith(c.ToString(CultureInfo.InvariantCulture)));
}
/// <summary>
/// Scans the argument declaration table to find a matching entry for a token from the command line
/// that is potentially an option keyword.
/// </summary>
/// <param name="argument">Keyword found on the command line. Any prefixes will be removed before attempting to match.</param>
/// <returns>Matching declaration or null if keyword not recognised</returns>
static ArgDeclaration FindArgDeclaration(string argument)
{
var keyword = argument.TrimStart(ArgumentPrefixes);
return ArgumentsTable.FirstOrDefault(argDeclation
=> keyword.Equals(argDeclation.ShortName, StringComparison.OrdinalIgnoreCase)
|| keyword.Equals(argDeclation.OptionName, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Resolves any relatively pathed filename.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
static string ResolvePath(string filePath)
{
if (Path.IsPathRooted(filePath))
return filePath;
return Path.GetFullPath(filePath);
}
}
}
| 302 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
public class Program
{
static int Main(string[] args)
{
var commandArguments = CommandArguments.Parse(args);
if (!string.IsNullOrEmpty(commandArguments.Error))
{
Console.WriteLine(commandArguments.Error);
return -1;
}
var returnCode = 0;
var options = commandArguments.ParsedOptions;
var modelsToProcess = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrEmpty(options.ServiceModels))
{
foreach (var s in options.ServiceModels.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
modelsToProcess.Add(s);
}
}
try
{
if (options.CompileCustomizations) // Compile all servicename.customizations*.json files into one json file in bin
CustomizationCompiler.CompileServiceCustomizations(options);
var generationManifest = GenerationManifest.Load(options);
if (string.IsNullOrEmpty(options.SelfServiceModel))
{
ConcurrentDictionary<string, string> generatedFiles = new ConcurrentDictionary<string, string>();
GeneratorDriver.GenerateCoreProjects(generationManifest, options);
GeneratorDriver.GeneratePartitions(options);
Parallel.ForEach(generationManifest.ServiceConfigurations, new ParallelOptions { MaxDegreeOfParallelism = 16 }, (serviceConfig, state) =>
{
if (modelsToProcess.Any() && !modelsToProcess.Contains(serviceConfig.ModelName))
{
Console.WriteLine("Skipping model (not in -servicemodels set to process): {0} ({1})",
serviceConfig.ModelName, serviceConfig.ModelPath);
return;
}
Console.WriteLine("Processing model: {0} ({1})", serviceConfig.ModelName,
serviceConfig.ModelPath);
var driver = new GeneratorDriver(serviceConfig, generationManifest, options);
driver.Execute();
foreach (var file in driver.FilesWrittenToGeneratorFolder)
{
generatedFiles.TryAdd(file, file);
}
GeneratorDriver.UpdateUnitTestProjects(generationManifest, options, driver.ServiceUnitTestFilesRoot, serviceConfig);
});
var files = new HashSet<string>(generatedFiles.Values);
if (!options.SkipRemoveOrphanCleanup)
GeneratorDriver.RemoveOrphanedShapesAndServices(files, options.SdkRootFolder);
GeneratorDriver.UpdateUnitTestProjects(generationManifest, options);
GeneratorDriver.UpdateSolutionFiles(generationManifest, options);
GeneratorDriver.UpdateAssemblyVersionInfo(generationManifest, options);
GeneratorDriver.UpdateNuGetPackagesInReadme(generationManifest, options);
GeneratorDriver.UpdateCodeAnalysisSolution(generationManifest, options);
GeneratorDriver.GenerateDefaultConfigurationModeEnum(generationManifest, options);
GeneratorDriver.GenerateEndpoints(options);
GeneratorDriver.GenerateS3Enumerations(options);
}
else
{
var serviceConfig = new ServiceConfiguration
{
ModelPath = options.SelfServiceModel,
ServiceFileVersion = "3.1.0.0"
};
serviceConfig.ModelName = Path.GetFileName(serviceConfig.ModelPath);
serviceConfig.ServiceDependencies = new Dictionary<string, string> { {"Core", "3.1.0.0"} };
serviceConfig.GenerateConstructors = true;
var relativePathToCustomizations = Path.Combine("customizations", string.Format("{0}.customizations.json", options.SelfServiceBaseName.ToLowerInvariant()));
if (File.Exists(relativePathToCustomizations))
{
serviceConfig.CustomizationsPath = Path.GetFullPath(relativePathToCustomizations);
Console.WriteLine("Using customization file: {0}", serviceConfig.CustomizationsPath);
}
Console.WriteLine("Processing self service {0} with model {1}.", options.SelfServiceBaseName, options.SelfServiceModel);
var driver = new GeneratorDriver(serviceConfig, generationManifest, options);
driver.Execute();
// Skip orphan clean for DynamoDB because of the complex nature of DynamDB and DynamoDB Streams
if (!serviceConfig.ClassName.StartsWith("DynamoDB") && !options.SkipRemoveOrphanCleanup)
{
GeneratorDriver.RemoveOrphanedShapes(driver.FilesWrittenToGeneratorFolder, driver.GeneratedFilesRoot);
}
}
}
catch (Exception e)
{
if (options.WaitOnExit)
{
Console.Error.WriteLine("Error running generator: " + e.Message);
Console.Error.WriteLine(e.StackTrace);
returnCode = -1;
}
else
throw;
}
if (options.WaitOnExit)
{
Console.WriteLine();
Console.WriteLine("Generation complete. Press a key to exit.");
Console.ReadLine();
}
return returnCode;
}
}
}
| 133 |
aws-sdk-net | aws | C# | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyDescription("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2c172bf0-9737-453c-aa52-4651b8245812")]
| 18 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System;
using System.Collections.Generic;
namespace ServiceClientGenerator
{
/// <summary>
/// Algorithms for validating request and response integrity for supported operations.
/// These are the algorithms supported by the .NET SDK, and the superset of the modeled
/// response algorithms for a given operation.
/// </summary>
public enum ChecksumAlgorithm
{
CRC32C,
CRC32,
SHA256,
SHA1
}
/// <summary>
/// Represents the request and response checksum configuration for a given operation,
/// read from the "httpChecksum" trait applied at the operation-level in a service model.
/// </summary>
public class ChecksumConfiguration
{
/// <summary>
/// Indicates if checksum MUST be present in the operation's HTTP request
/// </summary>
public bool RequestChecksumRequired { get; set; }
/// <summary>
/// Represents the member name of the operation input member used to configure the request checksum behavior.
/// The operation input member MUST target an enum representing the supported checksum algorithms.
/// </summary>
public string RequestAlgorithmMember { get; set; }
/// <summary>
/// Represents the member name of the operation input member used to opt-in for the best effort validation of the checksums returned
/// on the response. The operation input member MUST target an enum and the only supported enum value is "ENABLED".
/// </summary>
public string RequestValidationModeMember { get; set; }
/// <summary>
/// List of checksum algorithms for which clients should perform checksum validation
/// if the checksum data value is present in the response headers.
/// </summary>
public List<ChecksumAlgorithm> ResponseAlgorithms { get; set; }
public ChecksumConfiguration(JsonData data)
{
if (data[ServiceModel.RequestChecksumRequiredKey] != null)
{
if (data[ServiceModel.RequestChecksumRequiredKey].IsBoolean)
{
RequestChecksumRequired = (bool)data[ServiceModel.RequestChecksumRequiredKey];
}
else
{
throw new ArgumentOutOfRangeException($"{data[ServiceModel.RequestChecksumRequiredKey]} is not a valid boolean value for {ServiceModel.RequestChecksumRequiredKey}");
}
}
RequestAlgorithmMember = data.SafeGetString(ServiceModel.RequestAlgorithmMemberKey);
RequestValidationModeMember = data.SafeGetString(ServiceModel.RequestValidationModeMemberKey);
ResponseAlgorithms = ParseList(data[ServiceModel.ResponseAlgorithmsKey]);
}
public static List<ChecksumAlgorithm> ParseList(JsonData jsonData)
{
var algorithms = new List<ChecksumAlgorithm>();
if (jsonData != null && jsonData.IsArray)
{
var invalidAlgorithms = new List<string>();
foreach (JsonData rawAlgorithm in jsonData)
{
if (Enum.TryParse<ChecksumAlgorithm>((string)rawAlgorithm, false, out var parsedAlgorithm))
{
algorithms.Add(parsedAlgorithm);
}
else
{
invalidAlgorithms.Add(rawAlgorithm.ToString());
}
}
if (invalidAlgorithms.Count > 0)
{
throw new ArgumentOutOfRangeException($"Found one or more more unsupported values for {nameof(ChecksumAlgorithm)}: {string.Join(",", invalidAlgorithms)}");
}
}
return algorithms;
}
}
}
| 97 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using ServiceClientGenerator.Generators.CodeAnalysis;
namespace ServiceClientGenerator
{
public class CodeAnalysisProjectCreator
{
public void Execute(string codeAnalysisRoot, ServiceConfiguration serviceConfiguration)
{
SetupProjectFile(codeAnalysisRoot, serviceConfiguration);
GenerateAssemblyInfo(codeAnalysisRoot, serviceConfiguration);
GeneratePropertyValueRules(codeAnalysisRoot, serviceConfiguration);
GeneratePropertyValueAnalyzer(codeAnalysisRoot, serviceConfiguration);
}
void SetupProjectFile(string codeAnalysisRoot, ServiceConfiguration serviceConfiguration)
{
if (!Directory.Exists(codeAnalysisRoot))
Directory.CreateDirectory(codeAnalysisRoot);
var assemblyName = "AWSSDK." + serviceConfiguration.Namespace.Split('.')[1] + ".CodeAnalysis";
var projectFilename = string.Concat(assemblyName, ".csproj");
string projectGuid;
if (File.Exists(Path.Combine(codeAnalysisRoot, projectFilename)))
{
Console.WriteLine("...updating existing project file {0}", projectFilename);
var projectPath = Path.Combine(codeAnalysisRoot, projectFilename);
projectGuid = Utils.GetProjectGuid(projectPath);
}
else
{
projectGuid = Utils.NewProjectGuid;
Console.WriteLine("...creating project file {0}", projectFilename);
}
var templateSession = new Dictionary<string, object>();
templateSession["ProjectGuid"] = projectGuid;
templateSession["RootNamespace"] = serviceConfiguration.Namespace + ".CodeAnalysis";
templateSession["AssemblyName"] = assemblyName;
templateSession["SourceDirectories"] = GetProjectSourceFolders(codeAnalysisRoot);
templateSession["EmbeddedResources"] = GetEmbeddedResources(codeAnalysisRoot);
CodeAnalysisProjectFile generator = new CodeAnalysisProjectFile();
generator.Session = templateSession;
var generatedContent = generator.TransformText();
GeneratorDriver.WriteFile(codeAnalysisRoot, string.Empty, projectFilename, generatedContent);
}
private void GenerateAssemblyInfo(string codeAnalysisRoot, ServiceConfiguration serviceConfiguration)
{
var generator = new CodeAnalysisAssemblyInfo { Config = serviceConfiguration };
var text = generator.TransformText();
GeneratorDriver.WriteFile(codeAnalysisRoot, "Properties", "AssemblyInfo.cs", text);
}
private void GeneratePropertyValueRules(string codeAnalysisRoot, ServiceConfiguration serviceConfiguration)
{
StringBuilder sb = new StringBuilder();
using (var writer = XmlWriter.Create(sb, new XmlWriterSettings {Indent = true }))
{
writer.WriteStartElement("property-value-rules");
if (!string.Equals(serviceConfiguration.ClassName, "S3", StringComparison.InvariantCultureIgnoreCase))
{
HashSet<string> requestAndResponseShapes = new HashSet<string>();
foreach (var operation in serviceConfiguration.ServiceModel.Operations)
{
if (operation.RequestStructure != null)
{
GeneratePropertyValueRules(serviceConfiguration, writer, operation.Name + "Request", operation.RequestStructure);
requestAndResponseShapes.Add(operation.RequestStructure.Name);
}
if (operation.ResponseStructure != null)
{
GeneratePropertyValueRules(serviceConfiguration, writer, operation.Name + "Response", operation.ResponseStructure);
requestAndResponseShapes.Add(operation.ResponseStructure.Name);
}
}
foreach (var shape in serviceConfiguration.ServiceModel.Shapes.OrderBy(x => x.Name))
{
if (requestAndResponseShapes.Contains(shape.Name))
continue;
if (shape.IsStructure)
{
GeneratePropertyValueRules(serviceConfiguration, writer, shape.Name, shape);
}
}
}
writer.WriteEndElement();
}
var content = sb.ToString();
GeneratorDriver.WriteFile(Path.Combine(codeAnalysisRoot, "Generated"), string.Empty, "PropertyValueRules.xml", content);
}
private void GeneratePropertyValueRules(ServiceConfiguration serviceConfiguration, XmlWriter writer, string shapeName, Shape shape)
{
foreach (var member in shape.Members)
{
var memberShape = member.Shape;
if (!memberShape.IsPrimitiveType)
continue;
if (memberShape.Min == null && memberShape.Max == null && memberShape.Pattern == null)
continue;
writer.WriteStartElement("property-value-rule");
var propertyName = string.Format("{0}.Model.{1}.{2}", serviceConfiguration.Namespace, shapeName, member.PropertyName);
writer.WriteElementString("property", propertyName);
if (memberShape.Min != null)
writer.WriteElementString("min", memberShape.Min.Value.ToString());
if (memberShape.Max != null)
writer.WriteElementString("max", memberShape.Max.Value.ToString());
if (memberShape.Pattern != null)
{
try
{
// Make sure we can compile the expression
new System.Text.RegularExpressions.Regex(memberShape.Pattern);
writer.WriteElementString("pattern", memberShape.Pattern);
}
catch(Exception)
{
}
}
writer.WriteEndElement();
}
}
private void GeneratePropertyValueAnalyzer(string codeAnalysisRoot, ServiceConfiguration serviceConfiguration)
{
var generator = new PropertyValueAssignmentAnalyzer { Config = serviceConfiguration };
var text = generator.TransformText();
GeneratorDriver.WriteFile(codeAnalysisRoot, "Generated", "PropertyValueAssignmentAnalyzer.cs", text);
}
private IList<string> GetEmbeddedResources(string codeAnalysisRoot)
{
var embeddedResources = new List<string>();
foreach(var file in Directory.GetFiles(codeAnalysisRoot, "*.xml", SearchOption.AllDirectories))
{
var relativePath = file.Substring(codeAnalysisRoot.Length);
if (!relativePath.StartsWith(@"\Custom", StringComparison.OrdinalIgnoreCase))
continue;
embeddedResources.Add(relativePath.TrimStart('\\'));
}
return embeddedResources;
}
private IList<string> GetProjectSourceFolders(string codeAnalysisRoot)
{
// Start with the standard generated code folders for the platform
var sourceCodeFolders = new List<string>
{
"Generated"
};
if (Directory.Exists(codeAnalysisRoot))
{
var subFolders = Directory.GetDirectories(codeAnalysisRoot, "*", SearchOption.AllDirectories);
foreach (var folder in subFolders)
{
var serviceRelativeFolder = folder.Substring(codeAnalysisRoot.Length);
if (!serviceRelativeFolder.StartsWith(@"\Custom", StringComparison.OrdinalIgnoreCase))
continue;
sourceCodeFolders.Add(serviceRelativeFolder.TrimStart('\\'));
}
}
var foldersThatExist = new List<string>();
foreach (var folder in sourceCodeFolders)
{
if (Directory.Exists(Path.Combine(codeAnalysisRoot, folder)))
foldersThatExist.Add(folder);
}
// sort so we get a predictable layout
foldersThatExist.Sort(StringComparer.OrdinalIgnoreCase);
return foldersThatExist;
}
}
}
| 204 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceClientGenerator.Generators.CodeAnalysis;
namespace ServiceClientGenerator
{
public class CodeAnalysisSolutionCreator
{
public GeneratorOptions Options { get; set; }
const string projectTypeWildCard = "AWSSDK.*.csproj";
public void Execute()
{
var codeAnalysisProjects = GetListOfCodeAnalysisProjects();
if (Options.CreateCodeAnalysisVsixAssets)
{
GenerateVsixProject(codeAnalysisProjects);
GenerateVsixManifest(codeAnalysisProjects);
}
GenerateSolutionFile(codeAnalysisProjects);
}
public void GenerateSolutionFile(List<Project> codeAnalysisProjects)
{
var templateSession = new Dictionary<string, object>();
templateSession["CodeAnalysisProjects"] = codeAnalysisProjects;
CodeAnalysisSolutionFile generator = new CodeAnalysisSolutionFile();
generator.Session = templateSession;
var generatedContent = generator.TransformText();
GeneratorDriver.WriteFile(Options.SdkRootFolder, string.Empty, "AWSSDK.CodeAnalysis.sln", generatedContent, false, false);
}
public void GenerateVsixProject(List<Project> codeAnalysisProjects)
{
var templateSession = new Dictionary<string, object>();
templateSession["CodeAnalysisProjects"] = codeAnalysisProjects;
var generator = new VsixTestProfileFile();
generator.Session = templateSession;
var generatedContent = generator.TransformText();
GeneratorDriver.WriteFile(Path.Combine(Options.SdkRootFolder, GeneratorDriver.CodeAnalysisFoldername), "AWSCodeAnalysisTestExtension", "AWSCodeAnalysisTestExtension.Vsix.csproj", generatedContent, false, false);
}
public void GenerateVsixManifest(List<Project> codeAnalysisProjects)
{
var templateSession = new Dictionary<string, object>();
templateSession["CodeAnalysisProjects"] = codeAnalysisProjects;
var generator = new VsixManifest();
generator.Session = templateSession;
var generatedContent = generator.TransformText();
GeneratorDriver.WriteFile(Path.Combine(Options.SdkRootFolder, GeneratorDriver.CodeAnalysisFoldername), "AWSCodeAnalysisTestExtension", "source.extension.vsixmanifest", generatedContent, false, false);
}
public List<Project> GetListOfCodeAnalysisProjects()
{
List<Project> projects = new List<Project>();
var codeAnalysisProjectsRoot = Path.Combine(Options.SdkRootFolder, GeneratorDriver.CodeAnalysisFoldername);
foreach (var projectFile in Directory.GetFiles(codeAnalysisProjectsRoot, projectTypeWildCard, SearchOption.AllDirectories).OrderBy(x => x))
{
var fullPath = Path.GetFullPath(projectFile);
var relativePath = fullPath.Substring(fullPath.IndexOf("code-analysis"));
var projectNameInSolution =
Path.GetFileNameWithoutExtension(projectFile);
var project = new Project
{
Name = projectNameInSolution,
ShortName = projectNameInSolution.Replace("AWSSDK.", "").Replace(".CodeAnalysis", ""),
ProjectGuid = Utils.GetProjectGuid(projectFile),
ProjectPath = relativePath
};
projects.Add(project);
}
return projects;
}
public class Project
{
public string ProjectGuid { get; set; }
public string ProjectPath { get; set; }
public string Name { get; set; }
public string ShortName { get; set; }
}
}
}
| 105 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
/// <summary>
/// Wrapper around string builder to help emit properly indented code
/// </summary>
public class CodeBuilder
{
StringBuilder sb;
int tabWidth;
int currentIndent;
string indentSpaces;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="sb">StringBuilder instance to wrap</param>
/// <param name="startingIndent">Staring indent width (in spaces)</param>
/// <param name="tabWidth">Additional indent width (in spaces)</param>
public CodeBuilder(StringBuilder sb, int startingIndent, int tabWidth = 4)
{
this.sb = sb;
this.tabWidth = tabWidth;
this.currentIndent = startingIndent;
this.indentSpaces = new string(' ', currentIndent);
}
/// <summary>
/// Append a formatted string at the current location.
/// </summary>
/// <param name="format">Format string</param>
/// <param name="p">Parameters</param>
/// <returns>This CodeBuilder instance for chaining</returns>
public CodeBuilder AppendFormat(string format, params object[] p)
{
sb.AppendFormat(format, p);
return this;
}
/// <summary>
/// Append a string at the current location
/// </summary>
/// <param name="s">a string</param>
/// <returns>This CodeBuilder instance for chaining</returns>
public CodeBuilder Append(string s)
{
sb.Append(s);
return this;
}
/// <summary>
/// Append a string at the current location, add a newline and indent to the current indent.
/// </summary>
/// <param name="line"></param>
/// <returns>This CodeBuilder instance for chaining</returns>
public CodeBuilder AppendLine(string line)
{
sb.AppendLine(line);
sb.Append(indentSpaces);
return this;
}
/// <summary>
/// Add a newline, and indent to the current indent
/// </summary>
/// <returns>This CodeBuilder instance for chaining</returns>
public CodeBuilder AppendLine()
{
return this.AppendLine("");
}
/// <summary>
/// Increase the indent and open a block, adding a '{' and a newline and indent.
/// </summary>
/// <remarks>
/// The current position will be on a new line at the newly increased indent.
/// </remarks>
/// <returns>This CodeBuilder instance for chaining</returns>
public CodeBuilder OpenBlock()
{
this.currentIndent += this.tabWidth;
this.indentSpaces = new string(' ', currentIndent);
this.AppendLine("{");
return this;
}
/// <summary>
/// Add a newline, reduce the indent by the tab width, and add a '}'
/// </summary>
/// <returns>This CodeBuilder instance for chaining</returns>
public CodeBuilder CloseBlock()
{
this.currentIndent -= this.tabWidth;
if (currentIndent < 0)
throw new InvalidOperationException("Can't indent below 0");
this.indentSpaces = new string(' ', currentIndent);
this.AppendLine();
this.Append("}");
return this;
}
/// <summary>
/// Append a string with quotes around it.
/// </summary>
/// <param name="s">The string</param>
/// <param name="open">The opening quote character. Defaults to double quotes.</param>
/// <param name="close">The closing quote character. Defaults to the open character.</param>
/// <returns>This CodeBuilder instance for chaining</returns>
public CodeBuilder AppendQuote(string s, string open = @"""", string close = null)
{
sb.Append(open).Append(s.Replace("\"", "\\\"")).Append(null == close ? open : close);
return this;
}
}
}
| 124 |
aws-sdk-net | aws | C# | using ServiceClientGenerator.Generators.NuGet;
using ServiceClientGenerator.Generators.SourceFiles;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
public class CoreAssemblyInfoUpdater
{
public GenerationManifest Manifest { get; private set; }
public GeneratorOptions Options { get; private set; }
private Dictionary<string, object> session;
private static string corePath = Path.Combine("src", "Core");
private static string assemblyInfoPath = Path.Combine("Properties", "AssemblyInfo.cs");
private static string internalSdkUtilPath = Path.Combine("Amazon.Util","Internal","InternalSDKUtils.generated.cs");
private const string nuspecPath = "AWSSDK.Core.nuspec";
public CoreAssemblyInfoUpdater(GeneratorOptions options, GenerationManifest manifest)
{
Manifest = manifest;
Options = options;
session = new Dictionary<string, object>
{
{ "Version", Manifest.CoreVersion },
{ "FileVersion", Manifest.CoreFileVersion }
};
session["NuGetPreviewFlag"] = manifest.DefaultToPreview ? manifest.PreviewLabel : "";
}
public void Execute()
{
UpdateAssemblyVersion();
UpdateNuspec();
}
private void UpdateNuspec()
{
var avi = new CoreNuspec { Session = session };
var text = avi.TransformText();
GeneratorDriver.WriteFile(
Options.SdkRootFolder, corePath, nuspecPath, text);
}
private void UpdateAssemblyVersion()
{
var avi = new CoreAssemblyInfo { Session = session };
var text = avi.TransformText();
GeneratorDriver.WriteFile(
Options.SdkRootFolder, corePath, assemblyInfoPath, text);
var sdkUtil = new InternalSDKUtils { Session = session };
var sdkUtilText = sdkUtil.TransformText();
GeneratorDriver.WriteFile(
Options.SdkRootFolder, corePath, internalSdkUtilPath, sdkUtilText);
}
}
}
| 66 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
/// <summary>
/// Used to compile json customizations
/// </summary>
public static class CustomizationCompiler
{
/// <summary>
/// Compiles all files in the namespace *.customizations*.json into one large json file in bin\Release|Debug\customizations folder
/// </summary>
/// <param name="modelsPath">The path the to customization models to be compiled</param>
public static void CompileServiceCustomizations(GeneratorOptions options)
{
var modelsPath = options.ModelsFolder;
string compiledCustomizationsDirectory = "customizations";
Console.WriteLine("Compiling service customizations from {0}", modelsPath);
if (Directory.Exists(compiledCustomizationsDirectory))
{
Console.WriteLine("...cleaning previous compilation output");
Directory.Delete(compiledCustomizationsDirectory, true);
}
else
{
Directory.CreateDirectory(compiledCustomizationsDirectory);
}
var serviceDirectories = Utils.GetServiceDirectories(options);
foreach (string serviceDirectory in serviceDirectories)
{
var s = Path.GetFileName(serviceDirectory);
var compiledFilePath = Path.Combine(compiledCustomizationsDirectory, s + ".customizations.json");
var customizationFiles = Directory.GetFiles(serviceDirectory, "*.customizations*.json");
var jsonWriter = new JsonWriter { PrettyPrint = true };
JsonData outputJson = new JsonData();
outputJson.SetJsonType(JsonType.Object);
foreach (var entry in customizationFiles)
{
var customJson = JsonMapper.ToObject(new StreamReader(entry));
foreach (var property in customJson.PropertyNames)
{
outputJson[property] = customJson[property];
}
}
// Load examples into the customizations as well
var examples = Directory.GetFiles(serviceDirectory, "*.examples.json").FirstOrDefault();
if (null != examples)
{
var exampleData = JsonMapper.ToObject(new StreamReader(examples));
if (exampleData.IsObject && exampleData.PropertyNames.Contains("examples"))
{
outputJson["examples"] = exampleData["examples"];
}
}
outputJson.ToJson(jsonWriter);
// Fixes json being placed into the json mapper
var output = jsonWriter.ToString();
// Empty json file
if (output.Length < 10)
continue;
var compiledFileDirectory = Path.GetDirectoryName(compiledFilePath);
if (!Directory.Exists(compiledFileDirectory))
{
Directory.CreateDirectory(compiledFileDirectory);
}
File.WriteAllText(compiledFilePath, output);
Console.WriteLine("...updated {0}", Path.GetFullPath(compiledFilePath));
}
}
}
}
| 92 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
namespace ServiceClientGenerator
{
#region Simplifications
#region SimpleConstructorsModel
/// <summary>
/// A model that represents the simple constructors of a structure. These constructors are specified in customizations
/// Simple constructors are constructors that are added to request objects that take parameters to set members of the object.
/// This allows for easier creation of these request objects.
/// </summary>
public class SimpleConstructorsModel
{
public const string ConstructorsKey = "constructors";
JsonData _documentRoot;
readonly bool _emptyData = false;
/// <summary>
/// Creates a model for simple constructors for the structure. Used to customize the generation of the structure
/// </summary>
/// <param name="root">The json data that contains information about the customization</param>
public SimpleConstructorsModel(JsonData root)
{
if (root.PropertyNames.Contains("simpleConstructors", StringComparer.OrdinalIgnoreCase))
{
_documentRoot = root["simpleConstructors"];
}
else
{
_documentRoot = new JsonData();
_emptyData = true;
}
}
/// <summary>
/// Sets the document root from a json text
/// </summary>
/// <param name="reader">The reader to get the json text from</param>
void Initialize(TextReader reader)
{
this._documentRoot = JsonMapper.ToObject(reader);
}
/// <summary>
/// A dictionary that maps structure names to the form of the constructor
/// </summary>
public Dictionary<string, ConstructorForms> SimpleConstructors
{
get
{
var constructors = new Dictionary<string, ConstructorForms>(StringComparer.OrdinalIgnoreCase);
var data = _documentRoot[ConstructorsKey];
if (data == null) return constructors;
foreach (KeyValuePair<string, JsonData> kvp in data)
{
constructors[kvp.Key] = new ConstructorForms(kvp.Key, kvp.Value);
}
return constructors;
}
}
/// <summary>
/// Determines if custom constructors need to be generated for the structure
/// </summary>
/// <param name="className">The name of the structure to check for</param>
/// <returns>True if there are custom simple constructors</returns>
public bool CreateSimpleConstructors(string className)
{
if (_emptyData)
return false;
return SimpleConstructors.ContainsKey(className);
}
/// <summary>
/// A list of members for the structure that are used in the constructor form
/// </summary>
/// <param name="form">A list of the member names used by the constructor form</param>
/// <param name="operationMembers">All of the members for the structure</param>
/// <returns>The members for the form</returns>
public List<Member> GetFormMembers(List<string> form, IList<Member> operationMembers)
{
var docMembers = new List<Member>();
foreach (var mem in form)
{
foreach (var opmem in operationMembers)
{
if (opmem.PropertyName.Equals(mem, StringComparison.OrdinalIgnoreCase))
{
docMembers.Add(opmem);
break;
}
}
}
return docMembers;
}
/// <summary>
/// Used to generate a string used to define the params for the constructor
/// </summary>
/// <param name="form">List of member names for the constructor form</param>
/// <param name="operationMembers">All of the members of the structure</param>
/// <returns>A string that represents the required params for the constructor form</returns>
public string GetSimpleParameters(List<string> form, IList<Member> operationMembers)
{
string currentParams = "";
foreach (var mem in form)
{
Member member = null;
foreach (var opmem in operationMembers)
{
if (opmem.PropertyName.Equals(mem, StringComparison.OrdinalIgnoreCase))
{
member = opmem;
break;
}
}
if (member == null)
throw new ArgumentOutOfRangeException("Unable to find matching member");
if (currentParams == "")
currentParams = member.DetermineType() + " " + GeneratorHelpers.CamelCaseParam(member.PropertyName);
else
currentParams = currentParams + ", " + member.DetermineType() + " " + GeneratorHelpers.CamelCaseParam(member.PropertyName);
}
return currentParams;
}
}
#endregion
#region ConstructorForms
/// <summary>
/// Represents forms of the constructor
/// The constructor forms are the different parameter options of a constructor
/// </summary>
public class ConstructorForms
{
public const string ConstructorFormsKey = "constructorForms";
readonly JsonData _constructorRoot;
readonly string _name;
public string Name { get { return _name; } }
/// <summary>
/// Creates a representation for a constructor in the structure consisting of a list of a list of member names
/// </summary>
/// <param name="name">The name of the constructor</param>
/// <param name="json">The json customization for the constructor forms</param>
public ConstructorForms(string name, JsonData json)
{
this._name = name;
this._constructorRoot = json;
}
/// <summary>
/// A list of forms for the constructor consisting of the names of members in each form
/// </summary>
public List<List<string>> Forms
{
get
{
var forms = new List<List<string>>();
var data = _constructorRoot[ConstructorFormsKey];
if (data == null || !data.IsArray) return forms;
foreach (var formData in data)
{
var form = new List<string>();
foreach (var item in (formData as JsonData))
{
form.Add(item.ToString());
}
forms.Add(form);
}
return forms;
}
}
}
#endregion
#region SimpleMethodFormsModel
/// <summary>
/// Represents custom simple methods for the client being generated from the service model
/// Simple methods are methods added to the client that take members of the request as parameters and then creates a request with those
/// members internally and then calls the operation
/// </summary>
public class SimpleMethodFormsModel
{
public const string SimpleMethodsKey = "simpleMethods";
readonly JsonData _documentRoot;
readonly bool _emptyData = false;
/// <summary>
/// Creates a representation of the simple method customizations for the service client
/// </summary>
/// <param name="root">The json data that specifies forms of the simple methods</param>
public SimpleMethodFormsModel(JsonData root)
{
if (root.PropertyNames.Contains(SimpleMethodsKey, StringComparer.OrdinalIgnoreCase))
{
_documentRoot = root[SimpleMethodsKey];
}
else
{
_documentRoot = new JsonData();
_emptyData = true;
}
}
/// <summary>
/// A mapping of method names to the forms for that simple method
/// </summary>
public Dictionary<string, MethodForms> SimpleMethods
{
get
{
var methods = new Dictionary<string, MethodForms>(StringComparer.OrdinalIgnoreCase);
var data = _documentRoot[ServiceModel.OperationsKey];
if (data == null) return methods;
foreach (KeyValuePair<string, JsonData> kvp in data)
{
methods[kvp.Key] = new MethodForms(kvp.Key, kvp.Value);
}
return methods;
}
}
/// <summary>
/// Determines if the operation in the client has a custom simple method specified
/// </summary>
/// <param name="operationName">The name of the operation</param>
/// <returns>If the operation is specified in the customizations</returns>
public bool CreateSimpleMethods(string operationName)
{
if (_emptyData)
return false;
return SimpleMethods.ContainsKey(operationName);
}
/// <summary>
/// Finds the members from the request that need to be used in the method
/// </summary>
/// <param name="form">List of member names for the given form of an operation</param>
/// <param name="operationMembers">All of the members for the given operation</param>
/// <returns></returns>
public List<Member> GetFormMembers(List<string> form, IList<Member> operationMembers)
{
var docMembers = new List<Member>();
foreach (var mem in form)
{
foreach (var opmem in operationMembers)
{
if (opmem.PropertyName.Equals(mem, StringComparison.OrdinalIgnoreCase))
{
docMembers.Add(opmem);
break;
}
}
}
return docMembers;
}
/// <summary>
/// Generates the code for parameters of the method
/// </summary>
/// <param name="form">The form of the method contains names of all the members used</param>
/// <param name="operationMembers">All of the members of an operation</param>
/// <returns>A proper syntax for params of the simple method form</returns>
public string GetSimpleParameters(List<string> form, IList<Member> operationMembers)
{
string currentParams = "";
foreach (var mem in form)
{
Member member = null;
foreach (var opmem in operationMembers)
{
if (opmem.PropertyName.Equals(mem, StringComparison.OrdinalIgnoreCase))
{
member = opmem;
break;
}
}
if (member == null)
throw new ArgumentOutOfRangeException("Unable to find matching member");
string type = member.DetermineType();
if (type == "Stream")
type = "System.IO.Stream";
if (currentParams == "")
currentParams = type + " " + GeneratorHelpers.CamelCaseParam(member.PropertyName);
else
currentParams = currentParams + ", " + type + " " + GeneratorHelpers.CamelCaseParam(member.PropertyName);
}
return currentParams;
}
}
#endregion
#region MethodForms
/// <summary>
/// Represents the forms of a custom simple method
/// Forms of a simple method are the variety of parameters the method will have
/// </summary>
public class MethodForms
{
public const string MethodFormsKey = "methodForms";
readonly JsonData _methodRoot;
readonly string _name;
public string Name { get { return _name; } }
/// <summary>
/// Creates a representation of the forms for a custom simple method
/// </summary>
/// <param name="name">The name of the method</param>
/// <param name="json">The json model for the customization consisting of a list of forms</param>
public MethodForms(string name, JsonData json)
{
this._name = name;
this._methodRoot = json;
}
/// <summary>
/// The forms of a method which is a list of a list of member names for that form
/// </summary>
public List<List<string>> Forms
{
get
{
var forms = new List<List<string>>();
var data = _methodRoot[MethodFormsKey];
if (data == null || !data.IsArray) return forms;
foreach (var formData in data)
{
var form = new List<string>();
foreach (var item in (formData as JsonData))
{
form.Add(item.ToString());
}
forms.Add(form);
}
return forms;
}
}
}
#endregion
#endregion
#region CustomizationsModel
/// <summary>
/// A model used to represent different types of customizations for generating a service
/// </summary>
public class CustomizationsModel
{
public const string RetainOriginalMemberOrderingKey = "retainOriginalMemberOrdering";
public const string RuntimePipelineOverrideKey = "runtimePipelineOverride";
public const string OverridesKey = "overrides";
public const string OperationKey = "operation";
public const string TargetTypeKey = "targetType";
public const string NewTypeKey = "newType";
public const string ConstructorInputKey = "constructorInput";
public const string ConditionKey = "condition";
public const string NoArgOverloadsKey = "noArgOverloads";
public const string SuppressResultGenerationKey = "suppressResultGeneration";
public const string UseNullableTypeKey = "useNullableType";
public const string EmitIsSetPropertiesKey = "emitIsSetProperties";
public const string GlobalShapeKey = "*";
public const string ShapeSubstitutionsKey = "shapeSubstitutions";
public const string EmitAsShapeKey = "emitAsShape";
public const string RenameShapeKey = "renameShape";
public const string EmitFromMemberKey = "emitFromMember";
public const string ListMemberSuffixExclusionsKey = "listMemberSuffixExclusions";
public const string DataTypeSwapKey = "dataTypeSwap";
public const string TypeKey = "Type";
public const string MarshallerKey = "Marshaller";
public const string UnmarshallerKey = "Unmarshaller";
public const string SuppressSimpleMethodExceptionDocsKey = "suppressSimpleMethodExceptionDocs";
public const string XHttpMethodOverrideKey = "xHttpMethodOverride";
public const string DeprecationMessageKey = "message";
public const string ExamplesKey = "examples";
public const string GenerateUnmarshallerKey = "generateUnmarshaller";
public const string SkipUriPropertyValidationKey = "skipUriPropertyValidation";
public const string OverrideContentTypeKey = "overrideContentType";
JsonData _documentRoot;
SimpleMethodFormsModel _simpleMethodsModel;
SimpleConstructorsModel _simpleConstructorsModel;
/// <summary>
/// A model that represents any custom methods to be generated by the client generator
/// </summary>
public SimpleMethodFormsModel SimpleMethodsModel
{
get { return _simpleMethodsModel ?? (_simpleMethodsModel = new SimpleMethodFormsModel(_documentRoot)); }
}
/// <summary>
/// A model that represents any simple constructors to be included while generating structures for the service
/// </summary>
public SimpleConstructorsModel SimpleConstructorsModel
{
get
{
return _simpleConstructorsModel ??
(_simpleConstructorsModel = new SimpleConstructorsModel(_documentRoot));
}
}
/// <summary>
/// Creates a customization model used to get customizations for a service
/// </summary>
/// <param name="reader">Reader to get the json text from</param>
public CustomizationsModel(TextReader reader)
{
if (reader == null)
this._documentRoot = new JsonData();
else
Initialize(reader);
}
/// <summary>
/// Creates a customization model used to get customizations for a service
/// </summary>
/// <param name="modelPath">Path to the file to read the customizations from</param>
public CustomizationsModel(string modelPath)
{
if (string.IsNullOrEmpty(modelPath))
_documentRoot = new JsonData();
else
using (var reader = new StreamReader(modelPath))
Initialize(reader);
}
/// <summary>
/// Sets the document root by parsing the json text
/// </summary>
/// <param name="reader">The reader to get json text from</param>
void Initialize(TextReader reader)
{
this._documentRoot = JsonMapper.ToObject(reader);
}
RuntimePipelineOverride _runtimePipelineOverride;
/// <summary>
/// Allows customizing pipeline overrides to be added to the client
/// </summary>
public RuntimePipelineOverride PipelineOverride
{
get
{
if (_runtimePipelineOverride != null)
{
return _runtimePipelineOverride;
}
var data = _documentRoot[RuntimePipelineOverrideKey];
if (data != null)
{
_runtimePipelineOverride = new RuntimePipelineOverride();
foreach (var item in data[OverridesKey])
{
var jsonData = (JsonData) item;
_runtimePipelineOverride.Overrides.Add(
new RuntimePipelineOverride.Override()
{
OverrideMethod = jsonData[OperationKey] != null
? jsonData[OperationKey].ToString()
: null,
TargetType =
jsonData[TargetTypeKey] != null ? jsonData[TargetTypeKey].ToString() : null,
NewType = jsonData[NewTypeKey] != null ? jsonData[NewTypeKey].ToString() : null,
ConstructorInput = jsonData[ConstructorInputKey] != null ? jsonData[ConstructorInputKey].ToString() : "",
Condition = jsonData[ConditionKey] != null ? jsonData[ConditionKey].ToString() : ""
});
}
}
return _runtimePipelineOverride;
}
}
public bool SuppressSimpleMethodExceptionDocs
{
get
{
var flag = _documentRoot[SuppressSimpleMethodExceptionDocsKey];
if (flag != null && flag.IsBoolean)
{
return (bool)flag;
}
else if (flag != null && flag.IsString)
{
return bool.Parse((string)flag);
}
return false;
}
}
public bool RetainOriginalMemberOrdering
{
get
{
var flag = _documentRoot[RetainOriginalMemberOrderingKey];
if (flag != null && flag.IsBoolean)
{
return (bool)flag;
}
else if (flag != null && flag.IsString)
{
return bool.Parse((string)flag);
}
return false;
}
}
/// <summary>
/// A list of uri properties for the service where we should not do validation for presence.
/// </summary>
public List<string> SkipUriPropertyValidations
{
get
{
var validations = new List<string>();
var data = _documentRoot[SkipUriPropertyValidationKey];
if (data == null || !data.IsArray) return validations;
foreach (var item in data)
validations.Add(item.ToString());
return validations;
}
}
/// <summary>
/// A list of methods that will be customized to have no arguments as one form of the operation
/// </summary>
public List<string> NoArgOverloads
{
get
{
var overloads = new List<string>();
var data = _documentRoot[NoArgOverloadsKey];
if (data == null || !data.IsArray) return overloads;
foreach (var item in data)
overloads.Add(item.ToString());
overloads.Sort();
return overloads;
}
}
private HashSet<string> _resultGenerationSuppressions = null;
/// <summary>
/// A list of methods that will be customized to not have a derived
/// Result class due to an empty response.
/// </summary>
public HashSet<string> ResultGenerationSuppressions
{
get
{
if (_resultGenerationSuppressions == null)
{
_resultGenerationSuppressions = new HashSet<string>();
var data = _documentRoot[SuppressResultGenerationKey];
if (data != null && data.IsArray)
{
foreach (var item in data)
_resultGenerationSuppressions.Add(item.ToString());
}
}
return _resultGenerationSuppressions;
}
}
public bool GenerateCustomUnmarshaller
{
get
{
var data = _documentRoot[GenerateUnmarshallerKey];
if (data == null)
return false;
return true;
}
}
/// <summary>
/// Override for the Content-Type header
/// </summary>
public string OverrideContentType
{
get
{
var data = _documentRoot[OverrideContentTypeKey];
if (data == null)
{
return null;
}
return (string)data;
}
}
public List<string> CustomUnmarshaller
{
get
{
var data = _documentRoot[GenerateUnmarshallerKey];
if (data == null)
return null;
return (from JsonData s in data select s.ToString()).ToList();
}
}
/// <summary>
/// Determines if the operation has a customization for creating a no argument method
/// </summary>
/// <param name="operationName">The name of the operation to check for</param>
/// <returns>True if the operation is in the list of noarg customizations</returns>
public bool CreateNoArgOverload(string operationName)
{
return NoArgOverloads.Contains(operationName, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Gets the property modifier for a property in a shape (can be global) if so customized.
/// </summary>
/// <param name="shapeName">The name of the shape containing the property</param>
/// <param name="propertyName">The property name to look for</param>
/// <returns>The property modifier, null if not found</returns>
public PropertyModifier GetPropertyModifier(string shapeName, string propertyName)
{
// for renames, check for a shape-specific rename first, then look to
// see if the property is globally renamed
if (ShapeModifiers.ContainsKey(shapeName))
{
var shapeModifiers = ShapeModifiers[shapeName];
if (shapeModifiers.IsModified(propertyName))
return shapeModifiers.PropertyModifier(propertyName);
}
if (ShapeModifiers.ContainsKey(GlobalShapeKey))
{
var globalShapeModifiers = ShapeModifiers[GlobalShapeKey];
if (globalShapeModifiers.IsModified(propertyName))
return globalShapeModifiers.PropertyModifier(propertyName);
}
return null;
}
/// <summary>
/// Determines if the property has a customization to be set to nullable
/// </summary>
/// <param name="shapeName">The name of the shape the property is in</param>
/// <param name="propertyName">The name of the property</param>
/// <returns>If the property is to be nullable</returns>
public bool UseNullable(string shapeName, string propertyName)
{
var data = _documentRoot[UseNullableTypeKey];
if (data == null)
return false;
var shape = data[shapeName] as JsonData;
if (shape == null || !shape.IsArray)
return false;
foreach (var name in shape)
{
if (string.Equals(name.ToString(), propertyName))
return true;
}
return false;
}
/// <summary>
/// Determines if the collection property can be empty when being
/// sent to the service.
/// </summary>
/// <param name="shapeName">The name of the shape the property is in</param>
/// <param name="propertyName">The name of the property</param>
/// <returns>If the collection property can be empty</returns>
public bool EmitIsSetProperties(string shapeName, string propertyName)
{
var data = _documentRoot[EmitIsSetPropertiesKey];
if (data == null)
return false;
var shape = data[shapeName] as JsonData;
if (shape == null || !shape.IsArray)
return false;
foreach (var name in shape)
{
if (string.Equals(name.ToString(), propertyName))
return true;
}
return false;
}
public string GetOverrideShapeName(string originalShapeName)
{
return GetRemappedShapeName(originalShapeName, RenameShapeKey);
}
/// <summary>
/// Returns the name of the shape that should be used instead of the supplied shape
/// </summary>
/// <param name="originalShapeName">The shape to have its name changed</param>
/// <returns>The new name, or null if not found</returns>
public string GetSubstituteShapeName(string originalShapeName)
{
return GetRemappedShapeName(originalShapeName, EmitAsShapeKey);
}
private string GetRemappedShapeName(string originalShapeName, string key)
{
var substitutionsData = _documentRoot[ShapeSubstitutionsKey];
if (substitutionsData == null)
return null;
var shapeRemapData = substitutionsData[originalShapeName] as JsonData;
if (null == shapeRemapData || null == shapeRemapData[key])
return null;
return (string)shapeRemapData[key];
}
/// <summary>
/// Returns the substitution entry for a shape
/// </summary>
/// <param name="originalShapeName"></param>
/// <returns></returns>
public JsonData GetSubstituteShapeData(string originalShapeName)
{
var substitutionsData = _documentRoot[ShapeSubstitutionsKey];
if (substitutionsData == null)
return null;
return substitutionsData[originalShapeName];
}
/// <summary>
/// Determines if the shape should be substituted with another
/// </summary>
/// <param name="originalShapeName">The original shape</param>
/// <returns>If the shape is in the rename shapes</returns>
public bool IsSubstitutedShape(string originalShapeName)
{
var substitutionsData = _documentRoot[ShapeSubstitutionsKey];
if (substitutionsData == null)
return false;
var remapShape = substitutionsData[originalShapeName] as JsonData;
return remapShape != null;
}
/// <summary>
/// Gets any customizations for a new data type to be used on a property
/// </summary>
/// <param name="shapeName">The name of the shape the property is defined within</param>
/// <param name="propertyName">The name of the property to check</param>
/// <returns>The override datatype object, null if not found</returns>
public DataTypeOverride OverrideDataType(string shapeName, string propertyName)
{
var data = _documentRoot[DataTypeSwapKey];
if (data == null)
return null;
var shape = data[shapeName] as JsonData;
if (shape == null)
return null;
var jsonData = shape[propertyName];
if (jsonData == null)
return null;
var dataType = (string)jsonData[TypeKey];
string marshaller = null;
if (jsonData[MarshallerKey] != null && jsonData[MarshallerKey].IsString)
marshaller = (string)jsonData[MarshallerKey];
string unmarshaller = null;
if (jsonData[UnmarshallerKey] != null && jsonData[UnmarshallerKey].IsString)
unmarshaller = (string)jsonData[UnmarshallerKey];
return new DataTypeOverride(dataType, marshaller, unmarshaller);
}
#region ShapeModifier
/// <summary>
/// The ShapeModifier allows shapes pulled from the model to be customized by excluding
/// properties, modifying them (rename etc) and injecting properties not in the original
/// model.
/// </summary>
public class ShapeModifier
{
public const string ShapeModifiersKey = "shapeModifiers";
public const string ExcludeKey = "exclude";
public const string ModifyKey = "modify";
public const string InjectKey = "inject";
public const string CustomMarshallKey = "customMarshall";
public const string DeprecatedMessageKey = "deprecatedMessage";
public const string BackwardsCompatibleDateTimeKey = "backwardsCompatibleDateTimeProperties";
private readonly HashSet<string> _excludedProperties;
private readonly HashSet<string> _backwardsCompatibleDateTimeProperties;
private readonly Dictionary<string, JsonData> _modifiedProperties;
private readonly Dictionary<string, JsonData> _injectedProperties;
public string DeprecationMessage { get; private set; }
public ShapeModifier(JsonData data)
{
DeprecationMessage = data[DeprecatedMessageKey].CastToString();
_excludedProperties = ParseExclusions(data);
_backwardsCompatibleDateTimeProperties = ParseBackwardsCompatibleDateTimeProperties(data);
_modifiedProperties = ParseModifiers(data);
// Process additions after rename to allow for models where we
// add a 'convenience' member (for backwards compatibility) using
// the same name as an original (and now renamed) member.
_injectedProperties = ParseInjections(data);
}
#region Property Exclusion
// Exclusion modifier is a simple array of property names.
// "exclude": [ "propName1", "propName2" ]
private static HashSet<string> ParseExclusions(JsonData data)
{
var exclusions = data[ShapeModifier.ExcludeKey]
?.Cast<object>()
.Select(exclusion => exclusion.ToString());
return new HashSet<string>(exclusions ?? new string[0]);
}
public bool IsExcludedProperty(string propertyName)
{
return _excludedProperties.Contains(propertyName);
}
#endregion
#region Backwards Compatible DateTime Properties
// Backwards Compatible DateTime Properties modifier is a simple array of property names.
// "backwardsCompatibleDateTimeProperties": [ "propName1", "propName2" ]
private static HashSet<string> ParseBackwardsCompatibleDateTimeProperties(JsonData data)
{
var exclusions = data[ShapeModifier.BackwardsCompatibleDateTimeKey]
?.Cast<object>()
.Select(exclusion => exclusion.ToString());
return new HashSet<string>(exclusions ?? new string[0]);
}
public bool IsBackwardsCompatibleDateTimeProperty(string propertyName)
{
return _backwardsCompatibleDateTimeProperties.Contains(propertyName);
}
#endregion
#region Property Modifiers
// A modifier is an array of objects, each object being the original
// property name (key) and an object containing replacement name (value)
// along with any custom marshal naming to apply.
// "modify": [
// {
// "modelPropertyName": {
// "emitPropertyName": "userVisibleName",
// "locationName": "customRequestMarshalName",
// "emitFromMember": "subMember"
// }
// }
// ]
private static Dictionary<string, JsonData> ParseModifiers(JsonData data)
{
var modifiers = data[ShapeModifier.ModifyKey]
?.Cast<JsonData>()
.Select(modifier => modifier.Cast<KeyValuePair<string, JsonData>>().First());
return modifiers?.ToDictionary(modifier => modifier.Key, modifier => modifier.Value)
?? new Dictionary<string, JsonData>();
}
public bool IsModified(string propertyName)
{
return _modifiedProperties.ContainsKey(propertyName);
}
public PropertyModifier PropertyModifier(string propertyName)
{
if (IsModified(propertyName))
return new PropertyModifier(propertyName, _modifiedProperties[propertyName]);
return null;
}
#endregion
#region Property Injection
// Injection modifier is an array of objects, each object being the
// name of the member to add plus any needed shape/marshalling data.
// "inject": [
// { "propertyName":
// { "type": "list",
// "member": { "shape": "String", "locationName": "item" }
// }
// }
// ]
// Since we don't have access to the model at this point, we simply store
// the json data for the shape type to be used and 'hydrate' it when needed
// externally
private static Dictionary<string, JsonData> ParseInjections(JsonData data)
{
var injections = data[ShapeModifier.InjectKey]
?.Cast<JsonData>()
.Select(modifier => modifier.Cast<KeyValuePair<string, JsonData>>().First());
return injections?.ToDictionary(modifier => modifier.Key, modifier => modifier.Value)
?? new Dictionary<string, JsonData>();
}
public bool HasInjectedProperties
{
get { return _injectedProperties.Any(); }
}
public IEnumerable<string> InjectedPropertyNames
{
get
{
var names = new List<string>();
if (HasInjectedProperties)
{
names.AddRange(_injectedProperties.Keys);
}
return names;
}
}
public PropertyInjector InjectedPropertyData(string propertyName)
{
if (!_injectedProperties.ContainsKey(propertyName))
throw new ArgumentException();
return new PropertyInjector(_injectedProperties[propertyName]);
}
#endregion
}
/// <summary>
/// Injects a new property into a model shape
/// </summary>
public class PropertyInjector
{
private readonly JsonData _injectionData;
internal PropertyInjector(JsonData injectionData)
{
this._injectionData = injectionData;
}
public JsonData Data { get { return _injectionData; } }
public bool IsSetUseCustomMarshall
{
get { return _injectionData[ShapeModifier.CustomMarshallKey] != null; }
}
// If set, the generated request marshaller will skip the member in
// favor of custom marshall logic in the pipeline
public bool UseCustomMarshall
{
get
{
if (IsSetUseCustomMarshall)
return (bool)_injectionData[ShapeModifier.CustomMarshallKey];
return false;
}
}
}
/// <summary>
/// Property modifiers allow properties to be renamed within a shape
/// as well as apply custom marshal names (for re-used shapes that
/// marshal differently)
/// </summary>
public class PropertyModifier
{
public const string EmitPropertyNameKey = "emitPropertyName";
public const string LocationNameKey = "locationName";
public const string AccessModifierKey = "accessModifier";
private readonly string _modelPropertyName; // for debug inspection assist
private readonly JsonData _modifierData;
internal PropertyModifier(string modelPropertyName, JsonData modifierData)
{
this._modelPropertyName = modelPropertyName;
this._modifierData = modifierData;
}
// The access modifier for the property. Defaults to public if not set in the customization.
public string AccessModifier
{
get
{
if (_modifierData[AccessModifierKey] == null)
return "public";
return (string)_modifierData[AccessModifierKey];
}
}
// The user-visible name that should be output for the property
public string EmitName
{
get
{
if (_modifierData[EmitPropertyNameKey] == null)
return null;
return (string)_modifierData[EmitPropertyNameKey];
}
}
// The custom marshal name for the property. If not set, the model
// marshal name should be used.
public string LocationName
{
get
{
if (_modifierData[LocationNameKey] == null)
return null;
return (string)_modifierData[LocationNameKey];
}
}
// For properties that are collections, the submember name that
// should be used to extract the value when marshalling into the
// operation.
public string EmitFromMemberName
{
get
{
if (_modifierData[EmitFromMemberKey] == null)
return null;
return (string)_modifierData[EmitFromMemberKey];
}
}
public bool IsSetUseCustomMarshall
{
get { return _modifierData[ShapeModifier.CustomMarshallKey] != null; }
}
// If set, the generated request marshaller will skip the member in
// favor of custom marshall logic in the pipeline
public bool UseCustomMarshall
{
get
{
if (IsSetUseCustomMarshall)
return (bool)_modifierData[ShapeModifier.CustomMarshallKey];
return false;
}
}
public string DeprecationMessage
{
get
{
return _modifierData[ShapeModifier.DeprecatedMessageKey].CastToString();
}
}
}
#endregion
// Injection modifier is an array of objects, each object being the
private Dictionary<string, ShapeModifier> _shapeModifiers = null;
// name of the member to add plus any needed shape/marshalling data.
// "inject": [
// { "propertyName":
// { "type": "list",
public Dictionary<string, ShapeModifier> ShapeModifiers
{
get
{
if (_shapeModifiers == null)
{
_shapeModifiers = new Dictionary<string, ShapeModifier>();
var data = _documentRoot[ShapeModifier.ShapeModifiersKey];
if (data != null)
{
foreach (var shapeName in data.PropertyNames)
{
var modifierData = data[shapeName];
var shapeModifier = new ShapeModifier(modifierData);
_shapeModifiers.Add(shapeName, shapeModifier);
}
}
}
return _shapeModifiers;
}
}
public ShapeModifier GetShapeModifier(string shapeName)
{
var shapeModifiers = ShapeModifiers;
return shapeModifiers.ContainsKey(shapeName) ? shapeModifiers[shapeName] : null;
}
/// <summary>
/// Returns true if the specified property name is excluded at global or
/// per-shape scope.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="shapeName"></param>
/// <returns></returns>
public bool IsExcludedProperty(string propertyName, string shapeName = null)
{
var globalShapeModifier = GetShapeModifier("*");
if (globalShapeModifier != null)
{
if (globalShapeModifier.IsExcludedProperty(propertyName))
return true;
}
if (shapeName != null)
{
var shapeModifier = GetShapeModifier(shapeName);
if (shapeModifier != null)
return shapeModifier.IsExcludedProperty(propertyName);
}
return false;
}
/// <summary>
/// Returns true if the specified property name is marked as requiring backwards compatible handling
/// of DateTime values at global or per-shape scope.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="shapeName"></param>
/// <returns></returns>
public bool IsBackwardsCompatibleDateTimeProperty(string propertyName, string shapeName = null)
{
if (shapeName != null)
{
var shapeModifier = GetShapeModifier(shapeName);
if (shapeModifier != null)
return shapeModifier.IsBackwardsCompatibleDateTimeProperty(propertyName);
}
return false;
}
public OperationModifiers GetOperationModifiers(string operationName)
{
var data = _documentRoot[OperationModifiers.OperationModifiersKey];
if (data == null)
return null;
var operation = data[operationName] as JsonData;
if (operation == null)
return null;
var modifiers = new OperationModifiers();
if (operation[OperationModifiers.NameKey] != null && operation[OperationModifiers.NameKey].IsString)
modifiers.Name = (string)operation[OperationModifiers.NameKey];
if (operation[OperationModifiers.ExcludeKey] != null && operation[OperationModifiers.ExcludeKey].IsBoolean)
modifiers.IsExcluded = (bool)operation[OperationModifiers.ExcludeKey];
if (operation[OperationModifiers.InternalKey] != null && operation[OperationModifiers.InternalKey].IsBoolean)
modifiers.IsInternal = (bool)operation[OperationModifiers.InternalKey];
if (operation[OperationModifiers.DeprecatedKey] != null && operation[OperationModifiers.DeprecatedKey].IsBoolean)
modifiers.IsDeprecated = (bool)operation[OperationModifiers.DeprecatedKey];
if (operation[OperationModifiers.UseWrappingResultKey] != null && operation[OperationModifiers.UseWrappingResultKey].IsBoolean)
modifiers.UseWrappingResult = (bool)operation[OperationModifiers.UseWrappingResultKey];
if (operation[OperationModifiers.AllowEmptyResultKey] != null && operation[OperationModifiers.AllowEmptyResultKey].IsBoolean)
modifiers.AllowEmptyResult = (bool)operation[OperationModifiers.AllowEmptyResultKey];
if (operation[OperationModifiers.WrappedResultShapeKey] != null && operation[OperationModifiers.WrappedResultShapeKey].IsString)
modifiers.WrappedResultShape = (string)operation[OperationModifiers.WrappedResultShapeKey];
if (operation[OperationModifiers.WrappedResultMemberKey] != null && operation[OperationModifiers.WrappedResultMemberKey].IsString)
modifiers.WrappedResultMember = (string)operation[OperationModifiers.WrappedResultMemberKey];
if (operation[OperationModifiers.DocumentationKey] != null && operation[OperationModifiers.DocumentationKey].IsString)
modifiers.Documentation = (string)operation[OperationModifiers.DocumentationKey];
if (operation[OperationModifiers.DeprecatedMessageKey] != null && operation[OperationModifiers.DeprecatedMessageKey].IsString)
modifiers.DeprecatedMessage = (string)operation[OperationModifiers.DeprecatedMessageKey];
if (operation[OperationModifiers.MarshallNameOverrides] != null &&
operation[OperationModifiers.MarshallNameOverrides].IsArray)
{
foreach (JsonData marshalOverride in operation[OperationModifiers.MarshallNameOverrides])
{
var shapeName = marshalOverride.PropertyNames.First();
var marshalData = marshalOverride[shapeName];
modifiers.AddMarshallNameOverride(shapeName, marshalData);
}
}
return modifiers;
}
public JsonData GetExamples(string operationName)
{
if (_documentRoot.PropertyNames.Contains(ExamplesKey) &&
_documentRoot[ExamplesKey].IsObject &&
_documentRoot[ExamplesKey].PropertyNames.Contains(operationName) &&
_documentRoot[ExamplesKey][operationName].IsArray)
return _documentRoot[ExamplesKey][operationName];
var empty = new JsonData();
empty.SetJsonType(JsonType.Array);
return empty;
}
public bool HasExamples
{
get
{
return _documentRoot.PropertyNames.Contains(ExamplesKey) &&
_documentRoot[ExamplesKey].IsObject &&
_documentRoot[ExamplesKey].PropertyNames.Any();
}
}
#region Samples Key
public class SampleInfo
{
public const string SolutionPathKey = "solutionPath";
}
#endregion
#region OperationModifiers
/// <summary>
/// A class used to specify modifiers of a client method
/// </summary>
public class OperationModifiers
{
public const string OperationModifiersKey = "operationModifiers";
public const string NameKey = "name";
public const string ExcludeKey = "exclude";
public const string InternalKey = "internal";
public const string UseWrappingResultKey = "useWrappingResult";
public const string AllowEmptyResultKey = "allowEmptyResult";
public const string WrappedResultShapeKey = "wrappedResultShape";
public const string WrappedResultMemberKey = "wrappedResultMember";
public const string MarshallNameOverrides = "marshallNameOverrides";
public const string DeprecatedKey = "deprecated";
public const string DeprecatedMessageKey = "deprecatedMessage";
public const string DocumentationKey = "documentation";
// within a marshal override for a shape; one or both may be present
public const string MarshallLocationName = "marshallLocationName";
public const string MarshallName = "marshallName";
private Dictionary<string, JsonData> _marshallNameOverrides = null;
/// <summary>
/// The name of the operation modified
/// </summary>
public string Name
{
get;
set;
}
/// <summary>
/// Indicates if the operation should be excluded
/// </summary>
public bool IsExcluded
{
get;
set;
}
/// <summary>
/// Indicates if the operation should be marked internal in the client
/// </summary>
public bool IsInternal
{
get;
set;
}
/// <summary>
/// Indicates if the operation should be marked deprecated in the client
/// </summary>
public bool IsDeprecated
{
get;
set;
}
public bool UseWrappingResult
{
get;
set;
}
/// <summary>
/// Allows the operation to return an empty result when the operation is modeled to return body result structure.
/// </summary>
public bool AllowEmptyResult
{
get;
set;
}
public string WrappedResultShape
{
get;
set;
}
public string WrappedResultMember
{
get;
set;
}
public string Documentation
{
get;
set;
}
public string DeprecatedMessage
{
get;
set;
}
public void AddMarshallNameOverride(string shapeName, JsonData overrides)
{
if (_marshallNameOverrides == null)
_marshallNameOverrides = new Dictionary<string, JsonData>();
_marshallNameOverrides.Add(shapeName, overrides);
}
public MarshallNameOverrides GetMarshallNameOverrides(string shapeName, string propertyName)
{
if (_marshallNameOverrides == null || !_marshallNameOverrides.ContainsKey(shapeName))
return null;
var shapeOverrides = _marshallNameOverrides[shapeName][propertyName];
if (shapeOverrides == null)
return null;
var overrideData = new MarshallNameOverrides();
if (shapeOverrides[MarshallLocationName] != null)
overrideData.MarshallLocationName = (string)shapeOverrides[MarshallLocationName];
if (shapeOverrides[MarshallName] != null)
overrideData.MarshallName = (string)shapeOverrides[MarshallName];
return overrideData;
}
}
public class ArnFieldProperties
{
public ArnFieldProperties(bool arnFieldExists, string arnFieldName)
{
ArnFieldExists = arnFieldExists;
ArnFieldName = arnFieldName;
}
public bool ArnFieldExists { get; set; }
public string ArnFieldName { get; set; }
}
/// <summary>
/// Contains the naming overrides for a property in a member for marshal
/// purposes. This allows shapes that are reused to employ different wire
/// names between operations if necessary.
/// </summary>
public class MarshallNameOverrides
{
public string MarshallName { get; set; }
public string MarshallLocationName { get; set; }
}
#endregion
#region DataTypeOverride
/// <summary>
/// A class that represents type overrides for a member
/// </summary>
public class DataTypeOverride
{
/// <summary>
/// Creates an override class that specifies overrides for a member
/// </summary>
/// <param name="dataType">The new custom type for a member</param>
/// <param name="marshaller">The custom marshaller for a member</param>
/// <param name="unmarshaller">The custom unmarshaller for a member</param>
public DataTypeOverride(string dataType, string marshaller, string unmarshaller)
{
this.DataType = dataType;
this.Marshaller = marshaller;
this.Unmarshaller = unmarshaller;
}
/// <summary>
/// The new datatype for the property
/// </summary>
public string DataType
{
get;
private set;
}
/// <summary>
/// The new marshaller for the property
/// </summary>
public string Marshaller
{
get;
private set;
}
/// <summary>
/// The new unmarshaller for the property
/// </summary>
public string Unmarshaller
{
get;
private set;
}
}
#endregion
#region RuntimePipelineOverride
/// <summary>
/// A class used to specify overidden runtime details
/// </summary>
public class RuntimePipelineOverride
{
public List<Override> Overrides { get; set; }
/// <summary>
/// Creates a runtime pipeline override that specifies new details about the pipeline
/// </summary>
public RuntimePipelineOverride()
{
this.Overrides = new List<Override>();
}
/// <summary>
/// A class that contains specific override details
/// </summary>
public class Override
{
public Override()
{
}
/// <summary>
/// Allows overriding a method in the pipeline
/// </summary>
public string OverrideMethod { get; set; }
/// <summary>
/// Overrides the type in the pipeline
/// </summary>
public string NewType { get; set; }
/// <summary>
/// Overrides the targettype in the pipeline
/// </summary>
public string TargetType { get; set; }
/// <summary>
/// Overrides the constructor input in the pipeline
/// </summary>
public string ConstructorInput { get; set; }
/// <summary>
/// Overrides the condition of the override input in the pipeline.
/// A condition on an override allows a customization that is only
/// executed when a defined condition is met. The condition must be
/// any code that would be valid within the Amazon[ServiceName]Client
/// class for the ServiceName where the override is being made. For
/// example, a valid condition is:
/// "if(this.Config.RetryMode == RequestRetryMode.Legacy)"
/// </summary>
public string Condition { get; set; }
/// <summary>
/// Proceses the override method and provides what type of override should be generated based on the string
/// </summary>
public string FormattedOverrideMethod
{
get
{
switch (OverrideMethod)
{
case "add": return "AddHandler";
case "addAfter": return string.Format(CultureInfo.InvariantCulture,
"AddHandlerAfter<{0}>", this.TargetType);
case "addBefore": return string.Format(CultureInfo.InvariantCulture,
"AddHandlerBefore<{0}>", this.TargetType);
case "remove": return string.Format(CultureInfo.InvariantCulture,
"RemoveHandler<{0}>", this.TargetType);
case "replace": return string.Format(CultureInfo.InvariantCulture,
"ReplaceHandler<{0}>", this.TargetType);
default:
throw new ArgumentException("Invalid override method" + OverrideMethod,
"overrideMethod");
}
}
}
}
}
#endregion
}
#endregion
}
| 1,594 |
aws-sdk-net | aws | C# | namespace ServiceClientGenerator
{
public class EndpointConstant
{
public string Name { get; set; }
public string RegionCode { get; set; }
public string ConvertedRegionCode { get; set; }
public string RegionName { get; set; }
}
}
| 11 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
/// <summary>
/// Represents a code sample for an operation.
/// </summary>
public class Example : BaseModel
{
public const string
IdKey = "id",
TitleKey = "title",
DescriptionKey = "description",
InputKey = "input",
OutputKey = "output",
CommentsKey = "comments";
public Example(ServiceModel model, string operationName, JsonData data) : base(model, data)
{
this.OperationName = operationName;
}
/// <summary>
/// The name of the operation this sample is for
/// </summary>
public string OperationName { get; set; }
/// <summary>
/// The operation metadata associated with this example.
/// </summary>
public Operation Operation
{
get { return this.model.FindOperation(OperationName); }
}
/// <summary>
/// The example id taken from the model.
/// </summary>
/// <remarks>
/// This unique id is used for the region in the emitted code sample
/// that will be parsed to include the code in the documentation.
/// </remarks>
public string Id
{
get
{
return data.SafeGetString(IdKey);
}
}
/// <summary>
/// The title for the example.
/// </summary>
public string Title
{
get
{
return data.SafeGetString(TitleKey);
}
}
/// <summary>
/// Descriptive text for the example.
/// </summary>
public string Description
{
get
{
return data.SafeGetString(DescriptionKey);
}
}
/// <summary>
/// The sample data for the input parameters.
/// </summary>
public IDictionary<string, JsonData> InputParameters
{
get
{
var inputMap = data.SafeGet(InputKey);
if (null == inputMap)
return new Dictionary<string, JsonData>();
return inputMap.GetMap();
}
}
/// <summary>
/// The sample data for the output parameters.
/// </summary>
public IDictionary<string, JsonData> OutputParameters
{
get
{
var outputMap = data.SafeGet(OutputKey);
if (null == outputMap)
return new Dictionary<string, JsonData>();
return outputMap.GetMap();
}
}
/// <summary>
/// Comments for the sample input data.
/// </summary>
/// <remarks>
/// A map of property name to comment text.
/// </remarks>
public IDictionary<string, string> InputComments
{
get
{
return GetComments(InputKey);
}
}
/// <summary>
/// Comments for the sample response data.
/// </summary>
/// <remarks>
/// A map of property name to comment text.
/// </remarks>
public IDictionary<string, string> OutputComments
{
get
{
return GetComments(OutputKey);
}
}
// Common to the InputComments and OutputComments properties
private IDictionary<string, string> GetComments(string key)
{
var comments = this.data[CommentsKey];
if (null != comments)
{
var map = comments.SafeGet(key);
if (null != map)
return map.GetStringMap();
}
return new Dictionary<string, string>();
}
/// <summary>
/// For the request, build the literals and/or instantiators to assign to each
/// property in the request shape for which sample data was supplied in the example.
/// </summary>
/// <returns>A list of strings of the form 'PropertyName = value' with comments at the
/// end, if present.</returns>
public IList<string> GetRequestAssignments(int currentIndent)
{
var result = new List<string>();
if (!InputParameters.Any())
return result;
var last = InputParameters.Last().Key;
foreach (var param in InputParameters)
{
var member = Operation.RequestStructure.Members.GetMemberByName(param.Key);
if (null == member)
continue;
var sb = new StringBuilder();
var cb = new CodeBuilder(sb, currentIndent);
cb.Append(member.PropertyName).Append(" = ");
GetSampleLiteral(member, param.Value, cb);
if (param.Key != last)
cb.Append(",");
if (InputComments.ContainsKey(param.Key))
cb.Append(" // ").Append(InputComments[param.Key]);
result.Add(sb.ToString());
}
return result;
}
public IList<string> GetResponseAssignments()
{
var result = new List<string>();
foreach (var param in OutputParameters)
{
var member = Operation.ResponseStructure.Members.GetMemberByName(param.Key);
if (null == member)
continue;
var shapeType = ShapeType(member.Shape);
result.Add(string.Format("{0} {1} = response.{2};{3}",
shapeType,
member.ArgumentName,
member.PropertyName,
OutputComments.ContainsKey(param.Key) ? " // " + OutputComments[param.Key] : ""));
}
return result;
}
/// <summary>
/// Given a member and sample data, build a literal/instantation for the
/// member's type with the sample data.
/// </summary>
/// <param name="member">The member in the model</param>
/// <param name="data">Sample data to populate the literal with</param>
/// <param name="cb">A CodeBuilder instance to write the code to.</param>
public void GetSampleLiteral(Member member, JsonData data, CodeBuilder cb)
{
GetSampleLiteral(member.Shape, data, cb);
}
/// <summary>
/// Given a Shape and sample data, build a literal/instantiation for the
/// Shape's type with the sample data.
/// </summary>
/// <param name="shape">The Shape in the model</param>
/// <param name="data">Sample data to populate the literal with</param>
/// <param name="cb">A CodeBuilder instance to write the code to.</param>
public void GetSampleLiteral(Shape shape, JsonData data, CodeBuilder cb)
{
if (shape.IsString && data.IsString)
cb.AppendQuote(data.ToString());
else if (shape.IsBoolean)
cb.Append(data.ToString().ToLower());
else if (shape.IsFloat || shape.IsInt || shape.IsDouble || shape.IsLong)
cb.Append(data.ToString());
else if (shape.IsList && data.IsArray)
{
var itemType = shape.ListShape;
cb.AppendFormat("new List<{0}> ", ShapeType(itemType)).OpenBlock();
for (int i = 0; i < data.Count; i++)
{
GetSampleLiteral(itemType, data[i], cb);
if (i < (data.Count - 1))
cb.AppendLine(",");
}
cb.CloseBlock();
}
else if (shape.IsMap && data.IsObject)
{
var keyType = shape.KeyShape;
var valType = shape.ValueShape;
cb.AppendFormat("new Dictionary<{0}, {1}> ", ShapeType(keyType), ShapeType(valType));
cb.OpenBlock();
foreach (var k in data.PropertyNames)
{
cb.Append("{ ");
GetSampleLiteral(keyType, k, cb);
cb.Append(", ");
GetSampleLiteral(valType, data[k], cb);
cb.Append(" }");
if (k != data.PropertyNames.Last())
cb.AppendLine(",");
}
cb.CloseBlock();
}
else if (shape.IsStructure && data.IsObject)
{
cb.AppendFormat("new {0} ", ShapeType(shape));
if (data.PropertyNames.Count() > 1)
cb.OpenBlock();
else
cb.Append("{ ");
foreach (var field in data.PropertyNames)
{
var property = shape.Members.GetMemberByName(field);
if (null == property)
continue;
cb.AppendFormat("{0} = ", property.PropertyName);
GetSampleLiteral(property, data[field], cb);
if (field != data.PropertyNames.Last())
cb.AppendLine(",");
}
if (data.PropertyNames.Count() > 1)
cb.CloseBlock();
else
cb.Append(" }");
}
else if (shape.IsMemoryStream && data.IsString)
{
cb.AppendFormat("new {0}({1})", ShapeType(shape), data.ToString());
}
else if (shape.IsDateTime)
{
string exampleValue = null;
if (data.IsString)
{
var textValue = data.ToString();
DateTime parsedDateTime;
if (DateTime.TryParse(textValue, out parsedDateTime))
{
exampleValue = string.Format("new DateTime({0}, DateTimeKind.Utc)",
parsedDateTime.ToString("yyyy, M, d, h, m, s"));
}
}
if (string.IsNullOrEmpty(exampleValue))
{
exampleValue = "DateTime.UtcNow";
}
cb.Append(exampleValue);
}
else
{
// default value
cb.Append("<data>");
}
}
/// <summary>
/// Return the type name for a shape
/// </summary>
/// <param name="shape">The shape to get the type name for</param>
/// <returns></returns>
private string ShapeType(Shape shape)
{
if (shape.IsBoolean)
return "bool";
if (shape.IsInt)
return "int";
if (shape.IsLong)
return "long";
if (shape.IsFloat)
return "float";
if (shape.IsDouble)
return "double";
if (shape.IsDateTime)
return "DateTime";
if (shape.IsMemoryStream)
return "MemoryStream";
if (shape.IsMap)
return string.Format("Dictionary<{0}, {1}>", ShapeType(shape.KeyShape), ShapeType(shape.ValueShape));
if (shape.IsList)
return string.Format("List<{0}>", ShapeType(shape.ListShape));
if (shape.IsStructure)
return shape.Name;
if (shape.IsPrimitiveType)
return shape.Type;
throw new InvalidOperationException(string.Format("Unable to resolve type for shape {0}", shape.Name));
}
}
}
| 375 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using Json.LitJson;
namespace ServiceClientGenerator
{
#region ExceptionShape
/// <summary>
/// The model that represents exceptions for the service
/// </summary>
public class ExceptionShape : Shape
{
/// <summary>
/// Creates a model that represents an exception in the service processed in the response
/// </summary>
/// <param name="data">The json data that contains information about the exception found in the model</param>
/// <param name="name">The name of the exception</param>
/// <param name="documentation">The documentation for the exception found in the service model json</param>
/// <param name="structure">The shape that represents the exception</param>
public ExceptionShape(ServiceModel model, string name, JsonData data) : base(model, name, data)
{
}
/// <summary>
/// Returns the name of the exception with the word Exception appended to the end, removes the word fault from the end if it's there
/// </summary>
public override string Name
{
get
{
string normalizedName;
if (base.Name.EndsWith("Exception"))
{
normalizedName = base.Name;
}
else if (base.Name.EndsWith("Fault"))
{
string trimmedName = base.Name.Substring(0, base.Name.Length - 5);
normalizedName = $"{trimmedName}Exception";
}
else
{
normalizedName = $"{base.Name}Exception";
}
return normalizedName;
}
}
/// <summary>
/// Members of the shape, defined by another shape.
/// This overrider removes Message member becuase it's passed to System.Exception directly
/// </summary>
public override IList<Member> Members
{
get
{
return base.Members
.Where(member => !member.PropertyName.Equals("Message"))
.ToList();
}
}
/// <summary>
/// The error code for the exception, returns the name if one is not specified in the json model.
/// We first check in any referenced structure, then fall back to the exception shape to discover
/// the code.
/// </summary>
public string Code
{
get
{
if (HasErrorCode)
{
return ErrorCode;
}
var code = data[ErrorKey]?[ErrorCodeKey]?.ToString();
return code ?? base.Name;
}
}
/// <summary>
/// Determines if the exception is marked retryable
/// </summary>
public bool IsRetryable
{
get
{
return this.data[RetryableKey] != null;
}
}
/// <summary>
/// Determines if a retryable exception is marked as throttling
/// </summary>
public bool Throttling
{
get
{
var throttling = this.data[RetryableKey]?[ThrottlingKey];
return (bool)(throttling ?? false);
}
}
}
#endregion
}
| 111 |
aws-sdk-net | aws | C# | using System.IO;
namespace ServiceClientGenerator
{
public interface IFileReader
{
/// <inheritdoc cref="File.ReadAllText(string)"/>
string ReadAllText(string path);
}
public class FileReader : IFileReader
{
/// <inheritdoc cref="File.ReadAllText(string)"/>
public string ReadAllText(string path)
{
return File.ReadAllText(path);
}
}
} | 19 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Json.LitJson;
using ServiceClientGenerator.DefaultConfiguration;
using ServiceClientGenerator.Endpoints;
using ServiceClientGenerator.Endpoints.Tests;
namespace ServiceClientGenerator
{
/// <summary>
/// Loads the generator control manifest document. This document
/// yields the Visual Studio project metadata (for new project files
/// that we create) and the set of service configurations available
/// to process.
/// </summary>
public class GenerationManifest
{
abstract class ModelsSectionKeys
{
public const string ActiveKey = "active";
public const string NamespaceKey = "namespace";
public const string BaseNameKey = "base-name";
public const string NugetPackageTitleSuffix = "nuget-package-title-suffix";
public const string DefaultRegionKey = "default-region";
public const string GenerateClientConstructorsKey = "generate-client-constructors";
public const string CustomizationFileKey = "customization-file";
public const string MaxRetriesKey = "max-retries";
public const string SynopsisKey = "synopsis";
public const string NetStandardSupportKey = "netstandard-support";
public const string DependenciesKey = "dependencies";
public const string ReferenceDependenciesKey = "reference-dependencies";
public const string NugetDependenciesKey = "nuget-dependencies";
public const string DependencyNameKey = "name";
public const string DependencyVersionKey = "version";
public const string DependencyHintPathKey = "hint-path";
public const string ParentBaseNameKey = "parent-base-name";
public const string TagsKey = "tags";
public const string LicenseUrlKey = "license-url";
public const string TestServiceKey = "test-service";
public const string LegacyServiceIdKey = "legacy-service-id";
}
abstract class ProjectsSectionKeys
{
public const string ProjectsKey = "projects";
public const string NameKey = "name";
public const string ConfigurationsKey = "configurations";
public const string TargetFrameworksKey = "targetFrameworks";
public const string DefineConstantsKey = "defineConstants";
public const string BinSubFolderKey = "binSubFolder";
public const string TemplateKey = "template";
public const string PlatformCodeFoldersKey = "platformCodeFolders";
public const string ExtraTestProjects = "extraTestProjects";
public const string NuGetTargetFrameworkKey = "nugetTargetPlatform";
public const string PlatformExcludeFoldersKey = "excludeFolders";
public const string FrameworkPathOverrideKey = "frameworkPathOverride";
public const string FrameworkRefernecesKey = "frameworkReferences";
public const string EmbeddedResourcesKey = "embeddedResources";
public const string UnitTestProjectsKey = "unittestprojects";
public const string NoWarn = "noWarn";
public const string PackageReferences = "packageReferences";
public const string OutputPathOverrideKey = "outputPathOverride";
}
/// <summary>
/// URL for Apache License 2.0
/// </summary>
public const string ApacheLicenseURL = @"http://aws.amazon.com/apache2.0/";
/// <summary>
/// The set of services declared in the manifest as supporting generation.
/// </summary>
public IEnumerable<ServiceConfiguration> ServiceConfigurations { get; private set; }
//public IDictionary<string, string> ServiceVersions { get; private set; }
/// <summary>
/// The set of per-platform project metadata needed to generate a platform
/// specific project file for a service.
/// </summary>
public IEnumerable<ProjectFileConfiguration> ProjectFileConfigurations { get; private set; }
public IEnumerable<ProjectFileConfiguration> UnitTestProjectFileConfigurations { get; private set; }
public string CoreFileVersion { get; private set; }
public string CoreVersion { get; private set; }
public bool DefaultToPreview
{
get;
private set;
}
public string PreviewLabel
{
get;
private set;
}
/// <summary>
/// Model representing the default configuration modes as built
/// from the sdk-default-configurations.json file.
/// </summary>
public DefaultConfiguration.DefaultConfigurationModel DefaultConfiguration { get; set; }
//This should be the same version number as SdkVersioning.DefaultAssemblyVersion in BuildTasks
private const string DefaultAssemblyVersion = "3.3";
/// <summary>
/// Processes the control manifest to yield the set of services available to
/// generate and the Visual Studio project file information used to create
/// new projects for services.
/// </summary>
/// <param name="options">GeneratorOptions containing information requred to load GenerationManifest</param>
public static GenerationManifest Load(GeneratorOptions options)
{
var generationManifest =
new GenerationManifest(
new DefaultConfigurationController(
new FileReader(),
new DefaultConfigurationParser()));
var manifest = LoadJsonFromFile(options.Manifest);
var versionsManifest = LoadJsonFromFile(options.Versions);
generationManifest.CoreFileVersion = versionsManifest["CoreVersion"].ToString();
generationManifest.CoreVersion = Utils.GetVersion(versionsManifest["OverrideCoreVersion"]?.ToString() ?? generationManifest.CoreFileVersion);
generationManifest.DefaultToPreview = (bool)versionsManifest["DefaultToPreview"];
if (generationManifest.DefaultToPreview)
{
generationManifest.PreviewLabel = (string)versionsManifest["PreviewLabel"];
}
if (!string.IsNullOrEmpty(generationManifest.PreviewLabel))
generationManifest.PreviewLabel = "-" + generationManifest.PreviewLabel;
generationManifest.LoadDefaultConfiguration(options.ModelsFolder);
generationManifest.LoadServiceConfigurations(manifest, versionsManifest["ServiceVersions"], options);
generationManifest.LoadProjectConfigurations(manifest);
generationManifest.LoadUnitTestProjectConfigurations(manifest);
return generationManifest;
}
/// <summary>
/// Loads the sdk-default-configurations.json file.
/// </summary>
private void LoadDefaultConfiguration(string manifestPath)
{
// ../../../ServiceModels/ + ../../
var repositoryRootDirectoryPath = Path.Combine(manifestPath, "..","..");
DefaultConfiguration = _defaultConfigurationController.LoadDefaultConfiguration(repositoryRootDirectoryPath);
}
/// <summary>
/// Recursively walk through the ServiceModels folder and load/parse the
/// model files to generate ServiceConfiguration objects.
/// </summary>
/// <param name="manifest">loaded _manifest.json file</param>
/// <param name="serviceVersions">loaded _sdk-versions.json file</param>
/// <param name="options">generator options</param>
void LoadServiceConfigurations(JsonData manifest, JsonData serviceVersions, GeneratorOptions options)
{
List<Tuple<JsonData, ServiceConfiguration>> modelConfigList = new List<Tuple<JsonData, ServiceConfiguration>>();
var serviceConfigurations = new List<ServiceConfiguration>();
var serviceDirectories = Utils.GetServiceDirectories(options);
foreach (string serviceDirectory in serviceDirectories)
{
string metadataJsonFile = Path.Combine(serviceDirectory, "metadata.json");
if (File.Exists(metadataJsonFile))
{
JsonData metadataNode = LoadJsonFromFile(metadataJsonFile);
var activeNode = metadataNode[ModelsSectionKeys.ActiveKey];
if (activeNode != null
&& activeNode.IsBoolean
&& !(bool)activeNode )
{
continue;
}
var serviceModelFileName = GetLatestModel(serviceDirectory);
string paginatorsFileName = GetLatestPaginators(serviceDirectory);
var config = CreateServiceConfiguration(metadataNode, serviceVersions, serviceDirectory, serviceModelFileName, paginatorsFileName);
serviceConfigurations.Add(config);
modelConfigList.Add(new Tuple<JsonData, ServiceConfiguration>(metadataNode, config));
}
}
if (string.IsNullOrEmpty(options.ServiceModels))
{
// We skip this check if ServiceModels provided, as we would never satisfy condition below.
//
// We need to make sure that we have configuration files for all expected services and
// that there aren't mismatches in the service names.
foreach (string serviceVersionEntry in serviceVersions.GetMap().Keys)
{
if (!serviceConfigurations.Any(config => config.ServiceNameRoot == serviceVersionEntry))
{
throw new Exception($"Service entry {serviceVersionEntry} doesn't match any of the available service configurations.");
}
}
}
// The parent model for current model, if set, the client will be generated
// in the same namespace and share common types.
foreach (var modelConfig in modelConfigList)
{
var modelNode = modelConfig.Item1;
var config = modelConfig.Item2;
var parentClassName = modelNode[ModelsSectionKeys.ParentBaseNameKey] != null ? modelNode[ModelsSectionKeys.ParentBaseNameKey].ToString() : null;
if (parentClassName != null)
{
try
{
config.ParentConfig = serviceConfigurations.Single(c => c.ClassName.Equals(parentClassName));
}
catch (KeyNotFoundException exception)
{
// Note : the parent model should be defined in the manifest before being referred by a child model
throw new KeyNotFoundException(
string.Format("A parent model with name {0} is not defined in the manifest", parentClassName),
exception); ;
}
}
}
ServiceConfigurations = serviceConfigurations
.OrderBy(sc => sc.ServiceDependencies.Count)
.ToList();
}
/// <summary>
/// Use the date order of the models combined with default string sort
/// to find the latest models file
/// </summary>
/// <param name="serviceDirectory"></param>
/// <returns></returns>
private static string GetLatestModel(string serviceDirectory)
{
string latestModelName = string.Empty;
foreach (string modelName in Directory.GetFiles(serviceDirectory, "*.normal.json", SearchOption.TopDirectoryOnly))
{
if (string.Compare(latestModelName, modelName) < 0)
{
latestModelName = modelName;
}
}
if (string.IsNullOrEmpty(latestModelName))
{
throw new FileNotFoundException("Failed to find a model file in " + serviceDirectory);
}
return Path.GetFileName(latestModelName);
}
/// <summary>
/// Use the date order of the paginators combined with default string sort
/// to find the latest paginators file
/// </summary>
/// <param name="serviceDirectory"></param>
/// <returns></returns>
private static string GetLatestPaginators(string serviceDirectory)
{
var latestPaginatorsName = Directory.GetFiles(serviceDirectory, "*.paginators.json", SearchOption.TopDirectoryOnly)
.OrderBy(x => x).FirstOrDefault() ?? "";
return Path.GetFileName(latestPaginatorsName);
}
private const string EndpointRuleSetFile = "endpoint-rule-set.json";
private const string EndpointRuleSetTestsFile = "endpoint-tests.json";
private ServiceConfiguration CreateServiceConfiguration(JsonData modelNode, JsonData serviceVersions, string serviceDirectoryPath, string serviceModelFileName, string servicePaginatorsFileName)
{
var modelFullPath = Path.Combine(serviceDirectoryPath, serviceModelFileName);
var paginatorsFullPath = Path.Combine(serviceDirectoryPath, servicePaginatorsFileName);
JsonData metadata = JsonMapper.ToObject(File.ReadAllText(modelFullPath))[ServiceModel.MetadataKey];
// A new config that the api generates from
var modelName = Path.GetFileName(serviceDirectoryPath);
var config = new ServiceConfiguration
{
ModelName = modelName,
ModelPath = modelFullPath,
PaginatorsPath = paginatorsFullPath,
Namespace = Utils.JsonDataToString(modelNode[ModelsSectionKeys.NamespaceKey]), // Namespace of the service if it's different from basename
ClassNameOverride = Utils.JsonDataToString(modelNode[ModelsSectionKeys.BaseNameKey]),
DefaultRegion = Utils.JsonDataToString(modelNode[ModelsSectionKeys.DefaultRegionKey]),
GenerateConstructors = modelNode[ModelsSectionKeys.GenerateClientConstructorsKey] == null || (bool)modelNode[ModelsSectionKeys.GenerateClientConstructorsKey], // A way to prevent generating basic constructors
IsTestService = modelNode[ModelsSectionKeys.TestServiceKey] != null && (bool)modelNode[ModelsSectionKeys.TestServiceKey]
};
// Load endpoints ruleset and tests if present
var rulesetFileName = Directory.GetFiles(serviceDirectoryPath, "*." + EndpointRuleSetFile, SearchOption.TopDirectoryOnly).FirstOrDefault();
var testsFileName = Directory.GetFiles(serviceDirectoryPath, "*." + EndpointRuleSetTestsFile, SearchOption.TopDirectoryOnly).FirstOrDefault();
// We have found tests but not rules, something is wrong!
if (rulesetFileName == null && testsFileName != null)
{
throw new FileNotFoundException($"We have found endpoints tests but endpoints rules are missing. Expected file suffix is .{EndpointRuleSetFile}");
}
if (rulesetFileName != null)
{
var json = File.ReadAllText(rulesetFileName);
config.EndpointsRuleSet = JsonMapper.ToObject<RuleSet>(json);
if (testsFileName == null)
{
throw new FileNotFoundException($"Endpoints tests are missing. Expected file suffix is .{EndpointRuleSetTestsFile}");
}
json = File.ReadAllText(testsFileName);
config.EndpointTests = JsonMapper.ToObject<EndpointTests>(json);
}
if (modelNode[ModelsSectionKeys.NugetPackageTitleSuffix] != null)
config.NugetPackageTitleSuffix = modelNode[ModelsSectionKeys.NugetPackageTitleSuffix].ToString();
if (modelNode[ModelsSectionKeys.ReferenceDependenciesKey] != null)
{
config.ReferenceDependencies = new Dictionary<string, List<Dependency>>();
foreach (KeyValuePair<string, JsonData> kvp in modelNode[ModelsSectionKeys.ReferenceDependenciesKey])
{
var platformDependencies = new List<Dependency>();
foreach (JsonData item in kvp.Value)
{
var platformDependency = new Dependency
{
Name = item[ModelsSectionKeys.DependencyNameKey].ToString(),
Version = item.PropertyNames.Contains(ModelsSectionKeys.DependencyVersionKey) ? item[ModelsSectionKeys.DependencyVersionKey].ToString() : "0.0.0.0",
HintPath = item[ModelsSectionKeys.DependencyHintPathKey].ToString(),
};
platformDependencies.Add(platformDependency);
}
config.ReferenceDependencies.Add(kvp.Key, platformDependencies);
}
}
if (modelNode[ModelsSectionKeys.NugetDependenciesKey] != null)
{
config.NugetDependencies = new Dictionary<string, List<Dependency>>();
foreach (KeyValuePair<string, JsonData> kvp in modelNode[ModelsSectionKeys.NugetDependenciesKey])
{
var nugetDependencies = new List<Dependency>();
foreach (JsonData item in kvp.Value)
{
var nugetDependency = new Dependency
{
Name = item[ModelsSectionKeys.DependencyNameKey].ToString(),
Version = item[ModelsSectionKeys.DependencyVersionKey].ToString(),
};
nugetDependencies.Add(nugetDependency);
}
config.NugetDependencies.Add(kvp.Key, nugetDependencies);
}
}
config.Tags = new List<string>();
if (modelNode[ModelsSectionKeys.TagsKey] != null)
{
foreach (JsonData tag in modelNode[ModelsSectionKeys.TagsKey])
{
config.Tags.Add(tag.ToString());
}
}
// Provides a way to specify a customizations file rather than using a generated one
config.CustomizationsPath = modelNode[ModelsSectionKeys.CustomizationFileKey] == null
? DetermineCustomizationsPath(config.ServiceDirectoryName)
: Path.Combine(serviceDirectoryPath, modelNode[ModelsSectionKeys.CustomizationFileKey].ToString());
if (modelNode[ModelsSectionKeys.MaxRetriesKey] != null && modelNode[ModelsSectionKeys.MaxRetriesKey].IsInt)
config.OverrideMaxRetries = Convert.ToInt32(modelNode[ModelsSectionKeys.MaxRetriesKey].ToString());
if (modelNode[ModelsSectionKeys.SynopsisKey] != null)
config.Synopsis = (string)modelNode[ModelsSectionKeys.SynopsisKey];
if (modelNode[ModelsSectionKeys.LegacyServiceIdKey] != null)
config.LegacyServiceId = (string)modelNode[ModelsSectionKeys.LegacyServiceIdKey];
if (modelNode[ModelsSectionKeys.NetStandardSupportKey] != null)
config.NetStandardSupport = (bool)modelNode[ModelsSectionKeys.NetStandardSupportKey];
else
config.NetStandardSupport = true;
config.ServiceDependencies = new Dictionary<string, string>(StringComparer.Ordinal);
if (modelNode[ModelsSectionKeys.DependenciesKey] != null && modelNode[ModelsSectionKeys.DependenciesKey].IsArray)
{
foreach (var d in modelNode[ModelsSectionKeys.DependenciesKey])
{
config.ServiceDependencies.Add(d.ToString(), null);
}
}
if (modelNode[ModelsSectionKeys.LicenseUrlKey] != null && modelNode[ModelsSectionKeys.LicenseUrlKey].IsString)
{
config.LicenseUrl = modelNode[ModelsSectionKeys.LicenseUrlKey].ToString();
config.RequireLicenseAcceptance = true;
}
else
config.LicenseUrl = ApacheLicenseURL;
var serviceName = config.ServiceNameRoot;
var versionInfoJson = serviceVersions[serviceName];
if (versionInfoJson != null)
{
var dependencies = versionInfoJson["Dependencies"];
foreach (var name in dependencies.PropertyNames)
{
var version = dependencies[name].ToString();
config.ServiceDependencies[name] = version;
}
var versionText = versionInfoJson["Version"].ToString();
config.ServiceFileVersion = versionText;
var assemblyVersionOverride = versionInfoJson["AssemblyVersionOverride"];
if (assemblyVersionOverride != null)
{
config.ServiceAssemblyVersionOverride = assemblyVersionOverride.ToString();
}
if(versionInfoJson["InPreview"] != null && (bool)versionInfoJson["InPreview"])
config.InPreview = true;
else
config.InPreview = this.DefaultToPreview;
}
else
{
config.ServiceDependencies["Core"] = CoreFileVersion;
config.InPreview = this.DefaultToPreview;
config.ServiceFileVersion = DefaultAssemblyVersion;
var versionTokens = CoreVersion.Split('.');
if (!DefaultAssemblyVersion.StartsWith($"{versionTokens[0]}.{versionTokens[1]}"))
{
throw new NotImplementedException($"{nameof(DefaultAssemblyVersion)} should be updated to match the AWSSDK.Core minor version number.");
}
}
return config;
}
private static List<string> SafeGetStringList(JsonData data, string key)
{
var t = data.SafeGet(key);
if (t != null)
{
return (from object obj in t select obj.ToString()).ToList<string>();
}
else
{
return new List<string>();
}
}
private static List<T> SafeGetObjectList<T>(JsonData data, string key, Func<JsonData, T> converter)
{
var t = data.SafeGet(key);
if (t != null)
{
return (from JsonData obj in t select converter(obj)).ToList<T>();
}
else
{
return new List<T>();
}
}
private static ProjectFileConfiguration LoadProjectFileConfiguration(JsonData node)
{
return new ProjectFileConfiguration{
Name = node.SafeGetString(ProjectsSectionKeys.NameKey),
TargetFrameworkVersions = SafeGetStringList(node, ProjectsSectionKeys.TargetFrameworksKey),
CompilationConstants = SafeGetStringList(node, ProjectsSectionKeys.DefineConstantsKey),
BinSubFolder = node.SafeGetString(ProjectsSectionKeys.BinSubFolderKey),
Template = node.SafeGetString(ProjectsSectionKeys.TemplateKey),
NuGetTargetPlatform = node.SafeGetString(ProjectsSectionKeys.NuGetTargetFrameworkKey),
FrameworkPathOverride = node.SafeGetString(ProjectsSectionKeys.FrameworkPathOverrideKey),
NoWarn = node.SafeGetString(ProjectsSectionKeys.NoWarn),
OutputPathOverride = node.SafeGetString(ProjectsSectionKeys.OutputPathOverrideKey),
Configurations = SafeGetStringList(node, ProjectsSectionKeys.ConfigurationsKey),
EmbeddedResources = SafeGetStringList(node, ProjectsSectionKeys.EmbeddedResourcesKey),
PlatformCodeFolders = SafeGetStringList(node, ProjectsSectionKeys.PlatformCodeFoldersKey),
PlatformExcludeFolders = SafeGetStringList(node, ProjectsSectionKeys.PlatformExcludeFoldersKey),
DllReferences = SafeGetObjectList<Dependency>(node, ProjectsSectionKeys.FrameworkRefernecesKey, Dependency.ParseJson),
PackageReferences = SafeGetObjectList<ProjectFileCreator.PackageReference>(node, ProjectsSectionKeys.PackageReferences, ProjectFileCreator.PackageReference.ParseJson),
};
}
/// <summary>
/// Parses the Visual Studio project metadata entries from the manifest. These
/// are used when generating project files for a service.
/// Sets the ProjectFileConfigurations member on exit with the collection of loaded
/// configurations.
/// </summary>
/// <param name="document"></param>
void LoadProjectConfigurations(JsonData document)
{
var projectConfigurations = new List<ProjectFileConfiguration>();
var projectsNode = document[ProjectsSectionKeys.ProjectsKey];
foreach (JsonData projectNode in projectsNode)
{
var config = LoadProjectFileConfiguration(projectNode);
var extraTestProjects = projectNode.SafeGet(ProjectsSectionKeys.ExtraTestProjects);
if (extraTestProjects == null)
{
config.ExtraTestProjects = new List<string>();
}
else
{
config.ExtraTestProjects = (from object etp in extraTestProjects
select etp.ToString()).ToList();
}
projectConfigurations.Add(config);
}
ProjectFileConfigurations = projectConfigurations;
}
void LoadUnitTestProjectConfigurations(JsonData document)
{
IList<ProjectFileConfiguration> configuraitons = new List<ProjectFileConfiguration>();
var projectsNode = document[ProjectsSectionKeys.UnitTestProjectsKey];
foreach (JsonData projectNode in projectsNode)
{
var configuration = LoadProjectFileConfiguration(projectNode);
configuraitons.Add(configuration);
}
UnitTestProjectFileConfigurations = configuraitons;
}
/// <summary>
/// Finds the customizations file in \customizations as model.customizations.json if it's there
/// </summary>
/// <param name="model">The name of the model as defined in the _manifest</param>
/// <returns>Full path to the customization if it exists, null if it wasn't found</returns>
private static string DetermineCustomizationsPath(string serviceKey)
{
if (!Directory.Exists("customizations"))
{
return null;
}
var files = Directory.GetFiles("customizations", serviceKey + ".customizations.json").OrderByDescending(x => x);
return !files.Any() ? null : files.Single();
}
/// <summary>
/// Loads a JsonData object for data in a given file.
/// </summary>
/// <param name="path">Path to the JSON file.</param>
/// <returns>JsonData corresponding to JSON in the file.</returns>
private static JsonData LoadJsonFromFile(string path)
{
JsonData data;
using (var reader = new StreamReader(path))
data = JsonMapper.ToObject(reader);
return data;
}
private readonly IDefaultConfigurationController _defaultConfigurationController;
private GenerationManifest(IDefaultConfigurationController defaultConfigurationController)
{
_defaultConfigurationController = defaultConfigurationController;
}
public GenerationManifest()
{
}
}
}
| 592 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ServiceClientGenerator.Generators;
using ServiceClientGenerator.Generators.Examples;
using ServiceClientGenerator.Generators.Marshallers;
using ServiceClientGenerator.Generators.NuGet;
using ServiceClientGenerator.Generators.SourceFiles;
using ServiceClientGenerator.Generators.TestFiles;
using StructureGenerator = ServiceClientGenerator.Generators.SourceFiles.StructureGenerator;
using Json.LitJson;
using System.Collections.Concurrent;
using ServiceClientGenerator.Generators.Endpoints;
using ServiceClientGenerator.Endpoints.Partitions;
using EventStreamExceptionGenerator = ServiceClientGenerator.Generators.SourceFiles.Exceptions.EventStreamExceptions;
namespace ServiceClientGenerator
{
public class GeneratorDriver
{
/// <summary>
/// Generation manifest for the entire SDK.
/// </summary>
public GenerationManifest GenerationManifest { get; private set; }
/// <summary>
/// The configuration for the service, as read from the service models
/// manifest file.
/// </summary>
public ServiceConfiguration Configuration { get; private set; }
/// <summary>
/// The configurations for each supported platform that we can compile the service
/// against.
/// </summary>
public IEnumerable<ProjectFileConfiguration> ProjectFileConfigurations { get; private set; }
/// <summary>
/// Runtime options for the generation process, as supplied at the command line.
/// </summary>
public GeneratorOptions Options { get; private set; }
/// <summary>
/// The folder under which all of the source files for the service
/// will exist.
/// </summary>
public string ServiceFilesRoot { get; private set; }
/// <summary>
/// The folder under which the code analysis project for the service will exist.
/// </summary>
public string CodeAnalysisRoot { get; private set; }
/// <summary>
/// The folder under which all of the test files exist.
/// </summary>
public string TestFilesRoot { get; private set; }
/// <summary>
/// The folder under which the generated source files for a service will
/// be placed. Typically (ServiceFilesRoot)/Generated. All content in this
/// folder hierarchy will be deleted prior to generation if the 'Clean'
/// generation option is set.
/// </summary>
public string GeneratedFilesRoot { get; private set; }
/// <summary>
/// The folder where all the sample files are located
/// </summary>
public string SampleFilesRoot { get; private set; }
/// <summary>
/// The folder under which all of the unit files for the service
/// will exist.
/// </summary>
public string ServiceUnitTestFilesRoot { get; private set; }
private readonly HashSet<Shape> _structuresToProcess = new HashSet<Shape>();
private readonly HashSet<string> _processedStructures = new HashSet<string>();
private readonly HashSet<string> _processedUnmarshallers = new HashSet<string>();
private readonly HashSet<string> _processedMarshallers = new HashSet<string>();
private const string Bcl35SubFolder = "_bcl35";
private const string Bcl45SubFolder = "_bcl45";
private const string NetStandardSubFolder = "_netstandard";
private const string MobileSubFolder = "_mobile";
private const string UnitySubFolder = "_unity";
private string PaginatorsSubFolder = string.Format("Model{0}_bcl45+netstandard", Path.DirectorySeparatorChar);
private string GeneratedTestsSubFolder = string.Format("UnitTests{0}Generated", Path.DirectorySeparatorChar);
private string CustomizationTestsSubFolder = string.Format("UnitTests{0}Generated{0}Customizations", Path.DirectorySeparatorChar);
private string PaginatorTestsSubFolder = string.Format("UnitTests{0}Generated{0}_bcl45+netstandard{0}Paginators", Path.DirectorySeparatorChar);
public const string SourceSubFoldername = "src";
public const string TestsSubFoldername = "test";
public const string CodeAnalysisFoldername = "code-analysis";
public const string ServicesSubFoldername = "Services";
public const string ServicesAnalysisSubFolderName = "ServiceAnalysis";
public const string CoreSubFoldername = "Core";
public const string GeneratedCodeFoldername = "Generated";
public const string CommonTestSubFoldername = "Common";
public const string UnitTestsSubFoldername = "UnitTests";
public const string IntegrationTestsSubFolderName = "IntegrationTests";
// Records any new project files we produce as part of generation. If this collection is
// not empty when we've processed all source, we must update the solution files to add
// the new projects.
private static readonly Dictionary<string, ProjectFileCreator.ProjectConfigurationData> NewlyCreatedProjectFiles
= new Dictionary<string, ProjectFileCreator.ProjectConfigurationData>();
public HashSet<string> FilesWrittenToGeneratorFolder { get; private set; }
private static ConcurrentBag<string> codeGeneratedServiceNames = new ConcurrentBag<string>();
public GeneratorDriver(ServiceConfiguration config, GenerationManifest generationManifest, GeneratorOptions options)
{
FilesWrittenToGeneratorFolder = new HashSet<string>();
GenerationManifest = generationManifest;
Configuration = config;
ProjectFileConfigurations = GenerationManifest.ProjectFileConfigurations;
Options = options;
ServiceFilesRoot = Path.Combine(Options.SdkRootFolder, SourceSubFoldername, ServicesSubFoldername, Configuration.ServiceFolderName);
ServiceUnitTestFilesRoot = Path.Combine(Options.SdkRootFolder, TestsSubFoldername, ServicesSubFoldername, Configuration.ServiceFolderName);
if (config.IsTestService)
{
ServiceFilesRoot = ServiceUnitTestFilesRoot;
}
GeneratedFilesRoot = Path.Combine(ServiceFilesRoot, GeneratedCodeFoldername);
CodeAnalysisRoot = Path.Combine(Options.SdkRootFolder, CodeAnalysisFoldername, ServicesAnalysisSubFolderName, Configuration.ServiceFolderName);
TestFilesRoot = Path.Combine(Options.SdkRootFolder, TestsSubFoldername);
codeGeneratedServiceNames.Add(Configuration.ServiceFolderName);
}
public void Execute()
{
if (Configuration.ServiceModel.H2Support == H2SupportDegree.Required)
{
Console.WriteLine("This service requires HTTP2 for all operations. The AWS SDK for .NET does not yet support this functionality. Not generating service.");
return;
}
ValidateServiceModel();
this.FilesWrittenToGeneratorFolder.Clear();
if (Options.Clean && !Configuration.IsChildConfig)
{
Console.WriteLine(@"-clean option set, deleting previously-generated code under .\Generated subfolders");
Directory.Delete(GeneratedFilesRoot, true);
Directory.CreateDirectory(GeneratedFilesRoot);
}
// .NET Framework 3.5 version
ExecuteGenerator(new ServiceClients(), "Amazon" + Configuration.ClassName + "Client.cs", Bcl35SubFolder);
ExecuteGenerator(new ServiceInterface(), "IAmazon" + Configuration.ClassName + ".cs", Bcl35SubFolder);
// .NET Framework 4.5 version
ExecuteGenerator(new ServiceClients45(), "Amazon" + Configuration.ClassName + "Client.cs", Bcl45SubFolder);
ExecuteGenerator(new ServiceInterface45(), "IAmazon" + Configuration.ClassName + ".cs", Bcl45SubFolder);
// .NET Standard version
ExecuteGenerator(new ServiceClientsNetStandard(), "Amazon" + Configuration.ClassName + "Client.cs", NetStandardSubFolder);
ExecuteGenerator(new ServiceInterfaceNetStandard(), "IAmazon" + Configuration.ClassName + ".cs", NetStandardSubFolder);
if (string.IsNullOrEmpty(Options.SelfServiceModel))
{
// Do not generate AssemblyInfo.cs and nuspec file for child model.
// Use the one generated for the parent model.
if (!this.Configuration.IsChildConfig && !Configuration.IsTestService)
{
GenerateNuspec();
GenerateCodeAnalysisProject();
}
}
if (!this.Configuration.IsChildConfig)
{
ExecuteGeneratorAssemblyInfo();
}
// Client config object
ExecuteGenerator(new Generators.SourceFiles.DefaultConfiguration(), "Amazon" + Configuration.ClassName + "DefaultConfiguration.cs");
ExecuteGenerator(new ServiceConfig(), "Amazon" + Configuration.ClassName + "Config.cs");
ExecuteGenerator(new ServiceMetadata(), "Amazon" + Configuration.ClassName + "Metadata.cs", "Internal");
if (Configuration.EndpointsRuleSet != null)
{
ExecuteGenerator(new EndpointParameters(), "Amazon" + Configuration.ClassName + "EndpointParameters.cs");
ExecuteGenerator(new EndpointProvider(), "Amazon" + Configuration.ClassName + "EndpointProvider.cs", "Internal");
ExecuteGenerator(new EndpointResolver(), "Amazon" + Configuration.ClassName + "EndpointResolver.cs", "Internal");
}
if (Configuration.EndpointTests != null)
{
ExecuteTestGenerator(new EndpointProviderTests(), Configuration.ClassName + "EndpointProviderTests.cs", "Endpoints");
}
if (Configuration.Namespace == "Amazon.S3")
{
ExecuteProjectFileGenerators();
return;
}
// The top level request that all operation requests are children of
ExecuteGenerator(new BaseRequest(), "Amazon" + Configuration.ClassName + "Request.cs", "Model");
var enumFileName = this.Configuration.IsChildConfig ?
string.Format("ServiceEnumerations.{0}.cs", Configuration.ClassName) : "ServiceEnumerations.cs";
// Any enumerations for the service
this.ExecuteGenerator(new ServiceEnumerations(), enumFileName);
#if !BCL35
// Any paginators for the service
if (Configuration.ServiceModel.HasPaginators)
{
foreach (var operation in Configuration.ServiceModel.Operations)
{
GeneratePaginator(operation);
}
ExecuteGenerator(new ServicePaginatorFactoryInterface(), $"I{Configuration.ServiceNameRoot}PaginatorFactory.cs", PaginatorsSubFolder);
ExecuteGenerator(new ServicePaginatorFactory(), $"{Configuration.ServiceNameRoot}PaginatorFactory.cs", PaginatorsSubFolder);
// Paginator tests only need to be generated against a single service,
// so generate for the Test service
if (Configuration.IsTestService)
GeneratePaginatorTests();
}
#endif
// Do not generate base exception if this is a child model.
// We use the base exceptions generated for the parent model.
if (!this.Configuration.IsChildConfig)
{
this.ExecuteGenerator(new BaseServiceException(), "Amazon" + this.Configuration.ClassName + "Exception.cs");
}
// Generates the Request, Response, Marshaller, Unmarshaller, and Exception objects for a given client operation
foreach (var operation in Configuration.ServiceModel.Operations)
{
GenerateRequest(operation);
GenerateResponse(operation);
GenerateRequestMarshaller(operation);
GenerateResponseUnmarshaller(operation);
GenerateEndpointDiscoveryMarshaller(operation);
GenerateExceptions(operation);
}
if (Configuration.ServiceModel.Customizations.GenerateCustomUnmarshaller)
{
GenerateCustomUnmarshallers(Configuration.ServiceModel.Customizations.CustomUnmarshaller);
}
// Generate any missed structures that are not defined or referenced by a request, response, marshaller, unmarshaller, or exception of an operation
GenerateStructures();
var fileName = string.Format("{0}MarshallingTests.cs", Configuration.ClassName);
// Generate tests based on the type of request it is
if (Configuration.ServiceModel.Type == ServiceType.Json)
ExecuteTestGenerator(new JsonMarshallingTests(), fileName, "Marshalling");
else if (Configuration.ServiceModel.Type == ServiceType.Query)
{
if (Configuration.ServiceModel.IsEC2Protocol)
ExecuteTestGenerator(new AWSQueryEC2MarshallingTests(), fileName, "Marshalling");
else
ExecuteTestGenerator(new AWSQueryMarshallingTests(), fileName, "Marshalling");
}
else if (Configuration.ServiceModel.Type == ServiceType.Rest_Xml || Configuration.ServiceModel.Type == ServiceType.Rest_Json)
ExecuteTestGenerator(new RestMarshallingTests(), fileName, "Marshalling");
//Generate endpoint discovery tests for classes that have an endpoint operation
if(Configuration.ServiceModel.FindEndpointOperation() != null)
{
fileName = string.Format("{0}EndpointDiscoveryMarshallingTests.cs", Configuration.ClassName);
ExecuteTestGenerator(new EndpointDiscoveryMarshallingTests(), fileName, "Marshalling");
}
// Test that simple customizations were generated correctly
GenerateCustomizationTests();
ExecuteProjectFileGenerators();
if (this.Configuration.ServiceModel.Customizations.HasExamples)
{
var servicename = Configuration.Namespace.Split('.').Last();
ExecuteExampleGenerator(new ExampleCode(), servicename + ".GeneratedSamples.cs", servicename);
ExecuteExampleGenerator(new ExampleMetadata(), servicename + ".GeneratedSamples.extra.xml");
}
}
/// <summary>
/// Generates the request class for the operation.
/// </summary>
/// <param name="operation">The operation object which contains info about what the request needs to contain for the operation</param>
void GenerateRequest(Operation operation)
{
var requestGenerator = new StructureGenerator
{
ClassName = operation.Name + "Request",
BaseClass = string.Format("Amazon{0}Request", Configuration.ClassName),
StructureType = StructureType.Request,
Operation = operation
};
if (operation.RequestStructure != null)
{
requestGenerator.Structure = this.Configuration.ServiceModel.FindShape(operation.RequestStructure.Name);
}
this.ExecuteGenerator(requestGenerator, requestGenerator.ClassName + ".cs", "Model");
if (operation.RequestStructure != null)
this.DetermineStructuresToProcess(operation.RequestStructure, false);
}
private void ValidateServiceModel()
{
// Check to see if any of the GET operations have invalid request body members.
foreach (var operation in Configuration.ServiceModel.Operations)
{
// These methods have already been released. The are broken and we need to work with the service teams to get them fixed.
if (string.Equals(operation.HttpMethod, "GET", StringComparison.InvariantCultureIgnoreCase) && operation.RequestHasBodyMembers)
{
if ((string.Equals("QuickSight", Configuration.ServiceId) && string.Equals("ListIAMPolicyAssignments", operation.Name)) ||
(string.Equals("OpenSearch", Configuration.ServiceId) && string.Equals("DescribeDomainAutoTunes", operation.Name)) ||
(string.Equals("ivs", Configuration.ServiceId) && string.Equals("ListTagsForResource", operation.Name)) ||
(string.Equals("EFS", Configuration.ServiceId) && string.Equals("DescribeAccountPreferences", operation.Name)) ||
(string.Equals("SESv2", Configuration.ServiceId) && string.Equals("ListContacts", operation.Name)) ||
(string.Equals("SESv2", Configuration.ServiceId) && string.Equals("ListImportJobs", operation.Name)) ||
(string.Equals("Elasticsearch Service", Configuration.ServiceId) && string.Equals("DescribeDomainAutoTunes", operation.Name))
)
{
continue;
}
throw new InvalidOperationException($"Failed to generate for service with Id {Configuration.ServiceId} because it contains a GET operation ({operation.Name}) with request body members.");
}
}
}
private void DetermineStructuresToProcess(Shape containingShape, bool includeContainingShape)
{
if (containingShape.IsStructure)
{
if (containingShape.IsDocument)
return;
if (this._structuresToProcess.Contains(containingShape))
return;
else if (includeContainingShape)
this._structuresToProcess.Add(containingShape);
foreach (var member in containingShape.Members)
{
if (member.IsStructure)
{
DetermineStructuresToProcess(member.Shape, true);
}
else if (member.IsList)
{
DetermineStructuresToProcess(member.Shape.ListShape, true);
}
else if (member.IsMap)
{
DetermineStructuresToProcess(member.Shape.ValueShape, true);
}
}
}
else if (containingShape.IsList)
{
DetermineStructuresToProcess(containingShape.ListShape, true);
}
else if (containingShape.IsMap)
{
DetermineStructuresToProcess(containingShape.ValueShape, true);
}
}
/// <summary>
/// Generate the response class for the operation.
/// </summary>
/// <param name="operation">The operation object which contains info about what the response needs to contain for the operation</param>
private void GenerateResponse(Operation operation)
{
var suppressResultGeneration = false;
if (operation.UseWrappingResult)
{
// response members will be demoted to a structure contained by a
// result container class (that is not in the service model)
var className = operation.Name + "Response";
string propertyName = null;
var propertyModifier
= this.Configuration.ServiceModel.Customizations.GetPropertyModifier(className, operation.ResponseStructure.Name);
if (propertyModifier != null && propertyModifier.EmitName != null)
propertyName = propertyModifier.EmitName;
else
propertyName = operation.ResponseStructure.Name;
var resultGenerator = new WrappingResultGenerator
{
Operation = operation,
ClassName = className,
BaseClass = "AmazonWebServiceResponse",
Structure = this.Configuration.ServiceModel.FindShape(operation.ResponseStructure.Name),
PropertyName = propertyName
};
// emit the wrapping result but do not mark the shape as processed as a consequence
this.ExecuteGenerator(resultGenerator, resultGenerator.ClassName + ".cs", "Model");
DetermineStructuresToProcess(resultGenerator.Structure, true);
}
else
{
// if the operation has a suppressed result modification, use the structure generator to emit
// an empty xxxxResponse class, derived from AmazonWebServiceResponse
suppressResultGeneration =
operation.ResponseStructure == null ||
this.Configuration.ServiceModel.Customizations.ResultGenerationSuppressions.Contains(operation.Name);
if (suppressResultGeneration)
{
var responseGenerator = new StructureGenerator
{
ClassName = operation.Name + "Response",
BaseClass = "AmazonWebServiceResponse",
Operation = operation,
StructureType = StructureType.Response
};
this.ExecuteGenerator(responseGenerator, responseGenerator.ClassName + ".cs", "Model");
}
else
{
var resultGenerator = new StructureGenerator
{
ClassName = operation.Name + "Response",
BaseClass = "AmazonWebServiceResponse",
IsWrapped = operation.IsResponseWrapped,
Operation = operation,
StructureType = StructureType.Response
};
if (operation.ResponseStructure != null)
{
if (operation.IsResponseWrapped)
{
// If IsResponseWrapped is true, the operation.ResponseStructure will point to a
// the shape with same name as ResponseWrapper.
var resultShape = this.Configuration.ServiceModel.FindShape(operation.ResponseStructure.Name);
var innerShape = resultShape.Members[0].Shape;
resultGenerator.Structure = innerShape;
}
else
{
resultGenerator.Structure =
this.Configuration.ServiceModel.FindShape(operation.ResponseStructure.Name);
}
}
this.ExecuteGenerator(resultGenerator, resultGenerator.ClassName + ".cs", "Model");
}
if (operation.ResponseStructure != null)
{
this.DetermineStructuresToProcess(operation.ResponseStructure, false);
}
}
//if (!suppressResultGeneration)
//{
// if (operation.ResponseStructure != null)
// {
// // Mark the shape as processed if it's being referred only as operation's
// // output shape and not being referred directly by any other shape or via an
// // operation modifier generating an artifical structure not in the service model.
// if (!IsShapeReferred(operation.ResponseStructure.Name, this.Configuration.ServiceModel)
// && !operation.WrapsResultShape(operation.ResponseStructure.Name))
// this._processedStructures.Add(operation.ResponseStructure.Name);
// }
// // This generates the legacy response class which just extends from the result class.
// var responseGenerator = new LegacyResponseClass()
// {
// OperationName = operation.Name
// };
// this.ExecuteGenerator(responseGenerator, operation.Name + "Response.cs", "Model");
//}
}
/// <summary>
/// Checks if the shape is referred directly by another shape
/// </summary>
/// <param name="shapeName">Name of the shape to look for references of</param>
/// <param name="serviceModel">The ServiceModel containing information about the shapes of the service</param>
/// <returns>If the shape is a member of a structure or is a list or map</returns>
private static bool IsShapeReferred(string shapeName, ServiceModel serviceModel)
{
foreach (var shape in serviceModel.Shapes)
{
if (shape.IsStructure)
{
foreach (var member in shape.Members)
{
if (member.Shape.Name == shapeName)
{
return true;
}
}
}
else if (shape.IsList && shape.ListShape.Name == shapeName)
{
return true;
}
else if (shape.IsMap &&
(shape.ValueShape.Name == shapeName || shape.KeyShape.Name == shapeName))
{
return true;
}
}
return false;
}
/// <summary>
/// Generates the request marshaller.
/// </summary>
/// <param name="operation">The operation to generate request marshallers for</param>
void GenerateRequestMarshaller(Operation operation)
{
bool hasRequest = operation.RequestStructure != null;
bool normalizeMarshallers;
BaseRequestMarshaller generator;
GetRequestMarshaller(out generator, out normalizeMarshallers);
generator.Operation = operation;
this.ExecuteGenerator(generator, operation.Name + "RequestMarshaller.cs", "Model.Internal.MarshallTransformations");
if (hasRequest)
this._processedMarshallers.Add(operation.RequestStructure.Name);
if (normalizeMarshallers && hasRequest)
{
var lookup = new NestedStructureLookup();
lookup.SearchForNestedStructures(operation.RequestStructure);
foreach (var nestedStructure in lookup.NestedStructures)
{
// Skip structure marshallers that have already been generated for the parent model
if (IsShapePresentInParentModel(this.Configuration, nestedStructure.Name))
continue;
// Documents don't use a custom marshaller, always use DocumentMarshaller
if (nestedStructure.IsDocument)
continue;
if (!this._processedMarshallers.Contains(nestedStructure.Name))
{
var structureGenerator = GetStructureMarshaller();
structureGenerator.Structure = nestedStructure;
this.ExecuteGenerator(structureGenerator, nestedStructure.Name + "Marshaller.cs", "Model.Internal.MarshallTransformations");
//this.processedUnmarshallers.Add(nestedStructure.Name);
}
}
}
}
void GeneratePaginator(Operation operation)
{
if (operation.Paginators != null && !operation.UnsupportedPaginatorConfig)
{
// Generate operation paginator
BasePaginator paginatorGenerator = new BasePaginator();
paginatorGenerator.Operation = operation;
this.ExecuteGenerator(paginatorGenerator, $"{operation.Name}Paginator.cs", PaginatorsSubFolder);
// Generate operation paginator interface
BasePaginatorInterface paginatorInterfaceGenerator = new BasePaginatorInterface();
paginatorInterfaceGenerator.Operation = operation;
this.ExecuteGenerator(paginatorInterfaceGenerator, $"I{operation.Name}Paginator.cs", PaginatorsSubFolder);
}
}
/// <summary>
/// Generates the response unmarshaller along with any dependent structure unmarshallers that are called by this response unmarshaller.
/// </summary>
/// <param name="operation">The operation to generate the unmarshaller for</param>
void GenerateResponseUnmarshaller(Operation operation)
{
{
var baseException = string.Format("Amazon{0}Exception",
this.Configuration.IsChildConfig ?
this.Configuration.ParentConfig.ClassName : this.Configuration.ClassName);
var generator = GetResponseUnmarshaller();
generator.Operation = operation;
generator.IsWrapped = operation.IsResponseWrapped;
generator.HasSuppressedResult = this.Configuration.ServiceModel.Customizations.ResultGenerationSuppressions.Contains(operation.Name);
generator.BaseException = baseException;
var modifier = operation.model.Customizations.GetOperationModifiers(operation.Name);
if (modifier != null)
{
// can use wrapped member to effect a rename, even though we don't push response
// members down into a wrapped class
generator.WrappedResultMember = modifier.WrappedResultMember;
generator.IsWrapped = modifier.UseWrappingResult;
}
this.ExecuteGenerator(generator, operation.Name + "ResponseUnmarshaller.cs", "Model.Internal.MarshallTransformations");
// Add to the list of processed unmarshallers so we don't attempt to generate a generic structure unmarshaller.
if (operation.ResponseStructure != null)
{
// Mark the shape as processed if it's being referred only as operation's
// output shape and not being referred directly by any other shape or via an
// operation modifier generating an artifical structure not in the service model.
if (!IsShapeReferred(operation.ResponseStructure.Name, this.Configuration.ServiceModel)
&& !operation.WrapsResultShape(operation.ResponseStructure.Name))
this._processedUnmarshallers.Add(operation.ResponseStructure.Name);
}
}
if (operation.ResponseStructure != null)
{
var lookup = new NestedStructureLookup();
lookup.SearchForNestedStructures(operation.ResponseStructure);
//Do not generate an unmarshaller for the response's payload if it is of type EventStream
//This is because we attach the payload to the generic response and unmarshall it from there.
if (operation.IsEventStreamOutput)
{
if (operation.ResponsePayloadMember.ModelShape.IsEventStream)
{
//If the file was already generated incorrectly delete it
var unmarshallerName = operation.ResponsePayloadMember.ModelShape.Name + "Unmarshaller.cs";
var unmarshallerPath = Path.Combine(GeneratedFilesRoot, "Model","Internal", "MarshallTransformations", unmarshallerName);
if (File.Exists(unmarshallerPath))
{
File.Delete(unmarshallerPath);
}
return;
}
}
foreach (var nestedStructure in lookup.NestedStructures)
{
// Skip structure unmarshallers that have already been generated for the parent model
if (IsShapePresentInParentModel(this.Configuration, nestedStructure.Name))
continue;
if (this.Configuration.ServiceModel.Customizations.IsSubstitutedShape(nestedStructure.Name))
continue;
// Document structure don't need a custom marshaller, they use
// the 'simple' DocumentMarshaller in AWSSDK.
if (nestedStructure.IsDocument)
continue;
// Skip already processed unmarshallers. This handles the case of structures being returned in mulitiple requests.
if (!this._processedUnmarshallers.Contains(nestedStructure.Name))
{
var generator = GetStructureUnmarshaller();
generator.Structure = nestedStructure;
this.ExecuteGenerator(generator, nestedStructure.Name + "Unmarshaller.cs", "Model.Internal.MarshallTransformations");
this._processedUnmarshallers.Add(nestedStructure.Name);
}
else
{
//throw new Exception();
}
}
}
}
private void GenerateUnmarshaller(Shape shape)
{
var lookup = new NestedStructureLookup();
lookup.SearchForNestedStructures(shape);
foreach (var nestedStructure in lookup.NestedStructures)
{
// Skip structure unmarshallers that have already been generated for the parent model
if (IsShapePresentInParentModel(this.Configuration, nestedStructure.Name))
continue;
if (this.Configuration.ServiceModel.Customizations.IsSubstitutedShape(nestedStructure.Name))
continue;
// Document structure don't need a custom unmarshaller, they use
// the 'simple' DocumentMarshaller in AWSSDK.
if (nestedStructure.IsDocument)
continue;
// Skip already processed unmarshallers. This handles the case of structures being returned in mulitiple requests.
if (!this._processedUnmarshallers.Contains(nestedStructure.Name))
{
var generator = GetStructureUnmarshaller();
generator.Structure = nestedStructure;
this.ExecuteGenerator(generator, nestedStructure.Name + "Unmarshaller.cs", "Model.Internal.MarshallTransformations");
this._processedUnmarshallers.Add(nestedStructure.Name);
}
}
}
private void GenerateCustomUnmarshallers(List<string> structures)
{
foreach (var structure in structures)
{
var shape = this.Configuration.ServiceModel.FindShape(structure);
GenerateUnmarshaller(shape);
}
}
/// <summary>
/// Invokes T4: <see cref="DefaultConfigurationModeGenerator"/>
/// </summary>
public static void GenerateDefaultConfigurationModeEnum(GenerationManifest generationManifest, GeneratorOptions options)
{
Console.WriteLine("Generating DefaultConfigurationMode Enum...");
var defaultConfigurationModeFilesRoot = Path.Combine(options.SdkRootFolder, "src", "Core", "Amazon.Runtime");
const string fileName = "DefaultConfigurationMode.generated.cs";
var generator = new DefaultConfigurationModeGenerator
{
DefaultConfigurationModel = generationManifest.DefaultConfiguration
};
var text = generator.TransformText();
WriteFile(defaultConfigurationModeFilesRoot, null, fileName, text);
}
/// <summary>
/// Generates the endpoint discovery marshaller for the specified operation.
/// </summary>
/// <param name="operation">The operation to generate endpoint discovery marshaller for</param>
void GenerateEndpointDiscoveryMarshaller(Operation operation)
{
if(operation.IsEndpointOperation || !operation.EndpointDiscoveryEnabled)
{
return;
}
var generator = new EndpointDiscoveryMarshaller
{
Operation = operation
};
this.ExecuteGenerator(generator, operation.Name + "EndpointDiscoveryMarshaller.cs", "Model.Internal.MarshallTransformations");
}
private void GenerateExceptions(Operation operation)
{
//Generate a special EventStreamException class that extends EventStreamException
//We need a parameterless constructor to use it in EnumerableEventStream. Only once per service
if (operation.IsEventStreamOutput && !Configuration.GeneratedEventStreamException)
{
var eventStreamExceptionGenerator = new EventStreamExceptionGenerator();
this.ExecuteGenerator(eventStreamExceptionGenerator, this.Configuration.ClassName + "EventStreamException.cs","Model");
Configuration.GeneratedEventStreamException = true;
}
foreach (var exceptionShape in operation.Exceptions)
{
// Skip exceptions that have already been generated for the parent model
if (IsExceptionPresentInParentModel(this.Configuration, exceptionShape.Name) || this._processedStructures.Contains(exceptionShape.Name))
continue;
var generator = new StructureGenerator()
{
ClassName = exceptionShape.Name,
Structure = exceptionShape,
BaseClass = this.Configuration.BaseException
};
this.ExecuteGenerator(generator, exceptionShape.Name + ".cs", "Model");
this._processedStructures.Add(exceptionShape.Name);
var unmarshallerGenerator = GetExceptionUnmarshaller();
unmarshallerGenerator.Structure = exceptionShape;
this.ExecuteGenerator(unmarshallerGenerator, exceptionShape.Name + "Unmarshaller.cs", "Model.Internal.MarshallTransformations");
this._processedUnmarshallers.Add(exceptionShape.Name);
DetermineStructuresToProcess(exceptionShape, false);
GenerateUnmarshaller(exceptionShape);
}
}
public static void GenerateCoreProjects(GenerationManifest generationManifest,
GeneratorOptions options)
{
Console.WriteLine("Updating Core project files.");
string coreFilesRoot = Path.Combine(options.SdkRootFolder, "src", "Core");
var creator = new ProjectFileCreator(options);
creator.ExecuteCore(coreFilesRoot, generationManifest.ProjectFileConfigurations);
foreach (var newProjectKey in creator.CreatedProjectFiles.Keys)
{
NewlyCreatedProjectFiles.Add(newProjectKey, creator.CreatedProjectFiles[newProjectKey]);
}
}
/// <summary>
/// Generates partial Partition class used to retrieve partition-specific data.
/// </summary>
public static void GeneratePartitions(GeneratorOptions options)
{
Console.WriteLine("Generate Partition class.");
var coreFilesRoot = Path.Combine(options.SdkRootFolder, "src", "Core");
var writeToFolder = Path.Combine(coreFilesRoot, "Amazon.Runtime", "Internal", "Endpoints", "StandardLibrary");
var partitionsFile = Path.Combine(coreFilesRoot, "partitions.json");
var json = File.ReadAllText(partitionsFile);
var partitions = JsonMapper.ToObject<Partitions>(json);
var generator = new PartitionsTemplate
{
Partitions = partitions
};
var text = generator.TransformText();
WriteFile(writeToFolder, null, "Partition.generated.cs", text);
}
/// <summary>
/// Method to create/update legacy unit test projects
/// </summary>
public static void UpdateUnitTestProjects(GenerationManifest generationManifest, GeneratorOptions options)
{
string unitTestRoot = Path.Combine(options.SdkRootFolder, "test", "UnitTests");
var creator = new UnitTestProjectFileCreator(options, generationManifest.UnitTestProjectFileConfigurations);
UpdateUnitTestProjects(generationManifest.ServiceConfigurations, options, unitTestRoot, creator);
}
/// <summary>
/// Adding Method to create/update service specific unit test projects
/// </summary>
public static void UpdateUnitTestProjects(GenerationManifest generationManifest, GeneratorOptions options, string serviceTestFilesRoot, ServiceConfiguration serviceConfiguration)
{
Console.WriteLine("Updating unit test project files.");
string unitTestRoot = Path.Combine(serviceTestFilesRoot, "UnitTests");
var creator = new UnitTestProjectFileCreator(options, generationManifest.UnitTestProjectFileConfigurations, serviceConfiguration.ServiceFolderName);
UpdateUnitTestProjects(new[] { serviceConfiguration }, options, unitTestRoot, creator);
}
private static void UpdateUnitTestProjects(IEnumerable<ServiceConfiguration> serviceConfigurations, GeneratorOptions options, string unitTestRoot, UnitTestProjectFileCreator creator)
{
Console.WriteLine("Updating unit test project files.");
creator.Execute(unitTestRoot, serviceConfigurations, false);
}
public static void UpdateSolutionFiles(GenerationManifest manifest, GeneratorOptions options)
{
Console.WriteLine("Updating solution files.");
var solutionFileCreator = new SolutionFileCreator
{
Options = options,
ProjectFileConfigurations = manifest.ProjectFileConfigurations
};
solutionFileCreator.Execute(NewlyCreatedProjectFiles);
}
public static void UpdateCodeAnalysisSolution(GenerationManifest manifest, GeneratorOptions options)
{
Console.WriteLine("Updating code analysis solution file.");
var creator = new CodeAnalysisSolutionCreator
{
Options = options
};
creator.Execute();
}
public static void UpdateAssemblyVersionInfo(GenerationManifest manifest, GeneratorOptions options)
{
var updater = new CoreAssemblyInfoUpdater(options, manifest);
updater.Execute();
}
public static void UpdateNuGetPackagesInReadme(GenerationManifest manifest, GeneratorOptions options)
{
var nugetPackages = new Dictionary<string, string>();
foreach (var service in manifest.ServiceConfigurations.OrderBy(x => x.ClassName))
{
// Service like DynamoDB streams are included in a parent service.
if (service.ParentConfig != null || service.IsTestService)
continue;
if (string.IsNullOrEmpty(service.Synopsis))
throw new Exception(string.Format("{0} is missing a synopsis in the manifest.", service.ClassName));
var assemblyName = service.Namespace.Replace("Amazon.", "AWSSDK.");
nugetPackages[assemblyName] = service.Synopsis;
}
NuGetPackageReadmeSection generator = new NuGetPackageReadmeSection();
var session = new Dictionary<string, object> { { "NugetPackages", nugetPackages } };
generator.Session = session;
var nugetPackagesText = generator.TransformText();
var readmePath = Path.Combine(options.SdkRootFolder, "..", "README.md");
var originalContent = File.ReadAllText(readmePath);
int startPos = originalContent.IndexOf('\n', originalContent.IndexOf("### NuGet Packages")) + 1;
int endPos = originalContent.IndexOf("### Code Generator");
var newContent = originalContent.Substring(0, startPos);
newContent += nugetPackagesText + "\r\n";
newContent += originalContent.Substring(endPos);
File.WriteAllText(readmePath, newContent);
}
/// <summary>
/// Provides a way to generate the necessary attributes and marshallers/unmarshallers for nested structures to work
/// </summary>
class NestedStructureLookup
{
public List<Shape> NestedStructures { get; private set; }
public NestedStructureLookup()
{
NestedStructures = new List<Shape>();
}
/// <summary>
/// Function that recursively searches for structures of a given shape
/// </summary>
/// <param name="structure">The shape to look for recursive structures in</param>
public void SearchForNestedStructures(Shape structure)
{
if (NestedStructures.Contains(structure))
return;
if (structure.IsStructure)
NestedStructures.Add(structure);
if (structure.IsList)
{
if (structure.ListShape.IsStructure || structure.ListShape.IsList || structure.ListShape.IsMap)
{
SearchForNestedStructures(structure.ListShape);
}
}
else if (structure.IsMap)
{
if (structure.ValueShape.IsStructure || structure.ValueShape.IsList || structure.ValueShape.IsMap)
{
SearchForNestedStructures(structure.ValueShape);
}
}
else if (structure.IsStructure)
{
foreach (var member in structure.Members)
{
SearchForNestedStructures(member.Shape);
}
}
}
}
/// <summary>
/// Generates all the POCOs that go in the Model namespace for the structures defined in the service model.
/// </summary>
void GenerateStructures()
{
var excludedOperations = Configuration.ServiceModel.ExcludedOperations;
foreach (var definition in this._structuresToProcess)
{
// Skip structures that have already been generated for the parent model
if (IsShapePresentInParentModel(this.Configuration, definition.Name))
continue;
if (!this._processedStructures.Contains(definition.Name))
{
// if the shape had a substitution, we can skip generation
if (this.Configuration.ServiceModel.Customizations.IsSubstitutedShape(definition.Name))
continue;
// if the shape is a request or response type and the parent operation
// was excluded, then skip generation
var opName = definition.RelatedOperationName;
if (!string.IsNullOrEmpty(opName) && excludedOperations.Contains(opName))
continue;
var generator = new StructureGenerator()
{
ClassName = definition.Name,
Structure = definition
};
this.ExecuteGenerator(generator, definition.Name + ".cs", "Model");
this._processedStructures.Add(definition.Name);
}
}
}
static bool IsShapePresentInParentModel(ServiceConfiguration config, string shapeName)
{
if (config.IsChildConfig)
{
// Check to see if the structure is present in a parent model
if (config.ParentConfig.ServiceModel.Shapes.SingleOrDefault(
e => e.Name.Equals(shapeName)) != null)
{
return true;
}
}
return false;
}
static bool IsExceptionPresentInParentModel(ServiceConfiguration config, string exceptionName)
{
if (config.IsChildConfig)
{
// Check to see if the exception is present in a parent model
if (config.ParentConfig.ServiceModel.Exceptions.SingleOrDefault(
e => e.Name.Equals(exceptionName)) != null)
{
return true;
}
}
return false;
}
/// <summary>
/// Generates any missing project files for a service
/// </summary>
void ExecuteProjectFileGenerators()
{
var creator = new ProjectFileCreator(Options);
creator.Execute(ServiceFilesRoot, this.Configuration, this.ProjectFileConfigurations);
foreach (var newProjectKey in creator.CreatedProjectFiles.Keys)
{
NewlyCreatedProjectFiles.Add(newProjectKey, creator.CreatedProjectFiles[newProjectKey]);
}
}
void GenerateNuspec()
{
var coreVersion = GenerationManifest.CoreVersion;
// we're generating services only, so can automatically add the core runtime
// as a dependency
var awsDependencies = new Dictionary<string, string>(StringComparer.Ordinal);
if (Configuration.ServiceDependencies != null)
{
var dependencies = Configuration.ServiceDependencies;
foreach (var kvp in dependencies)
{
var service = kvp.Key;
var version = kvp.Value;
var dependentService = GenerationManifest.ServiceConfigurations.FirstOrDefault(x => string.Equals(x.Namespace, "Amazon." + service, StringComparison.InvariantCultureIgnoreCase));
string previewFlag;
if (dependentService != null && dependentService.InPreview)
{
previewFlag = GenerationManifest.PreviewLabel;
}
else if (string.Equals(service, "Core", StringComparison.InvariantCultureIgnoreCase) && GenerationManifest.DefaultToPreview)
{
previewFlag = GenerationManifest.PreviewLabel;
}
else
{
previewFlag = string.Empty;
}
var verTokens = version.Split('.');
var versionRange = string.Format("[{0}{2}, {1}.0{2})", version, int.Parse(verTokens[0]) + 1, previewFlag);
awsDependencies.Add(string.Format("AWSSDK.{0}", service), versionRange);
}
}
var nugetAssemblyName = Configuration.AssemblyTitle;
var nugetAssemblyTitle = Configuration.AssemblyTitle.Replace("AWSSDK.", "AWSSDK - ");
var nugetTitle = nugetAssemblyTitle;
if (!string.IsNullOrEmpty(Configuration.NugetPackageTitleSuffix))
nugetTitle += " " + Configuration.NugetPackageTitleSuffix;
var session = new Dictionary<string, object>
{
{ "AssemblyName", nugetAssemblyName },
{ "AssemblyTitle", nugetAssemblyTitle },
{ "NetStandardSupport", Configuration.NetStandardSupport },
{ "NetStandardCoreAssemblyName", Configuration.ServiceFolderName },
{ "NuGetTitle", nugetTitle },
{ "AssemblyDescription", Configuration.AssemblyDescription(includePreamble: false, includeBody: false) },
{ "AssemblyVersion", Configuration.ServiceFileVersion },
{ "AWSDependencies", awsDependencies },
{ "BaseName", Configuration.ClassName },
{ "CodeAnalysisServiceFolder", Configuration.Namespace.Replace("Amazon.", "") },
{ "ProjectFileConfigurations", ProjectFileConfigurations},
{ "ExtraTags", Configuration.Tags == null || Configuration.Tags.Count == 0 ? string.Empty : " " + string.Join(" ", Configuration.Tags) },
{ "licenseUrl", Configuration.LicenseUrl },
{ "requireLicenseAcceptance",Configuration.RequireLicenseAcceptance?"true":"false" }
};
if (Configuration.NugetDependencies != null)
session.Add("NugetDependencies", Configuration.NugetDependencies);
session["NuGetPreviewFlag"] = Configuration.InPreview ? this.GenerationManifest.PreviewLabel : "";
var nuspecGenerator = new Nuspec { Session = session };
var text = nuspecGenerator.TransformText();
var nuspecFilename = nugetAssemblyName + ".nuspec";
WriteFile(ServiceFilesRoot, string.Empty, nuspecFilename, text);
}
Version GetMinVersion(Version version)
{
var minVersion = new Version(version.Major, version.Minor);
return minVersion;
}
Version GetMinVersion(string versionText)
{
var version = new Version(versionText);
return GetMinVersion(version);
}
/// <summary>
/// Generates tests for the customizations of the service
/// </summary>
void GenerateCustomizationTests()
{
if (this.Configuration.ServiceModel.Customizations.SimpleConstructorsModel.SimpleConstructors.Count > 0)
{
var constructorTests = new SimpleConstructorTests()
{
Config = this.Configuration
};
ExecuteCustomizationTestGenerator(constructorTests, this.Configuration.ClassName + "ConstructorTests.cs", "Constructors");
}
if (this.Configuration.ServiceModel.Customizations.SimpleMethodsModel.SimpleMethods.Count > 0)
{
var methodTests = new SimpleMethodTests()
{
Config = this.Configuration
};
ExecuteCustomizationTestGenerator(methodTests, this.Configuration.ClassName + "MethodTests.cs", "SimpleMethods");
}
}
/// <summary>
/// Runs the generator and saves the content into _bcl35 directory under the generated files root.
/// </summary>
/// <param name="generator">The generator to use for outputting the text of the cs file</param>
/// <param name="fileName">The name of the cs file</param>
/// <param name="subNamespace">Adds an additional directory for the namespace</param>
void ExecuteGenerator(BaseGenerator generator, string fileName, string subNamespace = null)
{
generator.Config = this.Configuration;
generator.DefaultConfigurationModel = this.GenerationManifest.DefaultConfiguration;
var text = generator.TransformText();
string outputFile;
WriteFile(GeneratedFilesRoot, subNamespace, fileName, text, true, true, out outputFile);
FilesWrittenToGeneratorFolder.Add(outputFile);
}
/// <summary>
/// Runs the generator and saves the content in the test directory.
/// </summary>
/// <param name="generator">The generator to use for outputting the text of the cs file</param>
/// <param name="fileName">The name of the cs file</param>
/// <param name="subNamespace">Adds an additional directory for the namespace</param>
void ExecuteTestGenerator(BaseGenerator generator, string fileName, string subNamespace = null)
{
generator.Config = this.Configuration;
var text = generator.TransformText();
var outputSubFolder = subNamespace == null ? GeneratedTestsSubFolder : Path.Combine(GeneratedTestsSubFolder, subNamespace);
WriteFile(ServiceUnitTestFilesRoot, outputSubFolder, fileName, text);
}
void ExecuteGeneratorAssemblyInfo()
{
var generator = new AssemblyInfo { Config = this.Configuration };
var text = generator.TransformText();
WriteFile(ServiceFilesRoot, "Properties", "AssemblyInfo.cs", text);
}
void ExecuteExampleGenerator(BaseGenerator generator, string fileName, string subNamespace = null)
{
generator.Config = this.Configuration;
var text = generator.TransformText();
var outputSubFolder = Path.Combine("docgenerator", "AWSSDKDocSamples");
if (subNamespace != null)
outputSubFolder = Path.Combine(outputSubFolder, subNamespace);
WriteFile(Path.GetFullPath(TestFilesRoot + string.Format("{0}..{0}..{0}",
Path.DirectorySeparatorChar)), outputSubFolder, fileName, text);
}
/// <summary>
/// Runs the generator and saves the content in the test directory.
/// </summary>
/// <param name="generator">The generator to use for outputting the text of the cs file</param>
/// <param name="fileName">The name of the cs file</param>
/// <param name="subNamespace">Adds an additional directory for the namespace</param>
void ExecuteCustomizationTestGenerator(BaseGenerator generator, string fileName, string subNamespace = null)
{
generator.Config = this.Configuration;
var text = generator.TransformText();
var outputSubFolder = subNamespace == null ? CustomizationTestsSubFolder : Path.Combine(CustomizationTestsSubFolder, subNamespace);
WriteFile(ServiceUnitTestFilesRoot, outputSubFolder, fileName, text);
}
/// <summary>
/// Generates unit tests for all of the service's paginators
/// </summary>
void GeneratePaginatorTests()
{
if (this.Configuration.ServiceModel.HasPaginators && this.Configuration.GenerateConstructors)
{
var paginatorTests = new PaginatorTests
{
Config = this.Configuration
};
var text = paginatorTests.TransformText();
var outputSubFolder = PaginatorTestsSubFolder;
WriteFile(ServiceUnitTestFilesRoot, outputSubFolder, this.Configuration.ClassName + "PaginatorTests.cs", text);
}
}
internal static bool WriteFile(string baseOutputDir,
string subNamespace,
string filename,
string content,
bool trimWhitespace = true,
bool replaceTabs = true)
{
string outputFilePath;
return WriteFile(baseOutputDir, subNamespace, filename, content, trimWhitespace, replaceTabs, out outputFilePath);
}
/// <summary>
/// Writes the contents to disk. The content will by default be trimmed of all white space and
/// all tabs are replaced with spaces to make the output consistent.
/// </summary>
/// <param name="baseOutputDir">The root folder for the owning service's generated files</param>
/// <param name="subNamespace">An optional sub namespace under the service. (e.g. Model or Model.Internal.MarshallTransformations)</param>
/// <param name="filename">Filename to right to</param>
/// <param name="content">The contents to write to the file</param>
/// <param name="trimWhitespace"></param>
/// <param name="replaceTabs"></param>
/// <returns>Returns false if the file already exists and has the same content.</returns>
internal static bool WriteFile(string baseOutputDir,
string subNamespace,
string filename,
string content,
bool trimWhitespace,
bool replaceTabs,
out string outputFilePath)
{
var outputDir = !string.IsNullOrEmpty(subNamespace)
? Path.Combine(baseOutputDir, subNamespace.Replace('.', Path.DirectorySeparatorChar))
: baseOutputDir;
if (!Directory.Exists(outputDir))
Directory.CreateDirectory(outputDir);
var cleanContent = trimWhitespace ? content.Trim() : content;
if (replaceTabs)
cleanContent = cleanContent.Replace("\t", " ");
outputFilePath = Path.GetFullPath(Path.Combine(outputDir, filename));
if (File.Exists(outputFilePath))
{
var existingContent = File.ReadAllText(outputFilePath);
if (string.Equals(existingContent, cleanContent))
return false;
var outputFilePathFi = new FileInfo(outputFilePath);
// Handle Windows being case insensitive when a service makes a case change for shape name.
// Get a FileInfo that represents the casing of the file on disk
var fi = Directory.GetFiles(outputFilePathFi.DirectoryName)
.Select(x => new FileInfo(x))
.FirstOrDefault(x => string.Equals(x.Name, outputFilePathFi.Name, StringComparison.OrdinalIgnoreCase));
// Compare the casing on disk versus the computed value.
if(fi.FullName != new FileInfo(outputFilePath).FullName)
{
// Casing is different so delete the on disk file so we can create a new file with the correct casing.
File.Delete(outputFilePath);
Console.WriteLine("...deleting existing file that is different by case from new file: {0}", filename);
}
}
File.WriteAllText(outputFilePath, cleanContent);
Console.WriteLine("...created/updated {0}", filename);
return true;
}
/// <summary>
/// Sets the marshaller of the generator based on the service type
/// </summary>
/// <param name="marshaller">The marshaller to be set</param>
/// <param name="normalizeMarshallers">If the service type is a type of json then normalizeMarshallers is set to true, false otherwise</param>
void GetRequestMarshaller(out BaseRequestMarshaller marshaller, out bool normalizeMarshallers)
{
normalizeMarshallers = false;
switch (this.Configuration.ServiceModel.Type)
{
case ServiceType.Rest_Json:
case ServiceType.Json:
marshaller = new JsonRPCRequestMarshaller();
normalizeMarshallers = true;
break;
case ServiceType.Query:
marshaller = new AWSQueryRequestMarshaller();
break;
case ServiceType.Rest_Xml:
marshaller = new RestXmlRequestMarshaller();
break;
default:
throw new Exception("No request marshaller for service type: " + this.Configuration.ServiceModel.Type);
}
}
/// <summary>
/// Determines the type of marshaller that needs to be generated based on the service model type
/// </summary>
/// <returns>JSONRPCStructureMarshaller for Rest_Json and Json, error otherwise</returns>
BaseRequestMarshaller GetStructureMarshaller()
{
switch (this.Configuration.ServiceModel.Type)
{
case ServiceType.Rest_Json:
case ServiceType.Json:
return new JsonRPCStructureMarshaller();
default:
throw new Exception("No structure marshaller for service type: " + this.Configuration.ServiceModel.Type);
}
}
/// <summary>
/// Determines the type of response unmarshaller to be used based on the service model type
/// </summary>
/// <returns>Either a JsonRPCResponseUnmarshaller, a AWSQueryResponseUnmarshaller, or a RestXmlResponseUnmarshaller. Error otherwise</returns>
BaseResponseUnmarshaller GetResponseUnmarshaller()
{
switch (this.Configuration.ServiceModel.Type)
{
case ServiceType.Rest_Json:
case ServiceType.Json:
return new JsonRPCResponseUnmarshaller();
case ServiceType.Query:
if (this.Configuration.ServiceModel.IsEC2Protocol)
return new AWSQueryEC2ResponseUnmarshaller();
return new AWSQueryResponseUnmarshaller();
case ServiceType.Rest_Xml:
return new RestXmlResponseUnmarshaller();
default:
throw new Exception("No response unmarshaller for service type: " + this.Configuration.ServiceModel.Type);
}
}
/// <summary>
/// Determines the Unmarshaller for structures based on the service model type
/// </summary>
/// <returns>Either JsonRPCStructureUnmarshaller, AWSQueryStructureUnmarshaller, or RestXmlStructureUnmarshaller. Error otherwise</returns>
BaseResponseUnmarshaller GetStructureUnmarshaller()
{
switch (this.Configuration.ServiceModel.Type)
{
case ServiceType.Rest_Json:
case ServiceType.Json:
return new JsonRPCStructureUnmarshaller();
case ServiceType.Query:
return new AWSQueryStructureUnmarshaller();
case ServiceType.Rest_Xml:
return new RestXmlStructureUnmarshaller();
default:
throw new Exception("No structure unmarshaller for service type: " + this.Configuration.ServiceModel.Type);
}
}
/// <summary>
/// Determines the Unmarshaller for structures based on the service model type
/// </summary>
/// <returns>Either JsonRPCStructureUnmarshaller, AWSQueryStructureUnmarshaller, or RestXmlStructureUnmarshaller. Error otherwise</returns>
BaseResponseUnmarshaller GetExceptionUnmarshaller()
{
switch (this.Configuration.ServiceModel.Type)
{
case ServiceType.Rest_Json:
case ServiceType.Json:
return new JsonRPCExceptionUnmarshaller();
case ServiceType.Query:
return new AWSQueryExceptionUnmarshaller();
case ServiceType.Rest_Xml:
return new RestXmlExceptionUnmarshaller();
default:
throw new Exception("No structure unmarshaller for service type: " + this.Configuration.ServiceModel.Type);
}
}
void GenerateCodeAnalysisProject()
{
var command = new CodeAnalysisProjectCreator();
command.Execute(CodeAnalysisRoot, this.Configuration);
}
public static void RemoveOrphanedShapesAndServices(HashSet<string> generatedFiles, string sdkRootFolder)
{
var codeGeneratedServiceList = codeGeneratedServiceNames.Distinct();
var srcFolder = Path.Combine(sdkRootFolder, SourceSubFoldername, ServicesSubFoldername);
RemoveOrphanedShapes(generatedFiles, srcFolder);
// Cleanup orphaned Service src artifacts. This is encountered when the service identifier is modified.
RemoveOrphanedServices(srcFolder, codeGeneratedServiceList);
// Cleanup orphaned Service test artifacts. This is encountered when the service identifier is modified.
RemoveOrphanedServices(Path.Combine(sdkRootFolder, TestsSubFoldername, ServicesSubFoldername), codeGeneratedServiceList);
// Cleanup orphaned Service code analysis artifacts. This is encountered when the service identifier is modified.
RemoveOrphanedServices(Path.Combine(sdkRootFolder, CodeAnalysisFoldername, ServicesAnalysisSubFolderName), codeGeneratedServiceList);
}
public static void RemoveOrphanedShapes(HashSet<string> generatedFiles, string srcFolder)
{
// Remove orphaned shapes. Most likely due to taking in a model that was still under development.
foreach (var file in Directory.GetFiles(srcFolder, "*.cs", SearchOption.AllDirectories))
{
var fullPath = Path.GetFullPath(file);
if (fullPath.IndexOf(string.Format(@"\{0}\", GeneratedCodeFoldername), StringComparison.OrdinalIgnoreCase) < 0)
continue;
if (!generatedFiles.Contains(fullPath))
{
Console.Error.WriteLine("**** Warning: Removing orphaned generated code " + Path.GetFileName(file));
File.Delete(file);
}
}
}
private static void RemoveOrphanedServices(string path, IEnumerable<string> codeGeneratedServiceList)
{
foreach (var directoryName in Directory.GetDirectories(path))
{
if (!codeGeneratedServiceList.Contains(new DirectoryInfo(directoryName).Name))
{
Directory.Delete(directoryName, true);
}
}
}
/// <summary>
/// Constructs endpoint constant name from a region code
/// e.g. us-east-1 -> USEast1
/// </summary>
public static string ConstructEndpointName(string regionCode)
{
var parts = regionCode.Split('-');
var name = parts[0].ToUpper();
for (int i = 1; i < parts.Length; i++)
{
// for backward compatibility, only "northwest" is transformed into upper camel case
var part = parts[i] == "northwest" ? "NorthWest" : parts[i].ToUpperFirstCharacter();
// special case for "Gov" regions, we add "Cloud" to it
part = part == "Gov" ? part + "Cloud" : part;
name += part;
}
return name;
}
public static List<EndpointConstant> ExtractEndpoints(GeneratorOptions options, Func<string, string> nameConverter, Func<string, string> codeConverter = null)
{
var coreFilesRoot = Path.Combine(options.SdkRootFolder, "src", "Core");
var endpointsJsonFile = Path.Combine(coreFilesRoot, "endpoints.json");
var endpointsJson = JsonMapper.ToObject(File.ReadAllText(endpointsJsonFile));
var endpoints = new List<EndpointConstant>();
foreach (JsonData partition in endpointsJson["partitions"])
{
JsonData regions = partition["regions"];
foreach (var regionCode in regions.PropertyNames)
{
var regionName = regions[regionCode]["description"].ToString();
endpoints.Add(new EndpointConstant
{
Name = nameConverter(regionCode),
RegionCode = regionCode,
ConvertedRegionCode = codeConverter == null ? regionCode : codeConverter(regionCode),
RegionName = regionName
});
}
}
return endpoints;
}
public static void GenerateEndpoints(GeneratorOptions options)
{
Console.WriteLine("Generating endpoints constants...");
var coreFilesRoot = Path.Combine(options.SdkRootFolder, "src", "Core");
var endpointsFilesRoot = Path.Combine(coreFilesRoot, "RegionEndpoint");
const string fileName = "RegionEndpoint.generated.cs";
var endpoints = ExtractEndpoints(options, ConstructEndpointName);
var generator = new EndpointsGenerator
{
Endpoints = endpoints
};
var text = generator.TransformText();
WriteFile(endpointsFilesRoot, null, fileName, text);
}
/// <summary>
/// Converts region code to maintain backward compatibility with S3
/// </summary>
public static string ConvertS3RegionCode(string regionCode)
{
switch (regionCode)
{
case "us-east-1":
return "";
case "eu-west-1":
return "EU";
default:
return regionCode;
}
}
public static void GenerateS3Enumerations(GeneratorOptions options)
{
Console.WriteLine("Generating S3 enumerations constants...");
var srcFilesRoot = Path.Combine(options.SdkRootFolder, "src");
var coreFilesRoot = Path.Combine(srcFilesRoot, "Core");
var generatedFileRoot = Path.Combine(srcFilesRoot, "Services", "S3", "Generated");
const string fileName = "S3Enumerations.cs";
var endpoints = ExtractEndpoints(options, ConstructEndpointName, ConvertS3RegionCode);
var generator = new S3EnumerationsGenerator()
{
Endpoints = endpoints
};
var text = generator.TransformText();
WriteFile(generatedFileRoot, null, fileName, text);
}
}
}
| 1,564 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
/// <summary>
/// The set of data protocols used by AWS services
/// </summary>
public enum ServiceType { Json, Query, Rest_Xml, Rest_Json };
/// <summary>
/// Where the properties of the request should be placed
/// </summary>
public enum MarshallLocation { Header, Uri, QueryString, StatusCode, Body, Headers };
/// <summary>
/// What type of Model is being generated
/// </summary>
public enum StructureType { Structure, Request, Response, Result };
/// <summary>
/// TimestampFormat that may be specified on a member or a shape.
/// Here is how we determine the timestampFormat to be used.
///
/// 1. Use the timestampFormat trait of the member reference if present.
/// 2. Use the timestampFormat trait of the shape if present.
/// 3. Use the format required by the protocol for the given location.
///
/// Rules used to default the format if timestampFormat is not specified.
/// 1. All timestamp values serialized in HTTP headers are formatted using rfc822 by default.
/// 2. All timestamp values serialized in query strings are formatted using iso8601 by default.
/// 3. The default timestamp formats per protocol for structured payload shapes are as follows.
/// rest-json: unixTimestamp
/// jsonrpc: unixTimestamp
/// rest-xml: iso8601
/// query: iso8601
/// ec2: iso8601
/// </summary>
public enum TimestampFormat { None, ISO8601, RFC822, UnixTimestamp }
}
| 45 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Json.LitJson;
namespace ServiceClientGenerator
{
public static class GeneratorHelpers
{
public static string DetermineSigner(string signatureVersion, string serviceBasename)
{
switch (serviceBasename)
{
case "EventBridge":
// we should not continue to add new hardcoded service specific signers
// and instead implement a solution based on a signer selection specification
return "EventBridgeSigner";
}
switch (signatureVersion)
{
case "v2":
return "QueryStringSigner";
case "v3https":
return "AWS3Signer";
case "v4":
return "AWS4Signer";
case "s3":
return "Amazon.S3.Internal.S3Signer";
case "s3v4":
return "S3Signer";
case "bearer":
return "BearerTokenSigner";
case "":
return "NullSigner";
default:
throw new Exception("Unknown signer: " + signatureVersion);
}
}
public static readonly DateTime EPOCH_START = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static int ConvertToUnixEpochSeconds(DateTime dateTime)
{
TimeSpan ts = new TimeSpan(dateTime.ToUniversalTime().Ticks - EPOCH_START.Ticks);
return Convert.ToInt32(ts.TotalSeconds);
}
public static double ConvertToUnixEpochSecondsDouble(DateTime dateTime)
{
TimeSpan ts = new TimeSpan(dateTime.ToUniversalTime().Ticks - EPOCH_START.Ticks);
double seconds = Math.Round(ts.TotalMilliseconds, 0) / 1000.0;
return seconds;
}
// List members in EC2 are always considered flattened, so we drop the 'member' prefix
public static string DetermineAWSQueryListMemberPrefix(Member member)
{
if (member.model.IsEC2Protocol || member.Shape.IsFlattened)
return string.Empty;
if (member.Shape.IsList)
return "member";
if (member.Shape.IsMap)
return "entry";
throw new Exception("Unknown member type for list member prefix determination");
}
/// <summary>
/// Inspects list member to determine if the original list shape in the model has been
/// substituted and if so, whether a member suffix should be used to extract the value
/// for use in the query. An example usage would be the replacement of IpRange (in EC2)
/// within an IpRangeList - we treat as a list of strings, yet need to get to the
/// IpRange.CidrIp member in the query marshalling. Note that we also have some EC2
/// operations where we don't want this submember extraction too even though the
/// same substitite is in use.
/// </summary>
/// <param name="member"></param>
/// <returns></returns>
public static string DetermineAWSQueryListMemberSuffix(Operation operation, Member member)
{
if (member.Shape.ModelListShape == null)
return null;
string suffixMember = null;
var substituteShapeData = member.model.Customizations.GetSubstituteShapeData(member.ModelShape.ModelListShape.Name);
if (substituteShapeData != null && substituteShapeData[CustomizationsModel.EmitFromMemberKey] != null)
{
var useSuffix = true;
if (substituteShapeData[CustomizationsModel.ListMemberSuffixExclusionsKey] != null)
{
var exclusions = substituteShapeData[CustomizationsModel.ListMemberSuffixExclusionsKey];
foreach (JsonData excl in exclusions)
{
if (string.Equals(operation.Name, (string)excl, StringComparison.Ordinal))
{
useSuffix = false;
break;
}
}
}
if (useSuffix)
suffixMember = (string)substituteShapeData[CustomizationsModel.EmitFromMemberKey];
}
return suffixMember;
}
/// <summary>
/// Determines if a property modifier for the member is suppressing automatic marshall
/// generation code for the field. If true, custom code in the pipeline will handle the
/// member.
/// </summary>
/// <param name="member"></param>
/// <param name="operation"></param>
/// <returns></returns>
public static bool UseCustomMarshall(Member member, Operation operation)
{
if (member.PropertyModifier != null && member.PropertyModifier.IsSetUseCustomMarshall)
return member.PropertyModifier.UseCustomMarshall;
if (member.PropertyInjector != null && member.PropertyInjector.IsSetUseCustomMarshall)
return member.PropertyInjector.UseCustomMarshall;
return false;
}
// The marshal name must always be up-cased (first letter only) when used with EC2's
// variant of AWSQuery. We can also apply operation-specific customizations for marshal
// names
public static string DetermineAWSQueryMarshallName(Member member, Operation operation)
{
var isEC2Protocol = member.model.IsEC2Protocol;
CustomizationsModel.OperationModifiers modifiers = null;
if (operation != null)
modifiers = operation.OperationModifiers;
var marshallName = new StringBuilder();
if (modifiers != null)
{
var marshallOverride = modifiers.GetMarshallNameOverrides(member.OwningShape.Name, member.BasePropertyName);
if (marshallOverride != null)
{
var marshallOverrideName = !isEC2Protocol
? marshallOverride.MarshallName
: (string.IsNullOrEmpty(marshallOverride.MarshallLocationName)
? marshallOverride.MarshallName
: marshallOverride.MarshallLocationName);
marshallName.Append(TransformMarshallLocationName(isEC2Protocol, marshallOverrideName));
}
}
// if the operation didn't override the marshal location, is there a property modifier doing so?
if (marshallName.Length == 0 && member.PropertyModifier != null)
{
var locationName = TransformMarshallLocationName(isEC2Protocol, member.PropertyModifier.LocationName);
marshallName.Append(locationName);
}
// if the marshal name still isn't set, fall back to the model
if (marshallName.Length == 0)
{
string modelMarshallName;
if (!string.IsNullOrEmpty(member.MarshallQueryName))
{
modelMarshallName = member.MarshallQueryName;
}
else
{
if (isEC2Protocol && !string.IsNullOrEmpty(member.MarshallLocationName))
{
modelMarshallName = member.MarshallLocationName;
}
else
{
modelMarshallName = member.MarshallName;
}
modelMarshallName = TransformMarshallLocationName(isEC2Protocol, modelMarshallName);
}
marshallName.Append(modelMarshallName);
}
// also check if we need to emit from a submember as a result of shape substitution
var substituteShapeData = member.model.Customizations.GetSubstituteShapeData(member.ModelShape.Name);
if (substituteShapeData != null && substituteShapeData[CustomizationsModel.EmitFromMemberKey] != null)
{
var valueMember = (string) substituteShapeData[CustomizationsModel.EmitFromMemberKey];
var subMember = member.ModelShape.Members.Single(m => m.PropertyName.Equals(valueMember, StringComparison.Ordinal));
if (subMember != null)
{
string subExpression;
if (!string.IsNullOrEmpty(subMember.MarshallQueryName))
{
subExpression = subMember.MarshallQueryName;
}
else
{
subExpression = string.IsNullOrEmpty(subMember.MarshallLocationName)
? subMember.MarshallName
: subMember.MarshallLocationName;
subExpression = TransformMarshallLocationName(isEC2Protocol, subExpression);
}
marshallName.AppendFormat(".{0}", subExpression);
}
}
return marshallName.ToString();
}
// The "locationName" must always be lower-cased (first letter only) when used with EC2's
// variant of AWSQuery. MarshallLocationName isn't consistently set.
public static string DetermineAWSQueryBaseUnmarshallName(Member member)
{
if (!member.model.IsEC2Protocol)
return member.MarshallName;
var baseExpression = string.IsNullOrEmpty(member.MarshallLocationName)
? member.MarshallName
: member.MarshallLocationName;
return TransformUnmarshallLocationName(true, baseExpression);
}
// returns the unmarshall expression for a member
public static string DetermineAWSQueryTestExpression(Member member)
{
var isEC2Protocol = member.model.IsEC2Protocol;
var testExpression = DetermineAWSQueryBaseUnmarshallName(member);
if (member.IsList)
{
if (!member.Shape.IsFlattened)
{
testExpression += "/";
if (member.Shape.ListMarshallName != null)
testExpression += member.Shape.ListMarshallName;
else
testExpression += "member";
// If the list element shape has a customization replacing it
// with another shape, extend the expression with any subexpression
// to the value member that the replaced shape has. This allows us to
// handle collections of EC2's AttributeValue shape which is replaced
// by a 'string' and we unmarshall the collection using the shape's 'value'
// member.
var listShape = member.Shape.ModelListShape;
var substituteShapeData = member.model.Customizations.GetSubstituteShapeData(listShape.Name);
if (substituteShapeData != null)
{
if (substituteShapeData[CustomizationsModel.EmitFromMemberKey] != null)
{
var valueMember = (string)substituteShapeData[CustomizationsModel.EmitFromMemberKey];
if (isEC2Protocol)
testExpression += "/" + TransformUnmarshallLocationName(true, valueMember);
else
testExpression += "/" + valueMember;
}
else
{
if (listShape.ValueMarshallName != null)
testExpression += "/" + listShape.ValueMarshallName;
}
}
}
else
{
testExpression = member.Shape.ListMarshallName;
}
}
else if (member.IsMap)
{
if (!member.Shape.IsFlattened)
testExpression += "/entry";
}
else
{
var substituteShapeData = member.model.Customizations.GetSubstituteShapeData(member.ModelShape.Name);
if (substituteShapeData != null && substituteShapeData[CustomizationsModel.EmitFromMemberKey] != null)
{
var valueMember = (string)substituteShapeData[CustomizationsModel.EmitFromMemberKey];
var subMember = member.ModelShape.Members.Single(m => m.PropertyName.Equals(valueMember, StringComparison.Ordinal));
var subExpression = string.IsNullOrEmpty(subMember.MarshallLocationName)
? subMember.MarshallName
: subMember.MarshallLocationName;
if (!string.IsNullOrEmpty(subExpression))
testExpression += "/" + subExpression;
}
}
return testExpression;
}
/// <summary>
/// Returns true if the specified operation has been tagged as requiring the usual
/// 'Result' class suppressed (due to a void return type)
/// </summary>
/// <param name="operation"></param>
public static bool HasSuppressedResult(Operation operation)
{
return operation.model.Customizations.ResultGenerationSuppressions.Contains(operation.Name);
}
// common code to upper case, when EC2, the first char of the marshall location name
public static string TransformMarshallLocationName(bool isEC2Protocol, string locationName)
{
if (string.IsNullOrEmpty(locationName) || !isEC2Protocol)
return locationName;
return locationName.ToUpperFirstCharacter();
}
// common code to lower case, when EC2, the first char of the unmarshall location name
public static string TransformUnmarshallLocationName(bool isEC2Protocol, string locationName)
{
if (string.IsNullOrEmpty(locationName) || !isEC2Protocol)
return locationName;
return locationName.ToLowerFirstCharacter();
}
/// <summary>
/// Sets the first character of the param to lower, if it's an acronym it lowers it all until the next word
/// </summary>
/// <param name="param">The name of the parameter name for the constructor</param>
/// <returns>The parameter as a camel cased name</returns>
public static string CamelCaseParam(string param, bool removeUnderscoresAndDashes = false)
{
param = param ?? "";
if (removeUnderscoresAndDashes)
{
// handle kebab-case and snake_case
param = string.Join("", param.Split('-').Select((s, i) => i == 0 ? s : s.ToUpperFirstCharacter()));
param = string.Join("", param.Split('_').Select((s, i) => i == 0 ? s : s.ToUpperFirstCharacter()));
}
if (param.Length < 2 || char.IsUpper(param.ToCharArray()[0]) && char.IsLower(param.ToCharArray()[1]))
{
if ((char.ToLower(param.ToCharArray()[0]) + param.Substring(1)).Equals("namespace"))
{
return "awsNamespace";
}
return param.Length < 2 ? param.ToLower() : char.ToLower(param.ToCharArray()[0]) + param.Substring(1);
}
// If it gets here it's an acronym
int secondWord = 0;
for (int i = 0; i < param.ToCharArray().Length - 1; i++)
{
if (char.IsUpper(param.ToCharArray()[i]) && char.IsLower(param.ToCharArray()[i + 1]))
{
secondWord = i;
break;
}
else if (char.IsUpper(param.ToCharArray()[i]) && char.IsUpper(param.ToCharArray()[i + 1]))
{
continue;
}
}
if (secondWord == 0)
{
if (param.ToLower().Equals("namespace"))
{
return "awsNamespace";
}
return param.ToLower();
}
var camelParam = new StringBuilder();
for (int i = 0; i < secondWord; i++)
{
camelParam.Append(char.ToLower(param.ToCharArray()[i]));
}
camelParam.Append(param.Substring(secondWord));
if (camelParam.ToString().Equals("namespace"))
{
return "awsNamespace";
}
return camelParam.ToString();
}
}
public static class StringExtensions
{
public static string ToPascalCase(this string s)
{
return GeneratorHelpers.CamelCaseParam(s, removeUnderscoresAndDashes: true).ToUpperFirstCharacter();
}
public static string ToCamelCase(this string s)
{
return GeneratorHelpers.CamelCaseParam(s);
}
public static string ToClassMemberCase(this string s)
{
return "_" + s.ToCamelCase();
}
/// <summary>
/// Capitalizes the first character of a string, used to create proper naming for services, attributes, and operations
/// </summary>
public static string ToUpperFirstCharacter(this string s)
{
var txt = s.Substring(0,1).ToUpperInvariant();
if (s.Length > 1)
txt += s.Substring(1);
return txt;
}
/// <summary>
/// Changes first character of a string to lower case.
/// </summary>
public static string ToLowerFirstCharacter(this string s)
{
var txt = s.Substring(0, 1).ToLowerInvariant();
if (s.Length > 1)
txt += s.Substring(1);
return txt;
}
public static string ToNativeType(this string type, bool useNullableTypes = false)
{
switch (type.ToLower())
{
case "string": return "string";
case "boolean": return "bool" + (useNullableTypes ? "?" : "");
default:
throw new Exception("Unsupported type");
}
}
public static string ToNativeValue(this JsonData value)
{
if (value.IsBoolean) return value.ToString().ToLower();
if (value.IsString) return $"\"{(string)value}\"";
if (value.IsInt) return $"{(int)value}";
throw new Exception("Unsupported type");
}
public static string SanitizeQuotes(this string s)
{
return s.Replace("\"", "\"\"");
}
public static string ToVariableName(this string s)
{
return s.Replace("-", "_");
}
}
}
| 468 |
aws-sdk-net | aws | C# | using System.Collections.Generic;
using System.IO;
namespace ServiceClientGenerator
{
/// <summary>
/// Command line options for the AWS SDK code generator.
/// </summary>
public class GeneratorOptions
{
/// <summary>
/// If set, causes the generator to emit additional diagnostic messages
/// whilst running.
/// </summary>
public bool Verbose { get; set; }
/// <summary>
/// If set, waits for keypress before exiting generation.
/// </summary>
public bool WaitOnExit { get; set; }
/// <summary>
/// The name and location of the json manifest file listing all supported services
/// for generation. By default this is located in the ServiceModels folder and is
/// named '_manifests.json'.
/// </summary>
public string Manifest { get; set; }
/// <summary>
/// The name and location of the json versions file listing the versions of all supported
/// services for generation. By default this is located in the ServiceModels folder and is
/// named '_sdk-versions.json'.
/// </summary>
public string Versions { get; set; }
/// <summary>
/// The location of the folder containing the service model files.
/// </summary>
public string ModelsFolder { get; set; }
public string TestModelsFolder { get; set; }
/// <summary>
/// The root folder beneath which the code for the SDK is arranged. Source code exists under
/// a .\src folder, which is further partitioned into core runtime (.\Core) and service code
/// (.\Services). Tests are placed under a .\test folder, which is further partitioned into
/// unit tests (.\UnitTests) and integration tests (.\IntegrationTests).
/// </summary>
public string SdkRootFolder { get; set; }
/// <summary>
/// Collection of one or more service model identifiers. If null or empty, code for all
/// services listed in the GenerationManifest file will be generated. If set, only
/// the services listed will be generated. The value(s) provided need to match the
/// 'model' values in the service manifest file.
/// </summary>
public string ServiceModels { get; set; }
/// <summary>
/// Allows disabling orphaned shape and service cleanup.
/// Useful to set if you a) specify <see cref="ServiceModels"/> and b)
/// don't want to remove previously generated services. This is often the case
/// in a development environment.
/// </summary>
public bool SkipRemoveOrphanCleanup { get; set; }
/// <summary>
/// If set causes all servicename.customizations*.json files to be 'compiled' into
/// one json file during generation.
/// </summary>
public bool CompileCustomizations { get; set; }
/// <summary>
/// If set, the contents of the generated subfolder hierarchy are deleted prior
/// to code generation. The default behavior is to leave existing generated
/// content in-place and perform a cumulative generation pass.
/// </summary>
public bool Clean { get; set; }
/// <summary>
/// If set the solution files will be rebuilt even if no new projects were added.
/// </summary>
public bool ForceSolutionRebuilt { get; set; }
/// <summary>
/// If set, the generator will create a vsix (Visual Studio Extension) project and manifest.
/// This project will reference all of the service specific code analysis projects.
/// The default behavior is not to create any assets.
/// </summary>
public bool CreateCodeAnalysisVsixAssets { get; set; }
public string SelfServiceModel { get; set; }
public string SelfServiceBaseName { get; set; }
public string SelfServiceEndpointPrefix { get; set; }
public string SelfServiceSigV4Name { get; set; }
public GeneratorOptions()
{
Verbose = false;
WaitOnExit = false;
// default paths are relative to executing generator assembly
// in bin/debug or bin/release
Manifest = Path.Combine("..", "..", "..", "ServiceModels", "_manifest.json");
Versions = Path.Combine("..", "..", "..", "ServiceModels", "_sdk-versions.json");
ModelsFolder = Path.Combine("..", "..", "..", "ServiceModels");
TestModelsFolder = Path.Combine("..", "..", "..", "TestServiceModels");
SdkRootFolder = Path.Combine("..", "..", "..", "..", "sdk");
ServiceModels = string.Empty; // process all services
CompileCustomizations = true;
Clean = false;
CreateCodeAnalysisVsixAssets = false;
}
}
}
| 115 |
aws-sdk-net | aws | C# | namespace ServiceClientGenerator
{
public enum H2SupportDegree
{
None,
Optional,
Required,
EventStream
}
} | 10 |
aws-sdk-net | aws | C# | using System.Reflection;
using Json.LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using ServiceClientGenerator.Endpoints;
namespace ServiceClientGenerator
{
/// <summary>
/// Members are properties are parts of a shape, they are used to identify sub shapes that the parent shape owns
/// </summary>
public class Member : BaseModel
{
public const string Locationkey = "location";
public const string MemberKey = "member";
public const string FlattenedKey = "flattened";
public const string JsonValueKey = "jsonvalue";
public const string DeprecatedKey = "deprecated";
public const string RequiredKey = "required";
public const string DeprecatedMessageKey = "deprecatedMessage";
public const string HostLabelKey = "hostLabel";
public const string EventPayloadKey = "eventpayload";
private const string UnhandledTypeDecimalErrorMessage = "Unhandled type 'decimal' : using .net's decimal type for modeled decimal type may result in loss of data. decimal type members should explicitly opt-in via shape customization.";
private const string BackwardsCompatibleDateTimePropertySuffix = "Utc";
private readonly string _name;
private string _newType;
readonly string _defaultMarshallName;
public Member(ServiceModel model, Shape owningShape, string name, string defaultMarshallName, CustomizationsModel.PropertyInjector propertyInjector)
: base(model, propertyInjector.Data)
{
this.OwningShape = owningShape;
_name = name;
_defaultMarshallName = defaultMarshallName;
this.PropertyModifier = null;
this.PropertyInjector = propertyInjector;
}
public Member(ServiceModel model, Shape owningShape, string name, string defaultMarshallName, JsonData data, CustomizationsModel.PropertyModifier propertyModifier)
: base(model, data)
{
this.OwningShape = owningShape;
_name = name;
_defaultMarshallName = defaultMarshallName;
this.PropertyModifier = propertyModifier;
this.PropertyInjector = null;
}
public Shape OwningShape { get; protected set; }
// injected members are not subject to renaming, exclusion etc
public bool IsInjected
{
get { return PropertyInjector != null; }
}
public bool HasModifier
{
get { return PropertyModifier != null; }
}
public CustomizationsModel.PropertyModifier PropertyModifier { get; protected set; }
public CustomizationsModel.PropertyInjector PropertyInjector { get; protected set; }
/// <summary>
/// The access modifier of the property. Defaults to public if not set in the customization.
/// </summary>
public string AccessModifier
{
get
{
if (!this.HasModifier)
return "public";
return this.PropertyModifier.AccessModifier;
}
}
/// <summary>
/// The name of the member with the first character lower and begins with an underscore: _nameHere.
/// It includes the backward compatibility suffix if required.
/// </summary>
public string VariableName
{
get
{
if (IsBackwardsCompatibleDateTimeProperty)
return BaseVariableName + BackwardsCompatibleDateTimePropertySuffix;
return BaseVariableName;
}
}
/// <summary>
/// The name of the property's backing to be used in backwards compatibility property names
/// </summary>
public string BackwardCompatibilityVariableName
{
get
{
if (IsBackwardsCompatibleDateTimeProperty)
return BaseVariableName;
throw new Exception("Property " + BasePropertyName + " is not marked as requiring backward compatibility");
}
}
/// <summary>
/// The name of the member with the first character lower and begins with an underscore: _nameHere.
/// This doesn't include the backward compatibility suffix.
/// </summary>
private string BaseVariableName
{
get
{
string memberName = null;
// Follow any property renaming for this member for consistent viewing
if (!IsInjected)
{
var propertyModifier = this.model.Customizations.GetPropertyModifier(OwningShape.Name, this._name);
if (propertyModifier != null)
memberName = propertyModifier.EmitName;
}
if (string.IsNullOrEmpty(memberName))
memberName = this._name;
return memberName.ToClassMemberCase();
}
}
/// <summary>
/// The name of the member with the first character lower: nameHere
/// </summary>
public string ArgumentName
{
get
{
// ignoring any property renaming when used as an argument at this time
return GeneratorHelpers.CamelCaseParam(this._name);
}
}
/// <summary>
/// Used for getting any custom changes to the member such as changing the type from a string to a DateTime etc.
/// </summary>
public CustomizationsModel.DataTypeOverride OverrideDataType
{
get
{
// not applicable to injected properties, since we assume they are
// configured to match what must be produced
if (IsInjected)
return null;
var overrideType = this.model.Customizations.OverrideDataType(OwningShape.Name, this._name);
return overrideType;
}
}
/// <summary>
/// Determines if the member is customized to specifically use a nullable type
/// </summary>
public bool UseNullable
{
get
{
return this.model.Customizations.UseNullable(OwningShape.Name, this._name);
}
}
/// <summary>
/// Determines if the member is customized to emit an Is[Name]Set property.
/// </summary>
public bool EmitIsSetProperties
{
get
{
return this.model.Customizations.EmitIsSetProperties(OwningShape.Name, this._name);
}
}
/// <summary>
/// The name of the member as the first character upper: NameHere
/// Uses the custom name instead if it exists.
/// It includes the backward compatibility suffix if required.
/// </summary>
public string PropertyName
{
get
{
if (IsBackwardsCompatibleDateTimeProperty)
return BasePropertyName + BackwardsCompatibleDateTimePropertySuffix;
return BasePropertyName;
}
}
/// <summary>
/// The name of the member to be used in backwards compatibility property names
/// </summary>
public string BackwardCompatibilityPropertyName
{
get
{
if (IsBackwardsCompatibleDateTimeProperty)
return BasePropertyName;
throw new Exception("Property " + BasePropertyName + " is not marked as requiring backward compatibility");
}
}
/// <summary>
/// The name of the member as the first character upper: NameHere
/// Uses the custom name instead if it exists.
/// This doesn't include the backwards compatibility suffix.
/// </summary>
public string BasePropertyName
{
get
{
if (!IsInjected)
{
// Check to see if customizations is overriding the name specified in the model for the property.
var propertyModifier = this.model.Customizations.GetPropertyModifier(OwningShape.Name, this._name);
if (propertyModifier != null)
{
var overrideName = propertyModifier.EmitName;
if (!string.IsNullOrEmpty(overrideName))
return overrideName;
}
}
return _name.ToUpperFirstCharacter();
}
}
/// <summary>
/// The name of the marshaller
/// </summary>
public string MarshallName
{
get
{
return LocationName ?? _defaultMarshallName;
}
}
/// <summary>
/// Determines if this member resides in the head of the request/response
/// </summary>
public bool IsInHeader
{
get
{
var locationData = data[Locationkey];
var location = locationData == null ? null : locationData.ToString();
return !string.IsNullOrEmpty(location) &&
string.Equals(location, "header", StringComparison.Ordinal);
}
}
/// <summary>
/// The name of the location
/// </summary>
public string LocationName
{
get
{
if (ModelShape != null && !string.IsNullOrEmpty(ModelShape.LocationName) && ModelShape.IsFlattened)
return ModelShape.LocationName;
// if list, lookup member/metadata/xmlName
// otherwise, lookup metadata/xmlName
var source = data;
if (IsList)
{
var member = data[MemberKey];
if (member != null)
source = member;
}
var locationName = source[ServiceModel.LocationNameKey];
if (locationName == null) return null;
return locationName.ToString();
}
}
public bool IsEndpointDiscoveryId
{
get
{
return (bool)(this.data[ServiceModel.EndpointDiscoveryIdKey] ?? false);
}
}
/// <summary>
/// Determines if this member is a base64 encoded json in the header of the request/response
/// Note: In the future this may also include members that are not in a header. For now the generator assumes
/// that if IsJsonValue is true then IsInHeader is also true.
/// </summary>
public bool IsJsonValue
{
get
{
var jsonValueData = data[JsonValueKey];
return jsonValueData == null ? false : (bool)jsonValueData;
}
}
/// <summary>
/// If defined, specifies the namespace for the xml constructed
/// </summary>
public string XmlNamespace
{
get
{
return data[ServiceModel.XmlNamespaceKey] == null ? string.Empty :
(string)data[ServiceModel.XmlNamespaceKey][ServiceModel.XmlNamespaceUriKey];
}
}
/// <summary>
/// Determines if the member is flattened for the marshaller/unmarshaller
/// </summary>
public bool IsFlattened
{
get
{
var metadata = data[ServiceModel.MetadataKey];
if (metadata == null) return false;
var flattened = metadata[FlattenedKey];
if (flattened == null || !flattened.IsBoolean) return false;
return (bool)flattened;
}
}
/// <summary>
/// The location of the marshaller
/// </summary>
public MarshallLocation MarshallLocation
{
get
{
if (data[Locationkey] != null)
{
var location = (string)data[Locationkey];
MarshallLocation value;
if (!Enum.TryParse<MarshallLocation>(location, true, out value))
{
throw new Exception("Unknown MarshallLocation " + location);
}
return value;
}
// Default to Body if location is not specified.
return MarshallLocation.Body;
}
}
/// <summary>
/// The hostLabel of the shape
/// </summary>
public bool IsHostLabel
{
get
{
if (data[HostLabelKey] != null)
{
return (bool)data[HostLabelKey];
}
// Default to false (not a hostLabel) if hostLabel is not specified.
return false;
}
}
/// <summary>
/// If present, use instead of MarshallLocationName
/// </summary>
public string MarshallQueryName
{
get
{
return data[ServiceModel.QueryNameKey] == null ? string.Empty : (string)data[ServiceModel.QueryNameKey];
}
}
/// <summary>
/// The name of the location for the marshaller
/// </summary>
public string MarshallLocationName
{
get
{
return data[ServiceModel.LocationNameKey] == null ? string.Empty : (string)data[ServiceModel.LocationNameKey];
}
}
public string GetParamDocumentationForOperation(string operationName)
{
if (this.Documentation.Equals(string.Empty))
{
return "A property of " + operationName + "Request used to execute the " + operationName + " service method.";
}
else
{
var sb = new StringBuilder(this.Documentation);
return sb.Replace("<p>", string.Empty)
.Replace("</p>", string.Empty)
.Replace("\n", string.Empty)
.Replace(" ", " ")
.ToString();
}
}
public string GetParamDocumentationForConstructor(string className)
{
if (this.Documentation.Equals(string.Empty))
{
return "Sets the " + className + " " + this.PropertyName + " property";
}
else
{
var sb = new StringBuilder(this.Documentation);
return sb.Replace("<p>", string.Empty)
.Replace("</p>", string.Empty)
.Replace("\n", string.Empty)
.Replace(" ", " ")
.ToString();
}
}
/// <summary>
/// Used to get the proper type of the member so that it can be used in the generator for proper code
/// </summary>
/// <returns>The proper name of the type for the member</returns>
public string DetermineType()
{
return DetermineType(this.data, false);
}
/// <summary>
/// Determines the type of the member based on customizations, if it isn't custom then it pulls
/// from the full json model to get the shape of this member
/// </summary>
/// <param name="extendedData">The json data from the parent shape model</param>
/// <param name="treatEnumsAsString">If true all any found enum type will be returned as a string</param>
/// <returns></returns>
private string DetermineType(JsonData extendedData, bool treatEnumsAsString)
{
JsonData typeNode = null;
// Check to see if customizations is overriding - first by simple type remap
// and then via more extensive customization. If we are handed a collection
// shape to begin with, this check is whether the collection shape, not the
// collected type, is remapped.
/*var remapAsShapeName = this.model.Customizations.GetSubstituteShapeName(this.Shape.Name);
if (remapAsShapeName != null)
{
var remappedShape = this.model.FindShape(remapAsShapeName);
if (remappedShape == null)
throw new Exception(string.Format("Found shape remap from {0} to {1} but no such shape in model!",
this.Shape.Name, remapAsShapeName));
if (remappedShape.IsStructure)
return remapAsShapeName;
switch (remappedShape.Type)
{
case "boolean":
return "bool";
case "integer":
return "int";
case "timestamp":
return "DateTime";
default:
return remappedShape.Type;
}
}*/
var overrideType = this.model.Customizations.OverrideDataType(OwningShape.Name, this._name);
if (overrideType != null)
{
this._newType = overrideType.DataType;
return overrideType.DataType;
}
var extendsNode = extendedData[ServiceModel.ShapeKey];
if (extendsNode == null)
throw new Exception("Missing extends for member " + this._name);
JsonData memberShape = null;
// if this shape is a collection, has the collected type been remapped?
var emitAsShapeName = this.model.Customizations.GetSubstituteShapeName(extendsNode.ToString());
var renameShape = this.model.Customizations.GetOverrideShapeName(extendsNode.ToString());
if (emitAsShapeName == null)
{
memberShape = this.model.DocumentRoot[ServiceModel.ShapesKey][extendsNode.ToString()];
typeNode = memberShape[Shape.TypeKey];
}
else
{
// we only handle remap to one level at present
memberShape = this.model.DocumentRoot[ServiceModel.ShapesKey][emitAsShapeName];
typeNode = memberShape[Shape.TypeKey];
}
var documentTrait = memberShape[Shape.DocumentKey];
if (documentTrait?.IsBoolean == true && (bool) documentTrait)
return "Amazon.Runtime.Documents.Document";
if (typeNode == null)
throw new Exception("Type is missing for shape " + extendsNode.ToString());
switch (typeNode.ToString())
{
case "string":
if (!treatEnumsAsString && memberShape["enum"] != null)
{
return (renameShape ?? extendsNode.ToString()).ToUpperFirstCharacter();
}
return "string";
case "blob":
if (this.IsStreaming)
return "Stream";
return "MemoryStream";
case "boolean":
return "bool";
case "double":
return "double";
case "float":
return "float";
case "integer":
return "int";
case "long":
return "long";
case "timestamp":
return "DateTime";
case "structure":
return emitAsShapeName ?? renameShape ?? extendsNode.ToString();
case "map":
var keyType = DetermineType(memberShape["key"], true);
var valueType = DetermineType(memberShape["value"], true);
return string.Format("Dictionary<{0}, {1}>", keyType, valueType);
case "list":
var listType = DetermineType(memberShape["member"], true);
return string.Format("List<{0}>", listType);
case "decimal":
throw new Exception(UnhandledTypeDecimalErrorMessage);
default:
throw new Exception("Unknown type " + typeNode.ToString());
}
}
/// <summary>
/// Returns the type of the marshaller if it is customized, null otherwise
/// </summary>
public string CustomMarshallerTransformation
{
get
{
// Check to see if customizations is overriding.
var overrideType = this.model.Customizations.OverrideDataType(OwningShape.Name, this._name);
if (overrideType != null)
return overrideType.Marshaller;
return null;
}
}
/// <summary>
/// This method gets the name of an unmarshaller for a type. It is used from within DetermineTypeUnmarshallerInstantiate
/// to get the types for the generic declarations of maps and lists.
/// </summary>
/// <param name="extendedData">The data for the member defined in the shape</param>
/// <returns></returns>
string GetTypeUnmarshallerName(JsonData extendedData)
{
// Check to see if customizations is overriding.
var overrideType = this.model.Customizations.OverrideDataType(OwningShape.Name, this._name);
if (overrideType != null)
return overrideType.Unmarshaller;
var extendsNode = extendedData[ServiceModel.ShapeKey];
if (extendsNode == null)
throw new Exception("Missing extends for member " + this._name);
var memberShape = this.model.DocumentRoot[ServiceModel.ShapesKey][extendsNode.ToString()];
var document = memberShape[Shape.DocumentKey];
if (document?.IsBoolean == true && (bool)document)
return "Amazon.Runtime.Documents.Internal.Transform.DocumentUnmarshaller";
var typeNode = memberShape[Shape.TypeKey];
if (typeNode == null)
throw new Exception("Type is missing for shape " + extendsNode.ToString());
switch (typeNode.ToString())
{
case "string":
return "StringUnmarshaller";
case "blob":
return "MemoryStreamUnmarshaller";
case "boolean":
return "BoolUnmarshaller";
case "double":
return "DoubleUnmarshaller";
case "float":
return "FloatUnmarshaller";
case "integer":
return "IntUnmarshaller";
case "long":
return "LongUnmarshaller";
case "timestamp":
return "DateTimeUnmarshaller";
case "structure":
var shapeName = extendsNode.ToString();
var renamedShape = this.model.Customizations.GetOverrideShapeName(shapeName);
var substitutedShape = this.model.Customizations.GetSubstituteShapeName(shapeName);
if (!string.IsNullOrWhiteSpace(renamedShape))
{
shapeName = renamedShape;
}
else if(!string.IsNullOrWhiteSpace(substitutedShape))
{
shapeName = substitutedShape;
}
return shapeName + "Unmarshaller";
case "map":
var keyType = DetermineType(memberShape[Shape.KeyKey], true);
var keyTypeUnmarshaller = GetTypeUnmarshallerName(memberShape[Shape.KeyKey]);
var valueType = DetermineType(memberShape[Shape.ValueKey], true);
var valueTypeUnmarshaller = GetTypeUnmarshallerName(memberShape[Shape.ValueKey]);
return string.Format("DictionaryUnmarshaller<{0}, {1}, {2}, {3}>",
keyType, valueType, keyTypeUnmarshaller, valueTypeUnmarshaller);
case "list":
var listType = DetermineType(memberShape[Member.MemberKey], true);
var listTypeUnmarshaller = GetTypeUnmarshallerName(memberShape[Member.MemberKey]);
return string.Format("ListUnmarshaller<{0}, {1}>",
listType, listTypeUnmarshaller);
case "decimal":
throw new Exception(UnhandledTypeDecimalErrorMessage);
default:
throw new Exception("Unknown type " + typeNode.ToString());
}
}
/// <summary>
/// Determines the type of the unmarshaller for the member
/// </summary>
/// <returns>A string that can be used as a proper name for the unmarshaller</returns>
public string DetermineTypeUnmarshallerInstantiate()
{
return this.DetermineTypeUnmarshallerInstantiate(this.data);
}
/// <summary>
/// This returns the code that instantiates an unmarshaller. It will be called recursively for maps and
/// lists to handle the generic declarations.
/// </summary>
/// <param name="extendedData"></param>
/// <returns></returns>
public string DetermineTypeUnmarshallerInstantiate(JsonData extendedData)
{
// Check to see if customizations is overriding.
var overrideType = this.model.Customizations.OverrideDataType(OwningShape.Name, this._name);
if (overrideType != null && !string.IsNullOrEmpty(overrideType.Unmarshaller))
return overrideType.Unmarshaller + ".Instance";
var extendsNode = extendedData[ServiceModel.ShapeKey];
if (extendsNode == null)
throw new Exception("Missing extends for member " + this._name);
JsonData memberShape = null;
var substituteType = this.model.Customizations.GetSubstituteShapeName(extendsNode.ToString());
var renameShape = this.model.Customizations.GetOverrideShapeName(extendsNode.ToString());
memberShape = substituteType != null
? this.model.DocumentRoot[ServiceModel.ShapesKey][substituteType]
: this.model.DocumentRoot[ServiceModel.ShapesKey][extendsNode.ToString()];
var document = memberShape[Shape.DocumentKey];
if (document?.IsBoolean == true && (bool) document)
return "Amazon.Runtime.Documents.Internal.Transform.DocumentUnmarshaller.Instance";
var typeNode = memberShape[Shape.TypeKey];
if (typeNode == null)
throw new Exception("Type is missing for shape " + extendsNode);
switch (typeNode.ToString())
{
case "string":
return "StringUnmarshaller.Instance";
case "blob":
return "MemoryStreamUnmarshaller.Instance";
case "boolean":
return "BoolUnmarshaller.Instance";
case "double":
return "DoubleUnmarshaller.Instance";
case "float":
return "FloatUnmarshaller.Instance";
case "integer":
if (this.UseNullable)
return "NullableIntUnmarshaller.Instance";
return "IntUnmarshaller.Instance";
case "long":
return "LongUnmarshaller.Instance";
case "timestamp":
if (this.UseNullable)
return "NullableDateTimeUnmarshaller.Instance";
return "DateTimeUnmarshaller.Instance";
case "structure":
return (renameShape ?? extendsNode) + "Unmarshaller.Instance";
case "map":
var keyType = DetermineType(memberShape[Shape.KeyKey], true);
var keyTypeUnmarshaller = GetTypeUnmarshallerName(memberShape[Shape.KeyKey]);
var keyTypeUnmarshallerInstantiate = DetermineTypeUnmarshallerInstantiate(memberShape[Shape.KeyKey]);
var valueType = DetermineType(memberShape[Shape.ValueKey], true);
var valueTypeUnmarshaller = GetTypeUnmarshallerName(memberShape[Shape.ValueKey]);
var valueTypeUnmarshallerInstantiate = DetermineTypeUnmarshallerInstantiate(memberShape[Shape.ValueKey]);
if (this.model.Type == ServiceType.Json || this.model.Type == ServiceType.Rest_Json || this.model.Type == ServiceType.Rest_Xml)
return string.Format("new DictionaryUnmarshaller<{0}, {1}, {2}, {3}>(StringUnmarshaller.Instance, {5})",
keyType, valueType, keyTypeUnmarshaller, valueTypeUnmarshaller, keyTypeUnmarshallerInstantiate, valueTypeUnmarshallerInstantiate);
else
return string.Format("new KeyValueUnmarshaller<{0}, {1}, {2}, {3}>(StringUnmarshaller.Instance, {5})",
keyType, valueType, keyTypeUnmarshaller, valueTypeUnmarshaller, keyTypeUnmarshallerInstantiate, valueTypeUnmarshallerInstantiate);
case "list":
var listType = DetermineType(memberShape[Shape.MemberKey], true);
var listTypeUnmarshaller = GetTypeUnmarshallerName(memberShape[Shape.MemberKey]);
var listTypeUnmarshallerInstantiate = DetermineTypeUnmarshallerInstantiate(memberShape[Shape.MemberKey]);
if (this.model.Type == ServiceType.Json || this.model.Type == ServiceType.Rest_Json)
return string.Format("new ListUnmarshaller<{0}, {1}>({2})",
listType, listTypeUnmarshaller, listTypeUnmarshallerInstantiate);
else
return listTypeUnmarshallerInstantiate;
case "decimal":
throw new Exception(UnhandledTypeDecimalErrorMessage);
default:
throw new Exception("Unknown type " + typeNode.ToString());
}
}
public string GetPrimitiveType()
{
return this.Shape.GetPrimitiveType();
}
/// <summary>
/// Determines if they type of the member is a primitive that needs to be nullable.
/// If the shape is customized it uses the newtype to determine if it is nullable.
/// </summary>
public bool IsNullable
{
get
{
var emittingShapeType = this._newType; // set if we have a full override declaration
if (emittingShapeType == null)
{
// maybe a simple substitution?
var substituteData = this.model.Customizations.GetSubstituteShapeData(this.ModelShape.Name);
if (substituteData != null && substituteData[CustomizationsModel.EmitAsShapeKey] != null)
{
var shape = this.model.FindShape((string) substituteData[CustomizationsModel.EmitAsShapeKey]);
emittingShapeType = shape.Type;
}
}
return emittingShapeType != null
? Shape.NullableTypes.Contains(emittingShapeType, StringComparer.Ordinal)
: this.Shape.IsNullable;
}
}
/// <summary>
/// Determines if the operation is Idempotent.
/// </summary>
public bool IsIdempotent
{
get
{
var source = data[ServiceModel.IdempotencyTokenKey];
if (source != null && source.IsBoolean)
return (bool)source;
return false;
}
}
/// <summary>
/// Determines if the member is a map from the shape in the json model
/// </summary>
public bool IsMap
{
get
{
return this.Shape.IsMap;
}
}
/// <summary>
/// Determines if the member is a list from the shape in the json model
/// </summary>
public bool IsList
{
get
{
return this.Shape.IsList;
}
}
/// <summary>
/// Determines if the member is a structure from the shape in the json model
/// </summary>
public bool IsStructure
{
get
{
return this.Shape.IsStructure;
}
}
/// <summary>
/// Determines if the member is a memorystream from the shape in the json model
/// </summary>
public bool IsMemoryStream
{
get
{
return this.Shape.IsMemoryStream;
}
}
/// <summary>
/// Determines if the member has requiresLength from the shape in the json model
/// </summary>
public bool RequiresLength
{
get
{
return this.Shape.RequiresLength;
}
}
/// <summary>
/// Determines if the member is a stream from the shape in the json model
/// </summary>
public bool IsStreaming
{
get
{
return this.Shape.IsStreaming;
}
}
/// <summary>
/// Determines if the member is a document from the shape in the json model
/// </summary>
public bool IsDocument
{
get
{
return this.Shape.IsDocument;
}
}
/// <summary>
/// Determines if the member is deprecated
/// </summary>
public bool IsDeprecated
{
get
{
if (data[DeprecatedKey] != null && data[DeprecatedKey].IsBoolean)
return (bool)data[DeprecatedKey];
return false;
}
}
/// <summary>
/// Determines if the member is required
/// </summary>
public bool IsRequired
{
get
{
return OwningShape.IsFieldRequired(ModeledName);
}
}
/// <summary>
/// Returns the deprecation message specified in the model or in the customization file.
/// </summary>
public string DeprecationMessage
{
get
{
string message = this.model.Customizations.GetPropertyModifier(this.OwningShape.Name, this._name)?.DeprecationMessage ??
this.data[DeprecatedMessageKey].CastToString();
if (message == null)
throw new Exception(string.Format("The 'message' property of the 'deprecated' trait is missing for member {0}.{1}.\nFor example: \"MemberName\":{{ ... \"deprecated\":true, \"deprecatedMessage\":\"This property is deprecated, use XXX instead.\"}}", this.OwningShape.Name, this._name));
return message;
}
}
public bool IsExcluded
{
get { return this.model.Customizations.IsExcludedProperty(this.BasePropertyName, this.OwningShape.Name); }
}
/// <summary>
/// Determines if the member is an event payload type
/// </summary>
public bool IsEventPayload
{
get
{
if (data[EventPayloadKey] != null && data[EventPayloadKey].IsBoolean)
return (bool)data[EventPayloadKey];
return false;
}
}
public bool IsBackwardsCompatibleDateTimeProperty
{
get { return this.model.Customizations.IsBackwardsCompatibleDateTimeProperty(this.BasePropertyName, this.OwningShape.Name); }
}
/// <summary>
/// Determines if the member is a type that needs to be instantiated, such as a list or map
/// </summary>
public bool ShouldInstantiate
{
get { return this.IsMap || this.IsList; }
}
/// <summary>
/// Gets the name of the shape that the member extends so that info about the member can be retrieved
/// </summary>
string Extends
{
get
{
var extendsNode = this.data[ServiceModel.ShapeKey];
if (extendsNode == null)
throw new Exception("Missing extends for member " + this._name);
return extendsNode.ToString();
}
}
// Returns the original model shape
public Shape ModelShape
{
get
{
var memberShape = this.model.DocumentRoot[ServiceModel.ShapesKey][this.Extends];
return Shape.CreateShape(this.model, this.Extends, memberShape);
}
}
// Returns the Shape, potentially overriden by substitution, that we want to
// deal with
public Shape Shape
{
get
{
JsonData memberShape = null;
var substituteType = this.model.Customizations.GetSubstituteShapeName(this.Extends);
memberShape = substituteType != null
? this.model.DocumentRoot[ServiceModel.ShapesKey][substituteType]
: this.model.DocumentRoot[ServiceModel.ShapesKey][this.Extends];
if (memberShape == null)
throw new Exception("Type is missing for shape " + this.Extends);
return Shape.CreateShape(this.model, this.Extends, memberShape);
}
}
/// <summary>
/// Returns the name of this member as it appears in the model
/// </summary>
public string ModeledName
{
get
{
return this._name;
}
}
/// <summary>
/// TimestampFormat that may be specified on a member or a shape.
/// </summary>
public TimestampFormat TimestampFormat
{
get
{
if (!this.IsDateTime)
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"Property TimestampFormat is not valid for member {0} of type {1}.",
this.ModeledName, this.DetermineType()));
}
var resolvedTimestampFormat = data.GetTimestampFormat();
if (resolvedTimestampFormat == TimestampFormat.None)
{
// Fallback to shape's TimestampFormat if not specified at member level
// Fallback to marshall location/protocol rules if not specified at shape level
resolvedTimestampFormat = this.Shape.GetTimestampFormat(this.MarshallLocation);
}
return resolvedTimestampFormat;
}
}
/// <summary>
/// Returns if the member's type is timestamp.
/// </summary>
public bool IsDateTime
{
get
{
return this.DetermineType().Equals("DateTime", StringComparison.InvariantCulture);
}
}
/// <summary>
/// Returns the marshaller method to use in the generated marshaller code for a
/// member of primitive type.
/// </summary>
public string PrimitiveMarshaller
{
get
{
if (this.IsDateTime)
{
return "StringUtils.FromDateTimeTo" + this.TimestampFormat;
}
else
{
return "StringUtils.From" + this.GetPrimitiveType();
}
}
}
/// <summary>
/// Creates a representation of the member as a string using the member name
/// </summary>
/// <returns>The member name as a string</returns>
public override string ToString()
{
return this._name;
}
internal static TimestampFormat GetDefaultTimestampFormat(MarshallLocation marshallLocation, ServiceType serviceType)
{
// Rules used to default the format if timestampFormat is not specified.
// 1. All timestamp values serialized in HTTP headers are formatted using rfc822 by default.
// 2. All timestamp values serialized in query strings are formatted using iso8601 by default.
if (marshallLocation == MarshallLocation.Header)
{
return TimestampFormat.RFC822;
}
else if (marshallLocation == MarshallLocation.QueryString)
{
return TimestampFormat.ISO8601;
}
else
{
// Return protocol defaults if marshall location is not header or querystring.
// The default timestamp formats per protocol for structured payload shapes are as follows.
// rest-json: unixTimestamp
// jsonrpc: unixTimestamp
// rest-xml: iso8601
// query: iso8601
// ec2: iso8601
switch (serviceType)
{
case ServiceType.Rest_Json:
return TimestampFormat.UnixTimestamp;
case ServiceType.Json:
return TimestampFormat.UnixTimestamp;
case ServiceType.Query:
return TimestampFormat.ISO8601;
case ServiceType.Rest_Xml:
return TimestampFormat.ISO8601;
default:
throw new InvalidOperationException(
"Encountered unknown model type (protocol): " + serviceType);
}
}
}
/// <summary>
/// Gets request member context parameter, used to drive endpoint resolution
/// </summary>
public ContextParameter ContextParameter
{
get
{
var parameter = data.SafeGet("contextParam");
return parameter == null ? null : new ContextParameter { name = parameter.SafeGetString("name") };
}
}
}
}
| 1,121 |
aws-sdk-net | aws | C# | using Json.LitJson;
using ServiceClientGenerator.Endpoints;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
/// <summary>
/// An object that represents the operations for a service api
/// </summary>
public class Operation : BaseModel
{
/// <summary>
/// The name of the operation as found in the json model
/// </summary>
readonly string name;
private OperationPaginatorConfig _operationPaginatorConfig;
/// <summary>
/// Constructs on operation from a service model, operation name, and the json model
/// </summary>
/// <param name="model">The model of the service the operation belongs to</param>
/// <param name="name">The name of the operation</param>
/// <param name="data">The json data from the model file</param>
public Operation(ServiceModel model, string name, JsonData data)
: base(model, data)
{
this.model = model;
this.name = name;
this.data = data;
}
/// <summary>
/// Constructs on operation from a service model, operation name, the json model, and the json paginators
/// </summary>
/// <param name="model">The model of the service the operation belongs to</param>
/// <param name="name">The name of the operation</param>
/// <param name="data">The json data from the model file</param>
/// <param name="paginatorData">The json data from the paginators file</param>
public Operation(ServiceModel model, string name, JsonData data, JsonData paginatorData)
: this(model, name, data)
{
if (paginatorData[ServiceModel.OutputTokenKey] != null && paginatorData[ServiceModel.InputTokenKey] != null)
{
_operationPaginatorConfig = new OperationPaginatorConfig(this, name, paginatorData);
}
}
/// <summary>
/// The name of the operation determined by checking if there are any customizations for a change of the name
/// then using the provided name if there isn't a custom name.
/// </summary>
public string Name
{
get
{
var modifiers = this.model.Customizations.GetOperationModifiers(ShapeName);
if (modifiers != null && !string.IsNullOrEmpty(modifiers.Name))
return modifiers.Name;
return ShapeName;
}
}
/// <summary>
/// Returns the raw shape name without customization
/// </summary>
public string ShapeName
{
get
{
return this.name;
}
}
public override string Documentation
{
get
{
var modifiers = this.model.Customizations.GetOperationModifiers(this.name);
if (modifiers != null && !string.IsNullOrEmpty(modifiers.Documentation))
return modifiers.Documentation;
return base.Documentation;
}
}
/// <summary>
/// Determines if the operation is Deprecated.
/// </summary>
public bool IsDeprecated
{
get
{
if (data[ServiceModel.DeprecatedKey] != null && data[ServiceModel.DeprecatedKey].IsBoolean)
return (bool)data[ServiceModel.DeprecatedKey];
return false;
}
}
/// <summary>
/// Returns the deprecation message specified in the model or in the customization file.
/// </summary>
public string DeprecationMessage
{
get
{
string message = this.model.Customizations.GetOperationModifiers(this.name)?.DeprecatedMessage ??
data[ServiceModel.DeprecatedMessageKey].CastToString();
if (message == null)
throw new Exception(string.Format("The 'message' property of the 'deprecated' trait is missing for operation {0}.\nFor example: \"OperationName\":{{\"name\":\"OperationName\", ... \"deprecated\":true, \"deprecatedMessage\":\"This operation is deprecated\"}}", this.name));
return message;
}
}
/// <summary>
/// Determines if a checksum needs to be sent in the Content-MD5 header.
/// Checks both the older "httpChecksumRequired" property as well as the newer
/// "httpChecksum.requestChecksumRequired" property
/// </summary>
public bool HttpChecksumRequired
{
get
{
if (data[ServiceModel.HttpChecksumRequiredKey] != null && data[ServiceModel.HttpChecksumRequiredKey].IsBoolean)
{
if ((bool)data[ServiceModel.HttpChecksumRequiredKey])
{
return true;
}
}
if (ChecksumConfiguration != null && ChecksumConfiguration.RequestChecksumRequired)
{
return true;
}
return false;
}
}
/// <summary>
/// Request and response flexible checksum configuration, read from the "httpChecksum" object
/// </summary>
public ChecksumConfiguration ChecksumConfiguration
{
get
{
if (data[ServiceModel.HttpChecksumKey] != null)
return new ChecksumConfiguration(data[ServiceModel.HttpChecksumKey]);
return null;
}
}
/// <summary>
/// Determines whether this operation's marshaller needs to call the checksum
/// handling in Core. This means it either requires a MD5 checksum and/or supports
/// flexible checksums.
/// </summary>
public bool RequiresChecksumDuringMarshalling
{
get
{
if (HttpChecksumRequired)
{
return true;
}
if (!string.IsNullOrEmpty(ChecksumConfiguration?.RequestAlgorithmMember))
{
return true;
}
return false;
}
}
/// <summary>
/// Determines if the operation is customized to be only internally accessible.
/// </summary>
public bool IsInternal
{
get
{
var modifiers = this.model.Customizations.GetOperationModifiers(this.name);
if (modifiers != null)
return modifiers.IsInternal;
return false;
}
}
/// <summary>
/// Determines if the operation is to be excluded from generation
/// </summary>
public bool IsExcluded
{
get
{
var modifiers = this.model.Customizations.GetOperationModifiers(this.name);
if (modifiers != null)
return modifiers.IsExcluded;
return false;
}
}
// set if we need to 'demote' the response output members into a shape hosted
// within a result class that doesn't exist in the service model. As an example
// EC2's DescribeImageAttribute outputs a response with multiple members. We take
// those and put them into an ImageAttribute shape that is referenced by the
// DescribeImageAttributeResult class (which doesn't exist in EC2's model).
public bool UseWrappingResult
{
get
{
var modifiers = this.model.Customizations.GetOperationModifiers(this.name);
if (modifiers != null)
return modifiers.UseWrappingResult;
return false;
}
}
/// <summary>
/// Allows the operation to return an empty result when the operation is modeled to return body result structure.
/// </summary>
public bool AllowEmptyResult
{
get
{
var modifiers = this.model.Customizations.GetOperationModifiers(this.name);
if (modifiers != null)
return modifiers.AllowEmptyResult;
return false;
}
}
public bool WrapsResultShape(string shapeName)
{
var modifiers = this.model.Customizations.GetOperationModifiers(this.name);
if (modifiers != null && modifiers.UseWrappingResult)
{
var wrappedShape = modifiers.WrappedResultShape;
return (!string.IsNullOrEmpty(wrappedShape) &&
wrappedShape.Equals(shapeName, StringComparison.Ordinal));
}
return false;
}
/// <summary>
/// If the operation uses a payload member, return that member so that it can be generated for the operation as well.
/// Payloads are place holders in the json models. They are represented as another shape and contain the actual necessary attributes.
/// </summary>
public Member RequestPayloadMember
{
get
{
if (this.RequestStructure != null)
{
var payload = this.RequestStructure.PayloadMemberName;
if (!string.IsNullOrWhiteSpace(payload))
{
return this.RequestStructure.Members.Single(m => m.MarshallName.Equals(payload, StringComparison.InvariantCultureIgnoreCase));
}
}
return null;
}
}
/// <summary>
/// The response payload member, null if one does not exist.
/// </summary>
public Member ResponsePayloadMember
{
get
{
if (this.ResponseStructure != null)
{
var payload = this.ResponseStructure.PayloadMemberName;
if (!string.IsNullOrWhiteSpace(payload))
{
return this.ResponseStructure.Members.Single(m => m.MarshallName.Equals(payload, StringComparison.InvariantCultureIgnoreCase));
}
}
return null;
}
}
/// <summary>
/// Gets the namespace of the payload for an XML object
/// </summary>
public string XmlNamespace
{
get
{
if (this.RequestPayloadMember != null)
{
return RequestPayloadMember.XmlNamespace;
}
return this.Input.XmlNamespace;
}
}
/// <summary>
/// A list of the members that are in the request header, empty if none
/// </summary>
public IList<Member> RequestHeaderMembers
{
get
{
return this.RequestStructure == null ?
new List<Member>() :
this.RequestStructure.Members.Where(
m => m.MarshallLocation == MarshallLocation.Header || m.MarshallLocation == MarshallLocation.Headers).ToList();
}
}
/// <summary>
/// A list of members that are in the response header, empty if none
/// </summary>
public IList<Member> ResponseHeaderMembers
{
get
{
return this.ResponseStructure == null ?
new List<Member>() :
this.ResponseStructure.Members.Where(
m => m.MarshallLocation == MarshallLocation.Header || m.MarshallLocation == MarshallLocation.Headers).ToList();
}
}
/// <summary>
/// A member that is defined by the status code of the response, null if none
/// </summary>
public Member ResponseStatusCodeMember
{
get
{
return this.ResponseStructure == null ?
null :
this.ResponseStructure.Members.SingleOrDefault(
m => m.MarshallLocation == MarshallLocation.StatusCode);
}
}
/// <summary>
/// A member in the response that is sent as a stream, null if none
/// </summary>
public Member ResponseStreamingMember
{
get
{
return this.ResponseStructure == null ?
null :
this.ResponseStructure.Members.SingleOrDefault(m => m.IsStreaming);
}
}
/// <summary>
/// Members that are part of the URI for the request, empty if none
/// </summary>
public IList<Member> RequestUriMembers
{
get
{
return this.RequestStructure == null ?
new List<Member>() :
this.RequestStructure.Members.Where(
m => m.MarshallLocation == MarshallLocation.Uri).ToList();
}
}
/// <summary>
/// List of members that are part of the QueryString, empty if none
/// </summary>
public IList<Member> RequestQueryStringMembers
{
get
{
return this.RequestStructure == null ?
new List<Member>() :
this.RequestStructure.Members.Where(
m => m.MarshallLocation == MarshallLocation.QueryString).ToList();
}
}
/// <summary>
/// A member in the request that is sent as a stream, null if none
/// </summary>
public Member RequestStreamingMember
{
get
{
return this.RequestStructure == null ?
null :
this.RequestStructure.Members.SingleOrDefault(m => m.IsStreaming);
}
}
/// <summary>
/// Members who are part of the request's body
/// </summary>
public IList<Member> RequestBodyMembers
{
get
{
if (this.RequestStructure == null)
return new List<Member>();
var payloadName = this.RequestStructure.PayloadMemberName;
return this.RequestStructure.Members.Where(
m =>
m.MarshallLocation == MarshallLocation.Body &&
!string.Equals(m.MarshallName, payloadName, StringComparison.Ordinal)).ToList();
}
}
/// <summary>
/// Members who are part of the response's body
/// </summary>
public IList<Member> ResponseBodyMembers
{
get
{
if (this.ResponseStructure == null)
return new List<Member>();
var payloadName = this.ResponseStructure.PayloadMemberName;
return this.ResponseStructure.Members.Where(
m =>
m.MarshallLocation == MarshallLocation.Body &&
!string.Equals(m.MarshallName, payloadName, StringComparison.Ordinal)).ToList();
}
}
/// <summary>
/// List of members that are decorated with a hostLabel value equal to true
/// </summary>
public IEnumerable<Member> RequestHostPrefixMembers
{
get
{
return this.RequestStructure == null ?
new List<Member>() :
this.RequestStructure.Members.Where(m => m.IsHostLabel);
}
}
public bool IsEventStreamOutput => ResponseStructure?.Members?.Any(
member => member.Shape?.IsEventStream ?? false)
?? false;
/// <summary>
/// Determines if the request structure will have members in the header
/// </summary>
public bool RequestHasHeaderMembers
{
get
{
return (this.RequestHeaderMembers.Count > 0);
}
}
/// <summary>
/// Determines if the request structure will have members in the body
/// </summary>
public bool RequestHasBodyMembers
{
get
{
// Has any members which are marshalled as part of the request body
return (this.RequestBodyMembers.Count > 0);
}
}
/// <summary>
/// Determines if the request structure has uri members
/// </summary>
public bool RequestHasUriMembers
{
get
{
return (this.RequestUriMembers.Count > 0);
}
}
/// <summary>
/// Determines if the request structure has query string members
/// </summary>
public bool RequestHasQueryStringMembers
{
get
{
// Has any members which are marshalled as part of the request body
return this.RequestStructure != null &&
this.RequestStructure.Members.Any(m => m.MarshallLocation == MarshallLocation.QueryString);
}
}
/// <summary>
/// Determines if the response structure will have members in the body
/// </summary>
public bool ResponseHasBodyMembers
{
get
{
// Has any members which are marshalled as part of the response body
return (this.ResponseBodyMembers.Count > 0);
}
}
/// <summary>
/// Determines if the response structure will have members in the header
/// </summary>
public bool ResponseHasHeaderMembers
{
get
{
return (this.ResponseHeaderMembers.Count > 0);
}
}
/// <summary>
/// Use query string if there are body members or a streamed member
/// </summary>
public bool UseQueryString
{
get
{
return this.RequestStructure != null &&
this.RequestStructure.Members.Any(m => m.MarshallLocation == MarshallLocation.QueryString);
}
}
/// <summary>
/// The input of the operation, a shape for a request structure
/// </summary>
public OperationInput Input
{
get
{
JsonData inputNode = this.data[ServiceModel.InputKey];
if (inputNode == null)
return null;
return new OperationInput(this.model, inputNode);
}
}
public OperationAuthType? AuthType
{
get
{
return OperationAuthTypeParser.Parse(this.data[ServiceModel.AuthTypeKey]);
}
}
/// <summary>
/// The method of the operation (i.e. POST, GET, ...)
/// </summary>
public string HttpMethod
{
get
{
JsonData httpNode = this.data[ServiceModel.HttpKey];
if (httpNode == null)
return string.Empty;
JsonData methodNode = httpNode[ServiceModel.MethodKey];
if (methodNode == null)
return string.Empty;
return methodNode.ToString();
}
}
/// <summary>
/// The endpoint hostPrefix of the operation
/// </summary>
public string EndpointHostPrefix
{
get
{
JsonData endpointNode = this.data[ServiceModel.EndpointKey];
if (endpointNode == null)
return string.Empty;
return endpointNode[ServiceModel.HostPrefixKey]?.ToString() ?? string.Empty;
}
}
/// <summary>
/// The endpointoperation flag marking if this is the operation to use for endpoint discovery.
/// </summary>
public bool IsEndpointOperation
{
get
{
return (bool)(this.data[ServiceModel.EndpointOperationKey] ?? false);
}
}
/// <summary>
/// The endpointdiscovery flag specifying if this operation is to use endpoint discovery.
/// </summary>
public bool EndpointDiscoveryEnabled
{
get
{
return this.data[ServiceModel.EndpointDiscoveryKey] != null ? true : false;
}
}
/// <summary>
/// The endpointdiscovery required flag specifying if this operation is required use endpoint discovery.
/// </summary>
public bool IsEndpointDiscoveryRequired
{
get
{
JsonData endpointDiscovery = this.data[ServiceModel.EndpointDiscoveryKey];
if (endpointDiscovery == null)
return false;
JsonData required = endpointDiscovery[ServiceModel.RequiredKey];
if (required == null)
return false;
if (required.IsBoolean)
return (bool)(required ?? false);
return Convert.ToBoolean((string)required);
}
}
/// <summary>
/// Members that are marked with the "endpointdiscoveryid" = true trait
/// </summary>
public IList<Member> RequestEndpointDiscoveryIdMembers
{
get
{
if (this.RequestStructure == null)
return new List<Member>();
return this.RequestStructure.Members.Where(m => m.IsEndpointDiscoveryId && m.GetPrimitiveType() == "String").ToList();
}
}
/// <summary>
/// Determines if the structure has any members that are marked with the "endpointdiscoveryid" = true trait
/// </summary>
public bool RequestHasEndpointDiscoveryIdMembers
{
get
{
return (this.RequestEndpointDiscoveryIdMembers.Count > 0);
}
}
/// <summary>
/// Determines if there is an Operation member for the operation with the request structure marked with "endpointoperation" = true.
/// </summary>
public bool RequestHasOperationEndpointOperationMember
{
get
{
if (this.RequestStructure == null)
return false;
return this.RequestStructure.Members.FirstOrDefault(m => m.PropertyName == "Operation") != null;
}
}
/// <summary>
/// Determines if there is an Identifiers member for the operation with the request structure marked with "endpointoperation" = true.
/// </summary>
public bool RequestHasIdentifiersEndpointOperationMember
{
get
{
if (this.RequestStructure == null)
return false;
return this.RequestStructure.Members.FirstOrDefault(m => m.PropertyName == "Operation") != null;
}
}
/// <summary>
/// Returns the Request URI without any query parameters.
/// </summary>
public string RequestUri
{
get
{
return this.RequestUriRaw.Split(new char[] { '?' }, 2)[0];
}
}
/// <summary>
/// Returns the static query parameters which are specified in the RequestUri itself.
/// Example : Cloud Search Domain's Search operation (/2013-01-01/search?format=sdk&pretty=true).
/// </summary>
public Dictionary<string, string> StaticQueryParameters
{
get
{
var queryParams = new Dictionary<string, string>();
var segments = this.RequestUriRaw.Split(new char[] { '?' }, 2);
if (segments.Count() > 1)
{
var staticQueryParams = segments[1];
foreach (string s in staticQueryParams.Split('&', ';'))
{
string[] nameValuePair = s.Split(new char[] { '=' }, 2);
if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
{
queryParams.Add(nameValuePair[0], nameValuePair[1]);
}
else
{
queryParams.Add(nameValuePair[0], null);
}
}
}
return queryParams;
}
}
private string RequestUriRaw
{
get
{
JsonData httpNode = this.data[ServiceModel.HttpKey];
if (httpNode == null)
return string.Empty;
JsonData requestUri = httpNode[ServiceModel.RequestUriKey];
if (requestUri == null)
return string.Empty;
return requestUri.ToString();
}
}
/// <summary>
/// The parent xml node for the response data coming back from the service.
/// </summary>
public string ResultWrapper
{
get
{
JsonData output = this.data[ServiceModel.OutputKey];
if (output == null)
return string.Empty;
JsonData wrapper = output[ServiceModel.ResultWrapperKey];
if (wrapper == null)
return string.Empty;
return wrapper.ToString();
}
}
/// <summary>
/// The list of errors that the service returns which will be turned into exceptions.
/// </summary>
public IList<ExceptionShape> Exceptions
{
get
{
var hashSet = new HashSet<ExceptionShape>();
var errors = this.data[ServiceModel.ErrorsKey];
if (errors != null && errors.IsArray)
{
foreach (JsonData error in errors)
{
var extendsNode = error[ServiceModel.ShapeKey];
if (extendsNode == null)
continue;
var structure = this.model.FindShape(extendsNode.ToString());
hashSet.Add((ExceptionShape)structure);
}
}
return hashSet.OrderBy(x => x.Name).ToList();
}
}
/// <summary>
/// The structure of the request for the operation as a shape, used to generate the request object
/// </summary>
public Shape RequestStructure
{
get
{
var inputNode = this.data[ServiceModel.InputKey];
if (inputNode == null)
return null;
var structure = this.model.FindShape(inputNode[ServiceModel.ShapeKey].ToString());
return structure;
}
}
/// <summary>
/// The shape of the response for the operation as a shape, used to generate the response object
/// </summary>
public Shape ResponseStructure
{
get
{
var outputNode = this.data[ServiceModel.OutputKey];
if (outputNode == null)
return null;
var structure = this.model.FindShape(outputNode[ServiceModel.ShapeKey].ToString());
return structure;
}
}
/// <summary>
/// For Set to true when the service model specifies a shape that should be wrapped in a response.
/// ElastiCache CreateCacheCluster is an example of this.
/// </summary>
public bool IsResponseWrapped
{
get
{
var outputNode = this.data[ServiceModel.OutputKey];
if (outputNode == null)
return false;
var wrappedNode = outputNode[ServiceModel.WrapperKey];
if (wrappedNode == null)
return false;
return bool.Parse(wrappedNode.ToString());
}
}
public IList<Example> Examples
{
get
{
var list = new List<Example>();
var data = this.model.Customizations.GetExamples(this.name);
foreach(JsonData example in data)
{
list.Add(new Example(this.model, this.name, example));
}
return list;
}
}
public bool HasExamples
{
get
{
return this.model.Customizations.GetExamples(this.Name).Count > 0;
}
}
/// <summary>
/// Determines if a given member should be treated as a greedy path, meaning
/// that the resource path contains {MEMBER_NAME+} instead of simply {MEMBER_NAME}.
/// </summary>
/// <param name="member"></param>
/// <returns></returns>
public string GetUriResourcePathTarget(Member member,out bool isGreedy)
{
var greedyPathResourcePathIdentifier = "{" + member.MarshallLocationName + "+}";
var simplePathResourcePathIdentifier = "{" + member.MarshallLocationName + "}";
isGreedy = this.RequestUri.IndexOf(greedyPathResourcePathIdentifier, StringComparison.Ordinal) >= 0;
var isSimple = this.RequestUri.IndexOf(simplePathResourcePathIdentifier, StringComparison.Ordinal) >= 0;
if (isGreedy && isSimple)
throw new Exception(string.Format("Unexpected behavior/model, member {1} of operation {0} is both a simple and a greedy parameter", this.Name, member.PropertyName));
else if (!isGreedy && !isSimple)
throw new Exception(string.Format("Unexpected behavior/model, member {1} of operation {0} is neither a simple nor a greedy parameter", this.Name, member.PropertyName));
else if (isGreedy)
return greedyPathResourcePathIdentifier;
else
return simplePathResourcePathIdentifier;
}
/// <summary>
/// Represents the operation as a string
/// </summary>
/// <returns>The name of the operation, customized if specified</returns>
public override string ToString()
{
return Name;
}
/// <summary>
/// Returns any operation modifiers that have been set for this operation.
/// </summary>
public CustomizationsModel.OperationModifiers OperationModifiers
{
get { return this.model.Customizations.GetOperationModifiers(this.Name); }
}
public string RestAPIDocUrl
{
get {
string serviceId = this.model.ServiceUid;
if (!string.IsNullOrEmpty(serviceId))
{
return string.Format(@"http://docs.aws.amazon.com/goto/WebAPI/{0}/{1}", serviceId, ShapeName);
}
else
{
return null;
}
}
}
/// <summary>
/// Paginators for an operation
/// </summary>
public OperationPaginatorConfig Paginators { get { return this._operationPaginatorConfig; } }
/// <summary>
/// Whether or not this operation has properly configured
/// paginators based on provided json configuration
/// </summary>
public bool UnsupportedPaginatorConfig { get; set; }
private static ConcurrentDictionary<string, bool> _checkedService = new ConcurrentDictionary<string, bool>();
/// <summary>
/// Gets list of static context parameters, used on operation to drive endpoint resolution
/// </summary>
public List<StaticContextParameter> StaticContextParameters
{
get
{
var result = new List<StaticContextParameter>();
var parameters = data.SafeGet("staticContextParams");
if (parameters != null)
{
foreach (var param in parameters.GetMap())
{
result.Add(new StaticContextParameter
{
name = param.Key,
value = param.Value["value"]
});
}
}
return result;
}
}
}
}
| 969 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
public enum OperationAuthType { None, V4, V4UnsignedBody, Bearer }
public static class OperationAuthTypeParser
{
private static readonly Dictionary<string, OperationAuthType> OperationAuthTypeMap = new Dictionary<string, OperationAuthType>
{
{ "none", OperationAuthType.None },
{ "v4", OperationAuthType.V4 },
{ "v4-unsigned-body", OperationAuthType.V4UnsignedBody },
{ "bearer", OperationAuthType.Bearer }
};
public static OperationAuthType? Parse(JsonData authTypeNode)
{
OperationAuthType authType;
if (authTypeNode == null)
return null;
else if (OperationAuthTypeMap.TryGetValue(authTypeNode.ToString(), out authType))
return authType;
else
throw new ArgumentException("authTypeNode does not contain a valid value for OperationAuthType valid values include: " +
String.Join(", ", OperationAuthTypeMap.Values.ToArray()));
}
}
}
| 36 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
public class OperationPaginatorConfig
{
private readonly JsonData data;
private readonly Operation operation;
/// <summary>
/// The name of the operation
/// </summary>
public string Name { get; }
private IList<OperationPaginatorConfigOption> _resultKeys;
/// <summary>
/// Result keys are the values in the response which
/// can be enumerated on
/// </summary>
public IList<OperationPaginatorConfigOption> ResultKeys
{
get
{
if (this._resultKeys == null)
{
this._resultKeys = CreatePaginatorConfigOptionList(data[ServiceModel.ResultKeyKey], false, 'o');
}
return this._resultKeys;
}
}
private IList<OperationPaginatorConfigOption> _inputTokens;
/// <summary>
/// The token in the request specifying where to start
/// receiving data
/// </summary>
public IList<OperationPaginatorConfigOption> InputTokens {
get
{
if (this._inputTokens == null)
{
this._inputTokens = InitializeInputTokens();
}
return this._inputTokens;
}
}
private IList<OperationPaginatorConfigOption> _outputTokens;
/// <summary>
/// The token in the response to use in the subsequent request
/// to specify where to start receiving data
/// </summary>
public IList<OperationPaginatorConfigOption> OutputTokens {
get
{
if (this._outputTokens == null)
{
this._outputTokens = InitializeOutputTokens();
}
return this._outputTokens;
}
}
private OperationPaginatorConfigOption _moreResults;
/// <summary>
/// Whether or not the response is truncated
/// </summary>
public OperationPaginatorConfigOption MoreResults
{
get
{
if (this._moreResults == null)
{
this._moreResults = GetOperationPaginatorConfigOption(data[ServiceModel.MoreResultsKey], false);
}
return this._moreResults;
}
}
private OperationPaginatorConfigOption _limitKey;
/// <summary>
/// The key specifying the number of results per
/// request
/// </summary>
public OperationPaginatorConfigOption LimitKey
{
get
{
if (this._limitKey == null)
{
this._limitKey = GetOperationPaginatorConfigOption(data[ServiceModel.LimitKeyKey]);
}
return this._limitKey;
}
}
/// <summary>
/// Return an OperationPaginatorConfigOption object for the paginator option.
/// This contains the Member associated with the option. Also, it adjusts the
/// name if it is a jmespath expression.
/// </summary>
/// <param name="node"> The JsonData node provided in the paginator config </param>
/// <param name="checkRequest"> Check the request object for a member matching the node </param>
/// <param name="checkResponse"> Check the response object for a member matching the node </param>
/// <param name="checkQuery"> Check the query object for a member matching the node </param>
/// <returns></returns>
internal OperationPaginatorConfigOption GetOperationPaginatorConfigOption(JsonData node,
bool checkRequest = true, bool checkResponse = true)
{
Member configOption = null;
var foundOptionInResponse = false;
if (node == null)
{
return null;
}
if (IsJmesPath(node, out var jmesPathChar))
{
return HandleJmesPath(node, (char) jmesPathChar, operation);
}
if (checkRequest)
{
configOption = CheckRequestForNode(m => m.ModeledName.Equals(node.ToString()));
}
if (checkResponse && configOption == null)
{
configOption = CheckResponseForNode(m => m.ModeledName.Equals(node.ToString()) || m.MarshallName.Equals(node.ToString()));
// foundOptionInResponse is used for wrapped result members which need to be
// handled differently for the SWF service.
foundOptionInResponse = configOption != null;
}
if (configOption == null)
{
return null;
}
if (this.operation.UseWrappingResult && foundOptionInResponse)
{
return new OperationPaginatorConfigOption(false,
this.operation.OperationModifiers.WrappedResultMember, configOption);
}
return new OperationPaginatorConfigOption(false, configOption);
}
/// <summary>
/// Check all parts of request for node to find the corresponding
/// member
/// </summary>
/// <param name="checkFunction">Function to search all members for node</param>
/// <returns></returns>
internal Member CheckRequestForNode(Func<Member, bool> checkFunction)
{
Member configOption = null;
if (operation.RequestHasBodyMembers)
{
configOption = operation.RequestBodyMembers.SingleOrDefault(checkFunction);
}
if (operation.RequestHasUriMembers && configOption == null)
{
configOption = operation.RequestUriMembers.SingleOrDefault(checkFunction);
}
if (operation.RequestHasQueryStringMembers && configOption == null)
{
configOption = operation.RequestQueryStringMembers.SingleOrDefault(checkFunction);
}
if (operation.RequestHasHeaderMembers && configOption == null)
{
configOption = operation.RequestHeaderMembers.SingleOrDefault(checkFunction);
}
return configOption;
}
/// <summary>
/// Check all parts of response for node to find the corresponding
/// member
/// </summary>
/// <param name="checkFunction">Function to search all members for node</param>
/// <returns></returns>
internal Member CheckResponseForNode(Func<Member, bool> checkFunction)
{
Member configOption = null;
if (operation.ResponseHasBodyMembers && configOption == null)
{
configOption = operation.ResponseBodyMembers.SingleOrDefault(checkFunction);
}
if (operation.ResponseHasHeaderMembers && configOption == null)
{
configOption = operation.ResponseHeaderMembers.SingleOrDefault(checkFunction);
}
return configOption;
}
/// <summary>
/// Check if a paginator option is a jmespath expression.
/// Currently support only '.'
/// </summary>
/// <param name="node"> The JsonData node provided in the paginator config </param>
/// <param name="jmesPathChar"> The character which is contained in the jmespath expression
/// (currently only supports '.') </param>
/// <returns></returns>
internal static bool IsJmesPath(JsonData node, out char? jmesPathChar)
{
var stringNode = node.ToString();
string jPattern = "^[a-zA-Z0-9]+\\.[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)*$";
if (System.Text.RegularExpressions.Regex.IsMatch(stringNode, jPattern))
{
jmesPathChar = '.';
return true;
}
jmesPathChar = null;
return false;
}
/// <summary>
/// Handle a jmespath expression for a paginator option. Currently
/// only supporting '.'
/// </summary>
/// <param name="node"> The JsonData node provided in the paginator config </param>
/// <param name="jmesPathChar"> The character which is contained in the jmespath expression
/// (currently only supports '.') </param>
/// <returns></returns>
internal static OperationPaginatorConfigOption HandleJmesPath(JsonData node, char jmesPathChar, Operation operation)
{
if (jmesPathChar == '.')
{
var nestedMembers = node.ToString().Split('.');
var currentShape = operation.ResponseStructure;
Member currentMember = null;
var codePath = new StringBuilder();
for(int i = 0; i < nestedMembers.Length; i++)
{
currentMember = currentShape.Members.FirstOrDefault(x => string.Equals(x.ModeledName, nestedMembers[i]));
if (currentMember == null)
{
return null;
}
if(codePath.Length > 0)
{
codePath.Append('.');
}
codePath.Append(currentMember.PropertyName);
currentShape = currentMember.Shape;
if (currentShape == null)
{
return null;
}
}
return new OperationPaginatorConfigOption(true, currentMember, $"{codePath}");
}
return null;
}
/// <summary>
/// Only initialize the input token and the output token
/// because they are mandatory. If they are not configured
/// properly, set operation.UnsupportedPaginatorConfig to true
/// </summary>
internal void InitializeOperationPaginatorConfig()
{
this._inputTokens = InitializeInputTokens();
this._outputTokens = InitializeOutputTokens();
if (this.InputTokens.Count != this.OutputTokens.Count)
{
this.operation.UnsupportedPaginatorConfig = true;
}
}
/// <summary>
/// Return a list of all input tokens as OperationPaginatorConfigOptions
/// </summary>
/// <returns></returns>
internal IList<OperationPaginatorConfigOption> InitializeInputTokens()
{
return CreatePaginatorConfigOptionList(data[ServiceModel.InputTokenKey], true, 'i');
}
/// <summary>
/// Return a list of all output tokens as OperationPaginatorConfigOptions
/// </summary>
/// <returns></returns>
internal IList<OperationPaginatorConfigOption> InitializeOutputTokens()
{
return CreatePaginatorConfigOptionList(data[ServiceModel.OutputTokenKey], true, 'o');
}
/// <summary>
/// Create a list of OperationPaginatorConfigOptions based on the data provided
/// </summary>
/// <param name="node"> The JsonData node provided in the paginator config </param>
/// <param name="setUnsupported"> Should the operation's paginator config be valid if there is an
/// issue finding a matching member </param>
/// <param name="mode"> Whether this is input or output token or neither</param>
/// <returns></returns>
internal IList<OperationPaginatorConfigOption> CreatePaginatorConfigOptionList(JsonData node, bool setUnsupported = true,
char mode = 'n')
{
var checkRequest = mode == 'i' || mode == 'n';
var checkResponse = mode == 'o' || mode == 'n';
IList<OperationPaginatorConfigOption> optionList = new List<OperationPaginatorConfigOption>();
if (node == null)
{
if (setUnsupported)
{
this.operation.UnsupportedPaginatorConfig = true;
}
return optionList;
}
else if (node.IsArray)
{
for (var i = 0; i < node.Count; i++)
{
var option = GetOperationPaginatorConfigOption(node[i], checkRequest, checkResponse);
if (option != null)
{
optionList.Add(option);
}
else if (setUnsupported)
{
this.operation.UnsupportedPaginatorConfig = true;
}
}
}
else
{
var option = GetOperationPaginatorConfigOption(node, checkRequest, checkResponse);
if (option != null)
{
optionList.Add(option);
}
else if (setUnsupported)
{
this.operation.UnsupportedPaginatorConfig = true;
}
}
return optionList;
}
/// <summary>
/// Create a new OperationPaginatorConfig
/// </summary>
/// <param name="operation"></param>
/// <param name="name"></param>
/// <param name="data"></param>
public OperationPaginatorConfig(Operation operation, string name, JsonData data)
{
this.operation = operation;
Name = name;
this.data = data;
this.operation.UnsupportedPaginatorConfig = false;
InitializeOperationPaginatorConfig();
}
}
}
| 366 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
public class OperationPaginatorConfigOption
{
/// <summary>
/// String name of the option
/// </summary>
public string Name { get; }
/// <summary>
/// If the response wraps a member containing
/// the config option, set this to the name of
/// that member. This is a workaround for
/// SimpleWorkFlow
/// </summary>
public string WrappedResultMember { get; }
/// <summary>
/// Whether or not the provided option
/// is a jmespath expression
/// </summary>
public bool IsJmesPath { get; }
/// <summary>
/// The member associated with the option
/// </summary>
public Member Member { get; }
/// <summary>
/// The property name of the member
/// or the full name containing "."
/// if jmespath
/// </summary>
public string PropertyName
{
get
{
if (IsJmesPath)
{
return Name;
}
if (WrappedResultMember != null)
{
return $"{WrappedResultMember}.{Member.PropertyName}";
}
return Member.PropertyName;
}
}
/// <summary>
/// Support only result keys which are of type List
/// </summary>
public string ListItemType
{
get
{
var type = this.Member.DetermineType();
var pattern = "^List\\<[a-zA-Z0-9]+\\>$";
if (System.Text.RegularExpressions.Regex.IsMatch(type, pattern))
{
return type.Substring(5, type.Length - 6);
}
return null;
}
}
/// <summary>
/// Whether or not this option is a list or a
/// dictionary. Mostly used for input/output token- checking
/// if it is null or if it is empty if list or dictionary
/// </summary>
public bool IsListOrDict
{
get
{
return this.Member.IsList || this.Member.IsMap;
}
}
/// <summary>
/// Create a new OperationPaginatorConfigOption object
/// and set whether or not it is a jmespath expression
/// </summary>
/// <param name="isJmesPath"> Whether or not it is a jmespath expression </param>
/// <param name="member"> Member associated with the option </param>
public OperationPaginatorConfigOption(bool isJmesPath, Member member)
{
IsJmesPath = isJmesPath;
Member = member;
}
/// <summary>
/// Create a new OperationPaginatorConfigOption object
/// and set whether or not it is a jmespath expression
/// </summary>
/// <param name="isJmesPath"> Whether or not it is a jmespath expression </param>
/// <param name="member"> Member associated with the option </param>
/// <param name="name"> String name of the option as found in paginator config </param>
public OperationPaginatorConfigOption(bool isJmesPath, Member member, string name)
: this(isJmesPath, member)
{
Name = name;
}
/// <summary>
/// Create a new OperationPaginatorConfigOption object
/// and set whether or not it is a jmespath expression
/// </summary>
/// <param name="isJmesPath"> Whether or not it is a jmespath expression </param>
/// <param name="member"> Member associated with the option </param>
/// <param name="wrappedResultMember">If the result of this operation is wrapped in a response
/// object. (workaround for SimpleWorkFlow) </param>
public OperationPaginatorConfigOption(bool isJmesPath, string wrappedResultMember, Member member)
: this(isJmesPath, member)
{
WrappedResultMember = wrappedResultMember;
}
}
}
| 126 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
/// <summary>
/// Describes a Project file to be generated
/// </summary>
public class Project
{
/// <summary>
/// Name of the project template configuration
/// </summary>
public string Name { get; set; }
/// <summary>
/// Used to generate the AssemblyName element of the project file
/// </summary>
public string AssemblyName { get; set; }
/// <summary>
/// Used to generate the ProjectReference elements of the project file
/// </summary>
public IEnumerable<ProjectFileCreator.ProjectReference> ProjectReferences { get; set; }
/// <summary>
/// Used to generate the Include tag of the Reference elements of the project file
/// </summary>
public IEnumerable<Dependency> ReferenceDependencies { get; set; }
/// <summary>
/// Used to generate the PackageReference elements of the project file
/// </summary>
public IEnumerable<ProjectFileCreator.PackageReference> PackageReferences { get; set; }
/// <summary>
/// Used to generate the Include tag of the Service elements of the project file
/// </summary>
public IEnumerable<string> Services { get; set; }
/// <summary>
/// Used to generate the HintPath for Reference elements relative to Nuget dependencies
/// </summary>
public string NugetPackagesLocation { get; set; }
/// <summary>
/// Used to generate the TargetFramework or TargetFrameworks element of the project file
/// </summary>
public IEnumerable<string> TargetFrameworks { get; set; }
/// <summary>
/// Used to generate the DefineConstants element of the project file
/// </summary>
public IEnumerable<string> DefineConstants { get; set; }
/// <summary>
/// Used to generate the Remove tag of the Compile elements of the project file
/// </summary>
public IEnumerable<string> CompileRemoveList { get; set; }
/// <summary>
/// Used to generate the Include tag of the Compile elements of the project file for directories
/// </summary>
public IEnumerable<string> SourceDirectories { get; set; }
/// <summary>
/// Used to generate the Include tag of the Compile elements of the project file for single files
/// </summary>
public IEnumerable<string> IndividualFileIncludes { get; set; }
/// <summary>
/// Used to generate the Include tag of the EmbeddedResource elements of the project file
/// </summary>
public IEnumerable<string> EmbeddedResources { get; set; }
/// <summary>
/// Used to generate the FrameworkPathOverride element of the project file
/// </summary>
public string FrameworkPathOverride { get; set; }
/// <summary>
/// Used to generate the OutputPath element of the project file
/// </summary>
public string OutputPathOverride { get; set; }
/// <summary>
/// Used to generate the NoWarn element of the project file
/// </summary>
public string SupressWarnings { get; set; }
/// <summary>
/// Used to generate the ProjectGuid element of the project file
/// </summary>
public string ProjectGuid { get; set; }
/// <summary>
/// Used to generate the RootNamespace element of the project file
/// </summary>
public string RootNamespace { get; set; }
/// <summary>
/// Used to decide wether to generate the AssemblyOriginatorKeyFile element of the project file
/// </summary>
public bool SignBinaries { get; set; }
/// <summary>
/// Used to generate the AssemblyOriginatorKeyFile element of the project file
/// </summary>
public string KeyFilePath { get; set; }
/// <summary>
/// Used to generate the OutputPath element of the project file
/// </summary>
public string BinSubfolder { get; set; }
/// <summary>
/// Used to generate the RuleSet path of the project file
/// </summary>
public string FxcopAnalyzerRuleSetFilePath { get; set; }
/// <summary>
/// Used to generate the RuleSet path for build of the project file
/// </summary>
public string FxcopAnalyzerRuleSetFilePathForBuild { get; set; }
/// <summary>
/// Used to generate the Custom Roslyn Analyzers dll directory
/// </summary>
public string CustomRoslynAnalyzersDllDirectory { get; set; }
}
}
| 136 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Json.LitJson;
namespace ServiceClientGenerator
{
/// <summary>
/// Represents the metadata needed to generate a platform-specific project file
/// for a service (eg compile constants, build configuration and platform etc).
/// </summary>
public class ProjectFileConfiguration
{
/// <summary>
/// The name of the platform configuration; this forms part of the project
/// filename.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The set of solution build configuration and platforms (eg Debug|Any CPU)
/// supported by the project kind.
/// </summary>
public IEnumerable<string> Configurations { get; set; }
/// <summary>
/// The .Net Framework versions, in format vX.Y, that the project will compile
/// against.
/// </summary>
public IEnumerable<string> TargetFrameworkVersions { get; set; }
/// <summary>
/// The #define constants to be set at compile time. These are used for all
/// compilation types (debug, release etc).
/// </summary>
public IEnumerable<string> CompilationConstants { get; set; }
/// <summary>
/// The name of the subfolder that the compile outputs should be placed into.
/// By convention this is the same as the Name property, but lowercase.
/// </summary>
public string BinSubFolder { get; set; }
/// <summary>
/// The name of the T4 generator file used to emit the project file. The
/// type name should be relative to the code generator's Generators
/// namespace.
/// </summary>
public string Template { get; set; }
/// <summary>
/// The set of subfolder names used to hold custom code for a platform
/// </summary>
public IEnumerable<string> PlatformCodeFolders { get; set; }
public IEnumerable<string> PlatformExcludeFolders { get; set; }
/// <summary>
/// The platform name used by NuGet (e.g. wpa81)
/// </summary>
public string NuGetTargetPlatform { get; set; }
/// <summary>
/// The set of projects that should be included in the solution test folder.
/// </summary>
public IEnumerable<string> ExtraTestProjects { get; set; }
/// <summary>
/// Returns true if the last component of the specified folder
/// path begins with '_' character, our convention for representing
/// platform-specific code.
/// </summary>
public bool IsPlatformCodeFolder(string sourceFolder)
{
return GetPlatformFolderName(sourceFolder) != null;
}
public IEnumerable<ProjectFileCreator.ProjectReference> ProjectReferences { get; set; }
public IEnumerable<string> EmbeddedResources { get; set; }
public IEnumerable<string> VisualStudioServices { get; set; }
public string NoWarn { get; set; }
public string OutputPathOverride { get; set; }
public List<ProjectFileCreator.PackageReference> PackageReferences { get; set; }
/// <summary>
/// Specify where the framework binaries are. For net35 in vs2017 project, this is needed
/// to work around https://github.com/Microsoft/msbuild/issues/1333
/// </summary>
public string FrameworkPathOverride { get; set; }
public IEnumerable<Dependency> DllReferences { get; set; }
/// <summary>
/// Returns true if the specified folder ends with one of the custom code
/// platform folder names declared for this configuration.
/// </summary>
/// <param name="sourceFolder"></param>
/// <returns></returns>
private string GetPlatformFolderName(string folder)
{
var tokens = folder.Split('\\');
string platformFolder = null;
for (int i = tokens.Length - 1; i >= 0; i--)
{
if (tokens[i].StartsWith("_"))
{
platformFolder = tokens[i];
break;
}
}
return platformFolder;
}
/// <summary>
/// Returns true if the specified path folder names conforms with the
/// platform folder names declared for this configuration.
/// </summary>
/// <param name="sourceFolder"></param>
/// <returns></returns>
public bool IsValidPlatformPathForProject(string sourceFolder)
{
var tokens = sourceFolder.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
if (PlatformCodeFolders.Any())
{
foreach(var folder in tokens)
{
if (folder.StartsWith("_"))
{
bool isValid = false;
foreach (var pcf in PlatformCodeFolders)
{
if (folder.Equals(pcf, StringComparison.OrdinalIgnoreCase))
{
isValid = true;
break;
}
}
if (!isValid)
{
return false;
}
}
}
}
return true;
}
}
}
| 164 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.XPath;
using ServiceClientGenerator.Generators.ProjectFiles;
namespace ServiceClientGenerator
{
/// <summary>
/// Class used to emit the set of per-platform project files for a service.
/// Existing project files are retained, only missing files are generated.
/// </summary>
public class ProjectFileCreator
{
/// <summary>
/// On conclusion, the set of project files that were generated for the service.
/// </summary>
public Dictionary<string, ProjectConfigurationData> CreatedProjectFiles { get; set; }
private GeneratorOptions Options;
public ProjectFileCreator(GeneratorOptions options)
{
Options = options;
}
public void ExecuteCore(string coreFilesRoot, IEnumerable<ProjectFileConfiguration> projectFileConfigurations)
{
CreatedProjectFiles = new Dictionary<string, ProjectConfigurationData>();
foreach (var projectFileConfiguration in projectFileConfigurations)
{
var projectType = projectFileConfiguration.Name;
var assemblyName = "AWSSDK.Core";
var projectFilename = string.Concat(assemblyName, ".", projectType, ".csproj");
bool newProject = false;
if (projectFileConfiguration.Template.Equals("VS2017ProjectFile", StringComparison.InvariantCultureIgnoreCase))
{
// for vs2017 projects, skip csproject generation
}
else
{
string projectGuid;
if (File.Exists(Path.Combine(coreFilesRoot, projectFilename)))
{
Console.WriteLine("...updating existing project file {0}", projectFilename);
var projectPath = Path.Combine(coreFilesRoot, projectFilename);
projectGuid = Utils.GetProjectGuid(projectPath);
}
else
{
newProject = true;
projectGuid = Utils.NewProjectGuid;
Console.WriteLine("...creating project file {0}", projectFilename);
}
var projectProperties = new Project();
projectProperties.Name = projectFileConfiguration.Name;
projectProperties.ProjectGuid = projectGuid;
projectProperties.RootNamespace = "Amazon";
projectProperties.AssemblyName = assemblyName;
projectProperties.SourceDirectories = GetCoreProjectSourceFolders(projectFileConfiguration, coreFilesRoot);
projectProperties.IndividualFileIncludes = new List<string>
{
"endpoints.json",
};
projectProperties.KeyFilePath = @"..\..\awssdk.dll.snk";
projectProperties.SupressWarnings = "419,1570,1591";
projectProperties.NugetPackagesLocation = @"..\..\packages\";
projectProperties.FxcopAnalyzerRuleSetFilePath = @"..\..\AWSDotNetSDK.ruleset";
projectProperties.FxcopAnalyzerRuleSetFilePathForBuild = @"..\..\AWSDotNetSDKForBuild.ruleset";
projectProperties.TargetFrameworks = projectFileConfiguration.TargetFrameworkVersions;
projectProperties.DefineConstants = projectFileConfiguration.CompilationConstants;
projectProperties.BinSubfolder = projectFileConfiguration.BinSubFolder;
projectProperties.PackageReferences = projectFileConfiguration.PackageReferences;
projectProperties.CustomRoslynAnalyzersDllDirectory = @"..\..\..\buildtools\CustomRoslynAnalyzers.dll";
var projectConfigurationData = new ProjectConfigurationData { ProjectGuid = projectGuid };
var projectName = Path.GetFileNameWithoutExtension(projectFilename);
if (newProject)
CreatedProjectFiles[projectName] = projectConfigurationData;
var projectReferences = new List<ProjectReference>();
projectProperties.ProjectReferences = projectReferences.OrderBy(x => x.Name).ToList();
GenerateProjectFile(projectFileConfiguration, projectConfigurationData, projectProperties, coreFilesRoot, projectFilename);
}
}
}
/// <summary>
/// Creates the platform-specific project files for the given service configuration
/// </summary>
/// <param name="serviceFilesRoot">The folder under which all of the source files for the service will exist</param>
/// <param name="serviceConfiguration"></param>
/// <param name="projectFileConfigurations"></param>
public void Execute(string serviceFilesRoot, ServiceConfiguration serviceConfiguration, IEnumerable<ProjectFileConfiguration> projectFileConfigurations)
{
CreatedProjectFiles = new Dictionary<string, ProjectConfigurationData>();
var assemblyName = "AWSSDK." + serviceConfiguration.Namespace.Split('.')[1];
foreach (var projectFileConfiguration in projectFileConfigurations)
{
var projectType = projectFileConfiguration.Name;
if (projectType.Equals("NetStandard", StringComparison.InvariantCultureIgnoreCase) && !serviceConfiguration.NetStandardSupport)
continue;
if (projectFileConfiguration.Template.Equals("VS2017ProjectFile", StringComparison.InvariantCultureIgnoreCase))
{
var projectReferenceList = new List<ProjectReference>();
foreach (var dependency in serviceConfiguration.ServiceDependencies.Keys)
{
if (string.Equals(dependency, "Core", StringComparison.InvariantCultureIgnoreCase))
continue;
projectReferenceList.Add(new ProjectReference
{
IncludePath = string.Format(@"..\..\Services\{0}\AWSSDK.{1}.{2}.csproj", dependency, dependency, projectType)
});
}
var corePath = @"..\..\Core\AWSSDK.Core.{0}.csproj";
if (serviceConfiguration.IsTestService)
{
corePath = @"..\..\..\src\Core\AWSSDK.Core.{0}.csproj";
}
projectReferenceList.Add(new ProjectReference
{
IncludePath = string.Format(corePath, projectType)
});
projectFileConfiguration.ProjectReferences = projectReferenceList;
GenerateVS2017ProjectFile(serviceFilesRoot, serviceConfiguration, projectFileConfiguration);
continue;
}
var projectFilename = string.Concat(assemblyName, ".", projectType, ".csproj");
bool newProject = false;
string projectGuid;
if (File.Exists(Path.Combine(serviceFilesRoot, projectFilename)))
{
Console.WriteLine("...updating existing project file {0}", projectFilename);
var projectPath = Path.Combine(serviceFilesRoot, projectFilename);
projectGuid = Utils.GetProjectGuid(projectPath);
}
else
{
newProject = true;
projectGuid = Utils.NewProjectGuid;
Console.WriteLine("...creating project file {0}", projectFilename);
}
var projectProperties = new Project();
projectProperties.Name = projectFileConfiguration.Name;
projectProperties.ProjectGuid = projectGuid;
projectProperties.RootNamespace = serviceConfiguration.Namespace;
projectProperties.AssemblyName = assemblyName;
projectProperties.SourceDirectories = GetProjectSourceFolders(projectFileConfiguration, serviceFilesRoot);
projectProperties.NugetPackagesLocation = @"..\..\..\packages\";
projectProperties.FxcopAnalyzerRuleSetFilePath = @"..\..\..\AWSDotNetSDK.ruleset";
projectProperties.FxcopAnalyzerRuleSetFilePathForBuild = @"..\..\..\AWSDotNetSDKForBuild.ruleset";
projectProperties.TargetFrameworks = projectFileConfiguration.TargetFrameworkVersions;
projectProperties.DefineConstants = projectFileConfiguration.CompilationConstants;
projectProperties.BinSubfolder = projectFileConfiguration.BinSubFolder;
projectProperties.PackageReferences = projectFileConfiguration.PackageReferences;
projectProperties.CustomRoslynAnalyzersDllDirectory = @"..\..\..\..\buildtools\CustomRoslynAnalyzers.dll";
var projectConfigurationData = new ProjectConfigurationData { ProjectGuid = projectGuid };
var projectName = Path.GetFileNameWithoutExtension(projectFilename);
if (newProject)
CreatedProjectFiles[projectName] = projectConfigurationData;
var projectReferences = new List<ProjectReference>();
if (serviceConfiguration.ServiceDependencies != null)
{
foreach (var dependency in serviceConfiguration.ServiceDependencies)
{
var dependencyProjectName = "AWSSDK." + dependency.Key + "." + projectType;
string dependencyProject;
if (string.Equals(dependency.Key, "Core", StringComparison.InvariantCultureIgnoreCase))
{
dependencyProject = string.Concat(@"..\..\", dependency.Key, "\\", dependencyProjectName, ".csproj");
}
else
{
dependencyProject = string.Concat(@"..\", dependency.Key, "\\", dependencyProjectName, ".csproj");
}
projectReferences.Add(new ProjectReference
{
IncludePath = dependencyProject,
ProjectGuid = Utils.GetProjectGuid(Path.Combine(serviceFilesRoot, dependencyProject)),
Name = dependencyProjectName
});
}
}
projectProperties.ProjectReferences = projectReferences.OrderBy(x => x.Name).ToList();
if (serviceConfiguration.ReferenceDependencies != null &&
serviceConfiguration.ReferenceDependencies.ContainsKey(projectFileConfiguration.Name))
{
projectProperties.ReferenceDependencies = serviceConfiguration.ReferenceDependencies[projectFileConfiguration.Name];
}
GenerateProjectFile(projectFileConfiguration, projectConfigurationData, projectProperties, serviceFilesRoot, projectFilename);
}
}
/// <summary>
/// Invokes the T4 generator to emit a platform-specific project file.
/// </summary>
/// <param name="projectFileConfiguration"></param>
/// <param name="session"></param>
/// <param name="serviceFilesRoot"></param>
/// <param name="projectFilename"></param>
private void GenerateProjectFile(ProjectFileConfiguration projectFileConfiguration,
ProjectConfigurationData projectConfiguration,
Project projectProperties,
string serviceFilesRoot,
string projectFilename)
{
var projectName = Path.GetFileNameWithoutExtension(projectFilename);
string generatedContent = null;
try
{
var projectTemplateType = Type.GetType(
"ServiceClientGenerator.Generators.ProjectFiles." +
projectFileConfiguration.Template);
dynamic generator = Activator.CreateInstance(projectTemplateType);
generator.Project = projectProperties;
generatedContent = generator.TransformText();
}
catch (Exception)
{
throw new ArgumentException("Project template name "
+ projectFileConfiguration.Template + " is not recognized");
}
GeneratorDriver.WriteFile(serviceFilesRoot, string.Empty, projectFilename, generatedContent);
projectConfiguration.ConfigurationPlatforms = projectFileConfiguration.Configurations;
}
private void GenerateVS2017ProjectFile(string serviceFilesRoot, ServiceConfiguration serviceConfiguration, ProjectFileConfiguration projectFileConfiguration)
{
var assemblyName = "AWSSDK." + serviceConfiguration.Namespace.Split('.')[1];
var projectType = projectFileConfiguration.Name;
var projectProperties = new Project();
projectProperties.AssemblyName = assemblyName;
projectProperties.ProjectReferences = projectFileConfiguration.ProjectReferences;
projectProperties.TargetFrameworks = projectFileConfiguration.TargetFrameworkVersions;
projectProperties.DefineConstants = projectFileConfiguration.CompilationConstants;
projectProperties.CompileRemoveList = projectFileConfiguration.PlatformExcludeFolders.ToList();
if (serviceConfiguration.IsTestService)
{
var toExclude = projectProperties.CompileRemoveList as List<string>;
toExclude.Add("UnitTests");
}
projectProperties.FrameworkPathOverride = projectFileConfiguration.FrameworkPathOverride;
projectProperties.ReferenceDependencies = projectFileConfiguration.DllReferences;
projectProperties.SupressWarnings = projectFileConfiguration.NoWarn;
projectProperties.SignBinaries = true;
projectProperties.PackageReferences = projectFileConfiguration.PackageReferences;
projectProperties.FxcopAnalyzerRuleSetFilePath = @"..\..\..\AWSDotNetSDK.ruleset";
projectProperties.FxcopAnalyzerRuleSetFilePathForBuild = @"..\..\..\AWSDotNetSDKForBuild.ruleset";
projectProperties.CustomRoslynAnalyzersDllDirectory = @"..\..\..\..\buildtools\CustomRoslynAnalyzers.dll";
List<Dependency> dependencies;
List<PackageReference> references = new List<PackageReference>();
if ( serviceConfiguration.NugetDependencies != null &&
serviceConfiguration.NugetDependencies.TryGetValue(projectFileConfiguration.Name, out dependencies))
{
foreach(var dependency in dependencies)
{
references.Add(new PackageReference
{
Include = dependency.Name,
Version = dependency.Version,
});
}
projectProperties.PackageReferences = references;
}
var projectJsonTemplate = new VS2017ProjectFile();
projectJsonTemplate.Project = projectProperties;
projectJsonTemplate.ServiceConfiguration = serviceConfiguration;
var content = projectJsonTemplate.TransformText();
GeneratorDriver.WriteFile(serviceFilesRoot, string.Empty, string.Format("{0}.{1}.csproj", assemblyName, projectType), content);
}
/// <summary>
/// Returns the collection of subfolders containing source code that need to be
/// included in the project file. This is comprised the standard platform folders
/// under Generated, plus any custom folders we find that are not otherwise handled
/// (eg Properties).
/// </summary>
/// <param name="projectFileConfiguration">
/// The .Net project type we are generating. This governs the platform-specific
/// subfolders that get included in the project.
/// </param>
/// <param name="serviceRootFolder">The root output folder for the service code</param>
/// <returns></returns>
private IList<string> GetCoreProjectSourceFolders(ProjectFileConfiguration projectFileConfiguration, string coreRootFolder)
{
var exclusionList = new List<string>
{
"Properties",
"bin",
"obj",
".vs"
};
// Start with the standard folders for core
var sourceCodeFolders = new List<string>
{
"."
};
var childDirectories = Directory.GetDirectories(coreRootFolder, "*", SearchOption.AllDirectories);
foreach (var childDirectory in childDirectories)
{
var folder = childDirectory.Substring(coreRootFolder.Length).TrimStart('\\');
if (exclusionList.Any(e => folder.Equals(e, StringComparison.InvariantCulture) ||
folder.StartsWith(e + "\\", StringComparison.InvariantCulture)))
continue;
if (projectFileConfiguration.IsPlatformCodeFolder(folder))
{
if (projectFileConfiguration.IsValidPlatformPathForProject(folder))
sourceCodeFolders.Add(folder);
}
else
{
sourceCodeFolders.Add(folder);
}
}
//var platformSubFolders = projectFileConfiguration.PlatformCodeFolders;
//sourceCodeFolders.AddRange(platformSubFolders.Select(folder => Path.Combine(@"Generated", folder)));
//// Augment the returned folders with any custom subfolders already in existence. If the custom folder
//// ends with a recognised platform, only add it to the set if it matches the platform being generated
////if (Directory.Exists(serviceRootFolder))
//{
// var subFolders = Directory.GetDirectories(coreRootFolder, "*", SearchOption.AllDirectories);
// subFolders = subFolders.Except(exclusionList).ToArray();
// if (subFolders.Any())
// {
// foreach (var folder in subFolders)
// {
// var serviceRelativeFolder = folder.Substring(coreRootFolder.Length);
// if (!serviceRelativeFolder.StartsWith(@"\Custom", StringComparison.OrdinalIgnoreCase))
// continue;
// if (projectFileConfiguration.IsPlatformCodeFolder(serviceRelativeFolder))
// {
// if (projectFileConfiguration.IsValidPlatformCodeFolderForProject(serviceRelativeFolder))
// sourceCodeFolders.Add(serviceRelativeFolder.TrimStart('\\'));
// }
// else
// sourceCodeFolders.Add(serviceRelativeFolder.TrimStart('\\'));
// }
// }
//}
var foldersThatExist = new List<string>();
foreach (var folder in sourceCodeFolders)
{
if (Directory.Exists(Path.Combine(coreRootFolder, folder)))
foldersThatExist.Add(folder);
}
// sort so we get a predictable layout
foldersThatExist.Sort(StringComparer.OrdinalIgnoreCase);
return foldersThatExist;
}
/// <summary>
/// Returns the collection of subfolders containing source code that need to be
/// included in the project file. This is comprised the standard platform folders
/// under Generated, plus any custom folders we find that are not otherwise handled
/// (eg Properties).
/// </summary>
/// <param name="projectFileConfiguration">
/// The .Net project type we are generating. This governs the platform-specific
/// subfolders that get included in the project.
/// </param>
/// <param name="serviceRootFolder">The root output folder for the service code</param>
/// <returns></returns>
private IList<string> GetProjectSourceFolders(ProjectFileConfiguration projectFileConfiguration, string serviceRootFolder)
{
// Start with the standard generated code folders for the platform
var sourceCodeFolders = new List<string>
{
"Generated",
@"Generated\Internal",
@"Generated\Model",
@"Generated\Model\Internal",
@"Generated\Model\Internal\MarshallTransformations"
};
var platformSubFolders = projectFileConfiguration.PlatformCodeFolders;
sourceCodeFolders.AddRange(platformSubFolders.Select(folder => Path.Combine(@"Generated", folder)));
// Augment the returned folders with any custom subfolders already in existence. If the custom folder
// ends with a recognised platform, only add it to the set if it matches the platform being generated
if (Directory.Exists(serviceRootFolder))
{
var subFolders = Directory.GetDirectories(serviceRootFolder, "*", SearchOption.AllDirectories);
if (subFolders.Any())
{
foreach (var folder in subFolders)
{
var serviceRelativeFolder = folder.Substring(serviceRootFolder.Length);
if (!serviceRelativeFolder.StartsWith(@"\Custom", StringComparison.OrdinalIgnoreCase))
continue;
if (projectFileConfiguration.IsPlatformCodeFolder(serviceRelativeFolder))
{
if (projectFileConfiguration.IsValidPlatformPathForProject(serviceRelativeFolder))
sourceCodeFolders.Add(serviceRelativeFolder.TrimStart('\\'));
}
else
sourceCodeFolders.Add(serviceRelativeFolder.TrimStart('\\'));
}
}
}
var foldersThatExist = new List<string>();
foreach (var folder in sourceCodeFolders)
{
if (Directory.Exists(Path.Combine(serviceRootFolder, folder)))
foldersThatExist.Add(folder);
}
// sort so we get a predictable layout
foldersThatExist.Sort(StringComparer.OrdinalIgnoreCase);
return foldersThatExist;
}
public class ProjectReference : IComparable<ProjectReference>
{
public string IncludePath { get; set; }
public string ProjectGuid { get; set; }
public string Name { get; set; }
int IComparable<ProjectReference>.CompareTo(ProjectReference that)
{
return string.Compare(this.Name, that.Name);
}
}
public class ProjectConfigurationData
{
public string ProjectGuid { get; set; }
public IEnumerable<string> ConfigurationPlatforms { get; set; }
}
public class PackageReference
{
public string Include { get; set; }
public string Version { get; set; }
public string PrivateAssets { get; set; } = "none";
public string IncludeAssets { get; set; }
public bool IsAnalyzer { get; set; }
public bool HasPrivateAssets => PrivateAssets != "" && PrivateAssets != "none";
public static PackageReference ParseJson(Json.LitJson.JsonData data)
{
return new PackageReference
{
Include = data.SafeGetString("include"),
Version = data.SafeGetString("version"),
PrivateAssets = data.SafeGetString("privateAssets"),
IncludeAssets = data.SafeGetString("includeAssets"),
IsAnalyzer = data.SafeGet("analyzer") != null ? (bool) data.SafeGet("analyzer") : false
};
}
}
}
}
| 505 |
aws-sdk-net | aws | C# | using ServiceClientGenerator.Endpoints;
using ServiceClientGenerator.Endpoints.Tests;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ServiceClientGenerator
{
/// <summary>
/// Represents the information for generating the code for a service
/// </summary>
public class ServiceConfiguration
{
private const string amazonDotPrefix = "Amazon.";
private string _modelPath;
private string _paginatorsPath;
/// <summary>
/// The name of the model, taken from the "model" entry in the service models
/// manifest.
/// </summary>
public string ModelName { get; set; }
/// <summary>
/// Path to the model that is represented by these attributes
/// </summary>
public string ModelPath
{
get { return this._modelPath; }
set
{
this._serviceModel = null;
this._modelPath = value;
}
}
/// <summary>
/// Path to the paginators for a service
/// </summary>
public string PaginatorsPath
{
get { return this._paginatorsPath; }
set
{
this._paginatorsPath = value;
}
}
ServiceModel _serviceModel;
/// <summary>
/// The ServiceModel object, used to parse information inside of the model*.normal.json file as well as any customizations
/// </summary>
public ServiceModel ServiceModel
{
get
{
if (this._serviceModel == null)
{
this._serviceModel = this._paginatorsPath != null ? new ServiceModel(this.ModelPath, this.CustomizationsPath, this._paginatorsPath) :
new ServiceModel(this.ModelPath, this.CustomizationsPath);
}
return this._serviceModel;
}
}
string _customizationsPath;
/// <summary>
/// Path to the file used for customizations
/// </summary>
public string CustomizationsPath
{
get { return this._customizationsPath; }
set
{
// Cause the service model to reload with customizations
this._serviceModel = null;
this._customizationsPath = value;
}
}
private static string SanitizeStringForClassName(string name)
{
if (null == name)
return null;
string className = name;
className = className.Replace("AWS", "");
className = className.Replace("Amazon", "");
// concatenate all the words by removing whitespace.
className = System.Text.RegularExpressions.Regex.Replace(className, @"[^a-zA-Z0-9]", "");
return className.ToUpperFirstCharacter();
}
private string _className;
/// <summary>
/// The base name used in the client and the top level request class for a service
/// </summary>
public string ClassName
{
get
{
if (!string.IsNullOrEmpty(_className))
{
return _className;
}
if (ClassNameOverride != null)
{
_className = ClassNameOverride;
}
else if (!string.IsNullOrEmpty(this.LegacyServiceId))
{
//Use legacy service class name calculation
if (this.ServiceModel.ServiceAbbreviation != null)
{
_className = SanitizeStringForClassName(_serviceModel.ServiceAbbreviation);
}
else if (this.ServiceModel.ServiceFullName != null)
{
_className = SanitizeStringForClassName(_serviceModel.ServiceFullName);
}
else
{
throw new InvalidDataException("Generator was not able to determine the ClassName for a service.");
}
}
else
{
//All new services will not have a legacy-service-id metadata property value which indicates that they
//must use the ServiceId for the class name.
if (string.IsNullOrEmpty(this.ServiceId))
{
throw new InvalidDataException(
"Generator was not able to determine the ClassName for a service.");
}
_className = SanitizeStringForClassName(this.ServiceId);
}
return _className;
}
}
/// <summary>
/// Classname can be overriden by setting "base-name" in metadata.json
/// </summary>
public string ClassNameOverride { get; set; }
string _namespace;
/// <summary>
/// The namespace of the service, if not specified it is Amazon.ClassName
/// </summary>
public string Namespace
{
get
{
if (string.IsNullOrEmpty(this._namespace))
return amazonDotPrefix + this.ClassName;
return this._namespace;
}
set { this._namespace = value; }
}
// Base name in the manifest is not a reliable source of info, as if append-service
// is set 'Service' gets appended and in the case of IAM then sends us to the wrong folder.
// Instead we'll use the namespace and rip off any Amazon. prefix. This also helps us
// handle versioned namespaces too.
public string ServiceFolderName
{
get
{
var serviceNameRoot = this.Namespace.StartsWith("Amazon.", StringComparison.Ordinal)
? this.Namespace.Substring(7)
: this.Namespace;
return serviceNameRoot;
}
}
public string TestCategory
{
get
{
return ServiceFolderName;
}
}
public string AssemblyTitle
{
get
{
return this.Namespace.Replace(amazonDotPrefix, "AWSSDK.");
}
}
public string AssemblyDescription(
string versionIdentifier = "",
bool includePreamble = true,
bool includeBody = true,
bool includePostamble = true)
{
if (!string.IsNullOrEmpty(versionIdentifier) && !versionIdentifier.StartsWith("("))
versionIdentifier = $"({versionIdentifier})";
var preamble =
includePreamble
? $"The Amazon Web Services SDK for .NET {versionIdentifier} - "
: "";
string body = "";
if (includeBody)
{
body =
!string.IsNullOrEmpty(ServiceModel.ServiceFullName)
? $"{ServiceModel.ServiceFullName}. "
: $"{ServiceId}. ";
}
var postamble =
includePostamble
? $"{ (!string.IsNullOrEmpty(Synopsis) ? Synopsis : ServiceId) }"
: "";
return $"{preamble}{body}{postamble}";
}
public string BaseException
{
get
{
var baseException = string.Format("Amazon{0}Exception",
this.IsChildConfig ?
this.ParentConfig.ClassName : this.ClassName);
return baseException;
}
}
/// <summary>
/// An option suffix added on to the end of the Nuget package title.
/// </summary>
public string NugetPackageTitleSuffix { get; set; }
// Base name in the manifest is not a reliable source of info, as if append-service
// is set 'Service' gets appended and in the case of IAM then sends us to the wrong folder.
// Instead we'll use the namespace and rip off any Amazon. prefix. This also helps us
// handle versioned namespaces too.
public string ServiceNameRoot
{
get
{
var serviceNameRoot = this.Namespace.StartsWith(amazonDotPrefix, StringComparison.Ordinal)
? this.Namespace.Substring(amazonDotPrefix.Length)
: this.Namespace;
return serviceNameRoot;
}
}
public bool InPreview {get; set;}
public bool HasOverrideNamespace { get { return !string.IsNullOrEmpty(this._namespace); } }
public string RegionLookupName { get { return this.ServiceModel.EndpointPrefix; } }
public string LegacyServiceId { get; set; }
public string ServiceId {
get {
if (!string.IsNullOrEmpty(ServiceModel.ServiceId))
return ServiceModel.ServiceId;
//ServiceID is required, but there are a few services that were created before that requirement
if(!string.IsNullOrEmpty(LegacyServiceId))
{
return LegacyServiceId;
}
//If it's a newer service, then the ServiceId field is required
throw new Exception($"Invalid Service Model: Missing required {ServiceModel.ServiceIdKey}");
}
}
public string AuthenticationServiceName { get { return this.ServiceModel.SigningName != null ? this.ServiceModel.SigningName : this.ServiceModel.EndpointPrefix; } }
public int? OverrideMaxRetries { get; set; }
public string DefaultRegion { get; set; }
public bool GenerateConstructors { get; set; }
public string LockedApiVersion { get; set; }
public string Synopsis { get; set; }
public Dictionary<string, string> ServiceDependencies { get; set; }
public string LicenseUrl { get; set; }
public bool RequireLicenseAcceptance { get; set; }
public Dictionary<string, List<Dependency>> ReferenceDependencies { get; set; }
public Dictionary<string, List<Dependency>> NugetDependencies { get; set; }
public List<string> Tags { get; set; }
public bool NetStandardSupport { get; set; }
public bool GeneratedEventStreamException { get; set; }
public string ServiceVersion
{
get
{
if (!string.IsNullOrEmpty(this.ServiceAssemblyVersionOverride))
{
return ServiceAssemblyVersionOverride;
}
return Utils.GetVersion(ServiceFileVersion);
}
}
public string ServiceFileVersion { get; set; }
/// <summary>
/// If specified this overrides the AssemblyVersion for the service package in AssemblyInfo.cs.
/// Assembly version defaults to x.y of ServiceFileVersion if this is not specified.
/// </summary>
public string ServiceAssemblyVersionOverride { get; set; }
public bool SkipV1 { get; set; }
public bool IsChildConfig
{
get
{
return this.ParentConfig != null;
}
}
private ServiceConfiguration _parentConfig;
public ServiceConfiguration ParentConfig
{
get
{
return _parentConfig;
}
set
{
_parentConfig = value;
ServiceModel.ParentModel = value.ServiceModel;
}
}
public string ServiceDirectoryName
{
get
{
var directory = Path.GetDirectoryName(ModelPath);
var directoryName = Path.GetFileName(directory);
return directoryName;
}
}
public string DisplayModelPath
{
get
{
return Path.GetFileName(ModelPath);
}
}
public bool IsTestService { get; set; }
public RuleSet EndpointsRuleSet { get; set; }
public EndpointTests EndpointTests { get; set; }
public override string ToString()
{
return string.Format("{0} - {1}", this.Namespace, this.ModelPath);
}
}
public class Dependency
{
public string Name { get; set; }
public string Version { get; set; }
public string HintPath { get; set; }
public static Dependency ParseJson(Json.LitJson.JsonData data)
{
return new Dependency
{
Name = data.SafeGetString("name"),
Version = data.SafeGetString("version"),
HintPath = data.SafeGetString("hintPath"),
};
}
}
}
| 393 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Json.LitJson;
using System.Globalization;
using ServiceClientGenerator.Endpoints;
namespace ServiceClientGenerator
{
/// <summary>
/// The service model represents the information of a service found through the manifest, model, and customization file.
/// It is used to get any information necessary to generate the clients, operations, and structures of a service.
/// </summary>
public class ServiceModel
{
// metadata properties
public const string MetadataKey = "metadata";
public const string ApiVersionKey = "apiVersion";
public const string EndpointPrefixKey = "endpointPrefix";
public const string JsonVersionKey = "jsonVersion";
public const string ProtocolKey = "protocol";
public const string ProtocolSettingsKey = "protocolSettings";
public const string ProtocolSettingsH2Key = "h2";
public const string ServiceFullNameKey = "serviceFullName";
public const string SignatureVersionKey = "signatureVersion";
public const string TargetPrefixKey = "targetPrefix";
public const string UidKey = "uid";
public const string ServiceAbbreviationKey = "serviceAbbreviation";
public const string SigningNameKey = "signingName";
public const string ServiceIdKey = "serviceId";
public const string AWSQueryCompatibleKey = "awsQueryCompatible";
// operations
public const string OperationsKey = "operations";
public const string HttpKey = "http";
public const string MethodKey = "method";
public const string RequestUriKey = "requestUri";
public const string InputKey = "input";
public const string OutputKey = "output";
public const string ErrorsKey = "errors";
public const string ResultWrapperKey = "resultWrapper";
public const string AuthTypeKey = "authtype";
public const string EndpointKey = "endpoint";
public const string HostPrefixKey = "hostPrefix";
public const string EndpointOperationKey = "endpointoperation";
public const string EndpointDiscoveryKey = "endpointdiscovery";
public const string RequiredKey = "required";
public const string HttpChecksumRequiredKey = "httpChecksumRequired";
public const string HttpChecksumKey = "httpChecksum";
public const string RequestChecksumRequiredKey = "requestChecksumRequired";
public const string RequestAlgorithmMemberKey = "requestAlgorithmMember";
public const string RequestValidationModeMemberKey = "requestValidationModeMember";
public const string ResponseAlgorithmsKey = "responseAlgorithms";
// shapes
public const string ShapesKey = "shapes";
public const string ShapeKey = "shape";
public const string IdempotencyTokenKey = "idempotencyToken";
public const string DeprecatedKey = "deprecated";
public const string DeprecatedMessageKey = "deprecatedMessage";
public const string WrapperKey = "wrapper";
public const string LocationNameKey = "locationName";
public const string QueryNameKey = "queryName";
public const string XmlNamespaceUriKey = "uri";
public const string XmlNamespaceKey = "xmlNamespace";
public const string EndpointDiscoveryIdKey = "endpointdiscoveryid";
// pagination
public const string PaginationKey = "pagination";
public const string ResultKeyKey = "result_key";
public const string InputTokenKey = "input_token";
public const string OutputTokenKey = "output_token";
public const string LimitKeyKey = "limit_key";
public const string MoreResultsKey = "more_results";
// documentation
public const string DocumentationKey = "documentation";
// client context params
public const string ClientContextParams = "clientContextParams";
/// <summary>
/// This model contains information about customizations needed during the generation process
/// </summary>
readonly CustomizationsModel _customizationModel;
/// <summary>
/// The information found as a property at the top of the model structure which contains information on how to generate the service
/// </summary>
JsonData _metadata;
/// <summary>
/// This is the entire model document for the service processed as a json object
/// </summary>
internal JsonData DocumentRoot;
/// <summary>
/// This is the paginators for the service processed as a json object
/// </summary>
internal JsonData PaginatorsRoot;
/// <summary>
/// Used for unit testing, creates a service model from a TextReader so that the generation can be checked
/// </summary>
/// <param name="serviceModelReader">The reader to get the model information from</param>
/// <param name="customizationReader">The reader to get any customizations for the service from</param>
public ServiceModel(TextReader serviceModelReader, TextReader customizationReader)
{
InitializeServiceModel(serviceModelReader);
this._customizationModel = new CustomizationsModel(customizationReader);
}
/// <summary>
/// Used by the generator to create a model for the service being generated
/// </summary>
/// <param name="serviceModelPath">Path to the file containing the model of the service</param>
/// <param name="customizationModelPath">Path to the customizations file for the service</param>
public ServiceModel(string serviceModelPath, string customizationModelPath)
{
using (var reader = new StreamReader(serviceModelPath))
InitializeServiceModel(reader);
this._customizationModel = new CustomizationsModel(customizationModelPath);
}
/// <summary>
/// Used by the generator to create a model for the service being generated
/// </summary>
/// <param name="serviceModelPath">Path to the file containing the model of the service</param>
/// <param name="customizationModelPath">Path to the customizations file for the service</param>
/// /// <param name="servicePaginatorsPath">Path to the customizations file for the service</param>
public ServiceModel(string serviceModelPath, string customizationModelPath, string servicePaginatorsPath)
{
using (var reader = new StreamReader(serviceModelPath))
{
InitializeServiceModel(reader);
}
if (File.Exists(servicePaginatorsPath))
{
using (var reader = new StreamReader(servicePaginatorsPath))
InitializePaginators(reader);
}
this._customizationModel = new CustomizationsModel(customizationModelPath);
}
/// <summary>
/// Sets the base json info no matter how the model was constructed
/// </summary>
/// <param name="reader">The reader to pull the model json from</param>
private void InitializeServiceModel(TextReader reader)
{
this.DocumentRoot = JsonMapper.ToObject(reader);
this._metadata = this.DocumentRoot[MetadataKey];
}
/// <summary>
/// Sets the base json info no matter how the model was constructed
/// </summary>
/// <param name="reader">The reader to pull the model json from</param>
private void InitializePaginators(TextReader reader)
{
this.PaginatorsRoot = JsonMapper.ToObject(reader);
}
/// <summary>
/// Indicates that this service was converted from query to json 1.0
/// and may be sending AWSQuery compatible error code data in header.
/// </summary>
public bool IsAwsQueryCompatible
{
get
{
return this._metadata.PropertyNames.Contains(AWSQueryCompatibleKey);
}
}
/// <summary>
/// Whether or not this service has paginators available
/// for any operation
/// </summary>
public bool HasPaginators { get; private set; } = false;
/// <summary>
/// The customization model for the service
/// </summary>
public CustomizationsModel Customizations
{
get { return this._customizationModel; }
}
public ServiceModel ParentModel { get; set; }
/// <summary>
/// Provides the targetPrefix if it is set in the metadata.
/// Target prefix is defined so that the target can be set in the header of the request
/// </summary>
public string TargetPrefix
{
get { return this._metadata[TargetPrefixKey] == null ? "" : this._metadata[TargetPrefixKey].ToString(); }
}
/// <summary>
/// The json version as defined in the metadata, used to determine the content type header
/// </summary>
public string JsonVersion
{
get
{
var version = this._metadata[JsonVersionKey] == null ? "" : this._metadata[JsonVersionKey].ToString();
if (version == "1")
version = "1.0";
return version;
}
}
/// <summary>
/// Unique Service ID. For models without this entry, this may return null;
/// </summary>
public string ServiceUid
{
get
{
return this._metadata[UidKey] == null ? null : this._metadata[UidKey].ToString();
}
}
/// <summary>
/// Used to determine the signer version to use, important in generating signatures for the client
/// </summary>
public string SignatureVersion
{
get
{
var version = this._metadata[SignatureVersionKey] == null ? "" : this._metadata[SignatureVersionKey].ToString();
return version;
}
}
/// <summary>
/// Determines what service type the model uses, found in the metadata
/// </summary>
public ServiceType Type
{
get
{
var serviceType = Protocol;
if (serviceType.Equals("rest-xml", StringComparison.InvariantCulture))
{
serviceType = "rest_xml";
}
else if (serviceType.Equals("rest-json", StringComparison.InvariantCulture))
{
serviceType = "rest_json";
}
else if (serviceType.Equals("ec2", StringComparison.InvariantCulture))
{
serviceType = "query";
}
ServiceType value;
if (!Enum.TryParse<ServiceType>(serviceType, true, out value))
{
throw new Exception("Unknown service type: " + serviceType);
}
return value;
}
}
public string Protocol
{
get { return this._metadata[ProtocolKey] == null ? "" : this._metadata[ProtocolKey].ToString(); }
}
public JsonData ProtocolSettings => _metadata[ProtocolSettingsKey];
public H2SupportDegree H2Support => Enum.TryParse<H2SupportDegree>(ProtocolSettings?[ProtocolSettingsH2Key]?.ToString(), true, out var specifiedH2Degree)
? specifiedH2Degree
: H2SupportDegree.None;
public bool IsEC2Protocol
{
get { return Protocol.Equals("ec2", StringComparison.OrdinalIgnoreCase); }
}
/// <summary>
/// The information about the service found as the value for the documentation property of the json model
/// </summary>
public string Documentation
{
get
{
var docNode = this.DocumentRoot[DocumentationKey];
if (docNode == null)
return string.Empty;
return docNode.ToString();
}
}
/// <summary>
/// Returns the abbreviation name of a service
/// </summary>
public string ServiceAbbreviation
{
get { return Utils.JsonDataToString(this._metadata[ServiceAbbreviationKey]); }
}
/// <summary>
/// Returns the public name of a service
/// </summary>
public string ServiceFullName
{
get { return Utils.JsonDataToString(this._metadata[ServiceFullNameKey]); }
}
/// <summary>
/// Returns the endpoint prefix of a service
/// </summary>
public string EndpointPrefix
{
get { return Utils.JsonDataToString(this._metadata[EndpointPrefixKey]); }
}
/// <summary>
/// Returns the signing name of a service
/// </summary>
public string SigningName
{
get { return Utils.JsonDataToString(this._metadata[SigningNameKey]); }
}
/// <summary>
/// Returns the Service Id of a service
/// </summary>
public string ServiceId
{
get
{
return Utils.JsonDataToString(this._metadata[ServiceIdKey]);
}
}
/// <summary>
/// Gets the operation information based on the name of the operation
/// </summary>
/// <param name="name">The name of the operation that information is needed for</param>
/// <returns>An Operation object that contains details about the operation requested</returns>
public Operation FindOperation(string name)
{
return this.Operations.FirstOrDefault(x => x.Name == name);
}
/// <summary>
/// Gets the operation marked endpointoperation if one exists
/// </summary>
/// <returns>An Operation object that contains details about the operation requested</returns>
public Operation FindEndpointOperation()
{
return this.Operations.FirstOrDefault(x => x.IsEndpointOperation);
}
/// <summary>
/// The operations available through the service api found in the model.
/// These operation objects contain the necessary information to construct the required operation structures for the API
/// </summary>
public List<Operation> Operations
{
get
{
var list = new List<Operation>();
foreach (KeyValuePair<string, JsonData> kvp in DocumentRoot[OperationsKey])
{
Operation operation;
if (this.PaginatorsRoot != null && this.PaginatorsRoot[PaginationKey][kvp.Key] != null)
{
operation = new Operation(this, kvp.Key,
kvp.Value, this.PaginatorsRoot[PaginationKey][kvp.Key]);
if (operation.Paginators != null && !operation.UnsupportedPaginatorConfig)
{
this.HasPaginators = true;
}
}
else
{
operation = new Operation(this, kvp.Key, kvp.Value);
}
if (operation.IsExcluded)
{
ExcludedOperations.Add(operation.Name);
}
// Event Streams are not supported (yet)
else if (H2Support == H2SupportDegree.EventStream && operation.IsEventStreamOutput)
{
ExcludedOperations.Add(operation.Name);
}
else
{
list.Add(operation);
}
}
return list.OrderBy(x => x.Name).ToList();
}
}
public IDictionary<string, string> OperationsNameMapping
{
get
{
var mapping = new Dictionary<string, string>();
foreach (KeyValuePair<string, JsonData> kvp in DocumentRoot[OperationsKey])
{
var operation = new Operation(this, kvp.Key, kvp.Value);
if (operation.ShapeName != operation.Name)
{
mapping.Add(operation.Name, operation.ShapeName);
}
}
return mapping;
}
}
public IEnumerable<ExceptionShape> Exceptions
{
get
{
var exceptions = new List<ExceptionShape>();
foreach (var operation in this.Operations)
{
foreach (var exception in operation.Exceptions)
{
if (exceptions.All(e => !e.Name.Equals(exception.Name)))
exceptions.Add(exception);
}
}
return exceptions;
}
}
readonly HashSet<string> _excludedOperations = new HashSet<string>();
public HashSet<string> ExcludedOperations
{
get { return _excludedOperations; }
}
/// <summary>
/// Returns all the shapes that are of type structure.
/// </summary>
public IEnumerable<Shape> Structures
{
get
{
var list = new List<Shape>();
foreach (KeyValuePair<string, JsonData> kvp in DocumentRoot[ShapesKey])
{
var type = kvp.Value["type"];
if (type != null && type.ToString() == "structure")
list.Add(Shape.CreateShape(this, kvp.Key, kvp.Value));
}
return list.OrderBy(x => x.Name).ToList();
}
}
/// <summary>
/// Returns all the shapes.
/// </summary>
public IEnumerable<Shape> Shapes
{
get
{
var list = new List<Shape>();
foreach (KeyValuePair<string, JsonData> kvp in DocumentRoot[ShapesKey])
{
list.Add(Shape.CreateShape(this, kvp.Key, kvp.Value));
}
return list.OrderBy(x => x.Name).ToList();
}
}
/// <summary>
/// Returns list of enums defined in the service model.
/// </summary>
/// <param name="includeParentEnums">Includes enums from current service model, which are also
/// defined in the parent model.</param>
/// <returns></returns>
public IEnumerable<Enumeration> Enumerations(bool includeParentEnums)
{
var list = new List<Enumeration>();
foreach (KeyValuePair<string, JsonData> kvp in DocumentRoot[ShapesKey])
{
var type = kvp.Value["type"];
if (type != null && type.ToString() == "string" && kvp.Value["enum"] != null)
list.Add(new Enumeration(this, kvp.Key, kvp.Value));
}
list = list.OrderBy(x => x.Name).ToList();
if (includeParentEnums || this.ParentModel == null)
{
return list;
}
else
{
// Remove enums already defined in the parent model
return list.Where(e => ParentModel.Enumerations(true).All(en => !e.ModelName.Equals(en.ModelName)));
}
}
/// <summary>
/// Search the model for shape.
/// </summary>
/// <param name="name">The name of the shape to search for</param>
/// <returns>A shape object with information about the shape that was searched for</returns>
public Shape FindShape(string name)
{
var shapes = this.DocumentRoot[ShapesKey];
var shape = shapes[name];
return Shape.CreateShape(this, name, shape);
}
/// <summary>
/// Gets list of client context parameters,
/// used to extend client config with new properties and drive endpoint resolution
/// </summary>
public List<ClientContextParameter> ClientContextParameters
{
get
{
var result = new List<ClientContextParameter>();
var parameters = DocumentRoot.SafeGet(ClientContextParams);
if (parameters == null)
{
return result;
}
foreach(var param in parameters.GetMap())
{
// Skip S3/S3 Control-specific parameters as we already
// have custom definitions for them in client config.
if ((ServiceId == "S3" || ServiceId == "S3 Control") && (
param.Key == "UseArnRegion" ||
param.Key == "DisableMultiRegionAccessPoints" ||
param.Key == "Accelerate" ||
param.Key == "ForcePathStyle"))
{
continue;
}
result.Add(new ClientContextParameter
{
name = param.Key,
documentation = param.Value.SafeGetString("documentation"),
type = param.Value.SafeGetString("type")
});
}
return result;
}
}
/// <summary>
/// A value retrieved from the json model that is included in service requests
/// </summary>
public string APIVersion
{
get { return this.DocumentRoot[MetadataKey][ApiVersionKey].ToString(); }
}
/// <summary>
/// The service model represented as a string
/// </summary>
/// <returns>Format: targetPrefix - APIVersion</returns>
public override string ToString()
{
return string.Format("{0} - {1}", TargetPrefix, APIVersion);
}
}
}
| 585 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
/// <summary>
/// Shapes are used to model structures and member types. If they are a structure the shape
/// defines what members it has and what shape those members are. It also defines which of those
/// members are required. If it is not a structure then it is used to specify the type of the member and its properties.
/// </summary>
public class Shape : BaseModel
{
public const string ValueKey = "value";
public const string KeyKey = "key";
public const string MemberKey = "member";
public const string MembersKey = "members";
public const string PayloadKey = "payload";
public const string ExceptionKey = "exception";
public const string RetryableKey = "retryable";
public const string ThrottlingKey = "throttling";
public const string RequiresLengthKey = "requiresLength";
public const string StreamingKey = "streaming";
public const string TypeKey = "type";
public const string FlattenedKey = "flattened";
public const string RequiredKey = "required";
public const string MinKey = "min";
public const string MaxKey = "max";
public const string SensitiveKey = "sensitive";
public const string PatternKey = "pattern";
public const string ErrorKey = "error";
public const string ErrorCodeKey = "code";
public const string EventStreamKey = "eventstream";
public const string DeprecatedKey = "deprecated";
public const string DeprecatedMessageKey = "deprecatedMessage";
public const string TimestampFormatKey = "timestampFormat";
public const string DocumentKey = "document";
public const string EventKey = "event";
public static readonly HashSet<string> NullableTypes = new HashSet<string> {
"bool",
"boolean",
"decimal",
"double",
"DateTime",
"float",
"timestamp",
"int",
"integer",
"long",
};
public static readonly Dictionary<string, string> PrimitiveTypeNames = new Dictionary<string, string>
{
{ "blob", "MemoryStream" },
{ "boolean", "Bool" },
{ "decimal", "Decimal" },
{ "double", "Double" },
{ "float", "Float" },
{ "integer", "Int" },
{ "long", "Long" },
{ "string", "String" },
{ "timestamp", "DateTime"},
};
private readonly string _name;
public static Shape CreateShape(ServiceModel model, string name, JsonData data)
{
var exception = data[ExceptionKey];
if (exception != null && exception.IsBoolean)
{
return new ExceptionShape(model, name, data);
}
return new Shape(model, name, data);
}
/// <summary>
/// Creates a shape with a reference to the model it's a part of, its name, and the json data of the shape pulled from the model.
/// Shapes are used to model structures and member types. If they are a structure the shape
/// defines what members it has and what shape those members are. It also defines which of those
/// members are required. If it is not a structure then it is used to specify the type of the member and its properties.
/// </summary>
/// <param name="model">The model that contains the shape</param>
/// <param name="name">The name of the shape</param>
/// <param name="data">The json object of the shape, pulled form the model json</param>
protected Shape(ServiceModel model, string name, JsonData data)
: base(model, data)
{
this._name = name.ToUpperFirstCharacter();
var nameOverride = this.model.Customizations.GetOverrideShapeName(this._name);
if (nameOverride != null)
this._name = nameOverride;
}
/// <summary>
/// The name of the shape found in the model json
/// </summary>
public virtual string Name
{
get { return this._name; }
}
/// <summary>
/// Checks if an object is a Shape and has the same name as this shape
/// </summary>
/// <param name="obj">The object to compare to</param>
/// <returns>If the object is a shape and has the same name of this shape</returns>
public override bool Equals(object obj)
{
if (!(obj is Shape))
return false;
return string.Equals(this.Name, ((Shape)obj).Name);
}
/// <summary>
/// The hashcode of the shape is the hashcode of the name
/// </summary>
/// <returns>The hashcode of the shape retrieved from the name</returns>
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
/// <summary>
/// String representation of the shape found by the name
/// </summary>
/// <returns>The name of the shape as a string</returns>
public override string ToString()
{
return this.Name;
}
/// <summary>
/// If the structure is a map, returns the Value shape. Otherwise returns null.
/// </summary>
public Shape ValueShape
{
get
{
var valueNode = this.data[ValueKey];
if (valueNode == null)
return null;
var extendsNode = valueNode[ServiceModel.ShapeKey];
if (extendsNode == null)
return null;
return this.model.FindShape(extendsNode.ToString());
}
}
/// <summary>
/// The marshall name used for the value part of a dictionary.
/// </summary>
public string ValueMarshallName
{
get
{
var keyNode = this.data[ValueKey];
if (keyNode == null || keyNode[ServiceModel.LocationNameKey] == null)
return "value";
return keyNode[ServiceModel.LocationNameKey].ToString();
}
}
/// <summary>
/// If the structure is a map, returns the Key shape. Otherwise returns null.
/// </summary>
public Shape KeyShape
{
get
{
var valueNode = this.data[KeyKey];
if (valueNode == null)
return null;
var extendsNode = valueNode[ServiceModel.ShapeKey];
if (extendsNode == null)
return null;
return this.model.FindShape(extendsNode.ToString());
}
}
/// <summary>
/// The marshall name used for the key part of a dictionary.
/// </summary>
public string KeyMarshallName
{
get
{
var keyNode = this.data[KeyKey];
if (keyNode == null || keyNode[ServiceModel.LocationNameKey] == null)
return "key";
return keyNode[ServiceModel.LocationNameKey].ToString();
}
}
/// <summary>
/// If the structure is a list it returns the shape contained into the list otherwise null.
/// This returns the list shape recognizing any shape substitution in effect via customizations.
/// </summary>
public Shape ListShape
{
get
{
var shapeName = LookupListShapeName(true);
return !string.IsNullOrEmpty(shapeName) ? this.model.FindShape(shapeName) : null;
}
}
/// <summary>
/// If the structure is a list it returns the shape contained into the list otherwise null.
/// This returns the original list shape from the model, ignoring any shape substitution in
/// effect via customizations.
/// </summary>
public Shape ModelListShape
{
get
{
var shapeName = LookupListShapeName(false);
return !string.IsNullOrEmpty(shapeName) ? this.model.FindShape(shapeName) : null;
}
}
/// <summary>
/// Returns the name of a shape declared to be used by a list type, optionally allowing
/// for substitution.
/// </summary>
/// <param name="allowSubstitution"></param>
/// <returns></returns>
private string LookupListShapeName(bool allowSubstitution)
{
var valueNode = this.data[MemberKey];
if (valueNode == null)
return null;
var extendsNode = valueNode[ServiceModel.ShapeKey];
if (extendsNode == null)
return null;
var shapeName = extendsNode.ToString();
if (allowSubstitution)
{
var substituteShape = this.model.Customizations.GetSubstituteShapeName(shapeName);
if (substituteShape != null)
shapeName = substituteShape;
}
return shapeName;
}
/// <summary>
/// The marshall name for the list elements
/// </summary>
public string ListMarshallName
{
get
{
var keyNode = this.data[MemberKey];
if (keyNode == null || keyNode[ServiceModel.LocationNameKey] == null)
return null;
return keyNode[ServiceModel.LocationNameKey].ToString();
}
}
/// <summary>
/// The name of the member that should be the payload of a request or is the payload of a response.
/// </summary>
public string PayloadMemberName
{
get
{
var payloadNode = this.data[PayloadKey];
if (payloadNode == null)
return null;
return payloadNode.ToString();
}
}
/// <summary>
/// Members of the shape, defined by another shape
/// </summary>
public virtual IList<Member> Members
{
get
{
IList<Member> map = new List<Member>();
JsonData members = this.data[MembersKey];
if (members != null)
{
foreach (KeyValuePair<string, JsonData> kvp in members)
{
// filter out excluded members and perform any property
// renames at this stage to make downstream generation
// simpler
if (this.model.Customizations.IsExcludedProperty(kvp.Key, this.Name))
continue;
var propertyModifier = this.model.Customizations.GetPropertyModifier(this.Name, kvp.Key);
string propertyName;
if (propertyModifier != null && propertyModifier.EmitName != null)
propertyName = propertyModifier.EmitName;
else
propertyName = kvp.Key;
map.Add(new Member(this.model, this, propertyName, kvp.Key, kvp.Value, propertyModifier));
}
}
var shapeModifier = this.model.Customizations.GetShapeModifier(this.Name);
if (shapeModifier != null)
{
var injectedProperties = shapeModifier.InjectedPropertyNames;
foreach (var p in injectedProperties)
{
map.Add(new Member(this.model, this, p, p, shapeModifier.InjectedPropertyData(p)));
}
}
if (this.model.Customizations.RetainOriginalMemberOrdering)
return map;
else
return map.OrderBy(x => x.PropertyName).ToList();
}
}
/// <summary>
/// Finds all structure MarshallNames under the current shape that contain no members
/// </summary>
public IList<string> FindMarshallNamesWithoutMembers()
{
List<string> emptyMembers = new List<string>();
HashSet<string> processedMembers = new HashSet<string>();
Queue<Shape> shapeQueue = new Queue<Shape>();
shapeQueue.Enqueue(this);
processedMembers.Add(this.MarshallName);
while (shapeQueue.Count > 0)
{
var currentShape = shapeQueue.Dequeue();
foreach (var child in currentShape.Members)
{
if (child.IsStructure && !processedMembers.Contains(child.MarshallName))
{
processedMembers.Add(child.MarshallName);
if (child.Shape.Members.Count != 0)
shapeQueue.Enqueue(child.Shape);
else
emptyMembers.Add(child.MarshallName);
}
}
}
return emptyMembers;
}
/// <summary>
/// Find the member that is marked as payload
/// </summary>
public Member PayloadMember
{
get
{
return Members.SingleOrDefault<Member>(m => string.Equals(m.ModeledName, PayloadMemberName
, StringComparison.InvariantCultureIgnoreCase));
}
}
public bool IsEventStream
{
get
{
var isEventStream = data[EventStreamKey];
if (isEventStream != null && isEventStream.IsBoolean)
{
return (bool) isEventStream;
}
return false;
}
}
/// <summary>
/// If this shape is a primitive type this returns true so that the request can show if the member has been set or not
/// </summary>
public bool IsNullable
{
get
{
return NullableTypes.Contains(this.Type);
}
}
/// <summary>
/// Determines if the shape's type is a string
/// </summary>
public bool IsString
{
get { return this.Type == "string"; }
}
/// <summary>
/// Determines if the shape's type is a timestamp
/// </summary>
public bool IsDateTime
{
get { return this.Type == "timestamp"; }
}
/// <summary>
/// Determines if the shape's type is a integer
/// </summary>
public bool IsInt
{
get { return this.Type == "integer"; }
}
/// <summary>
/// Determines if the shape's type is a long
/// </summary>
public bool IsLong
{
get { return this.Type == "long"; }
}
/// <summary>
/// Determines if the shape's type is a float
/// </summary>
public bool IsFloat
{
get { return this.Type == "float"; }
}
/// <summary>
/// Determines if the shape's type is a double
/// </summary>
public bool IsDouble
{
get { return this.Type == "double"; }
}
/// <summary>
/// Determines if the shape's type is a boolean
/// </summary>
public bool IsBoolean
{
get { return this.Type == "boolean"; }
}
/// <summary>
/// Determines if the shape's type is a map
/// </summary>
public bool IsMap
{
get
{
return this.Type == "map";
}
}
/// <summary>
/// Determines if the shape's type is a list
/// </summary>
public bool IsList
{
get
{
return this.Type == "list";
}
}
/// <summary>
/// Determines if the shape's type is a string and enum is set in the json
/// </summary>
public bool IsEnum
{
get
{
return this.Type == "string" && this.data["enum"] != null;
}
}
/// <summary>
/// Determines if the shape's type is a structure
/// </summary>
public bool IsStructure
{
get
{
return this.Type == "structure";
}
}
/// <summary>
/// Determines if the shape's type is a blob
/// </summary>
public bool IsMemoryStream
{
get
{
return this.Type == "blob";
}
}
/// <summary>
/// Determines if the shape's json has a requiresLength attribute
/// </summary>
public bool RequiresLength
{
get
{
return (bool)(this.data[RequiresLengthKey] ?? false);
}
}
/// <summary>
/// Determines if the shape has the Document trait.
/// <para />
/// From the Spec:
/// 1. Structures marked with the document trait MUST NOT contain members.
/// 2. Document Types can not be used as an input, output, or error shape of an operation.
/// 3. IDocument types cannot function as unions, errors, event streams, or events. A Structure that has a Document trait can not also have
/// exception, fault, union, event, or eventstream traits.
/// <para />
/// NOTE: Restrictions are NOT enforced at this property. This will always return true if the document trait is present, even if the shape is not in a valid configuration.
/// </summary>
public bool IsDocument
{
get
{
var documentNode = this.data[DocumentKey];
if (documentNode == null)
return false;
return bool.Parse(documentNode.ToString());
}
}
/// <summary>
/// Determines if the shape's json has a streaming attribute
/// </summary>
public bool IsStreaming
{
get
{
var streamingNode = this.data[StreamingKey];
if (streamingNode == null)
return false;
return bool.Parse(streamingNode.ToString());
}
}
public bool Sensitive
{
get
{
var sensitiveNode = data[SensitiveKey];
if (sensitiveNode == null)
return false;
return bool.Parse(sensitiveNode.ToString());
}
}
public long? Min
{
get
{
var value = data[MinKey];
if(value != null)
{
long min;
if (!long.TryParse(value.ToString(), out min))
{
Console.WriteLine("Generator does not support non-integer values for Min.");
return null;
}
return min;
}
return null;
}
}
public long? Max
{
get
{
var value = data[MaxKey];
if (value != null)
{
long max;
if (!long.TryParse(value.ToString(), out max))
{
Console.WriteLine("Generator does not support non-integer values for Max.");
return null;
}
return max;
}
return null;
}
}
public string Pattern
{
get
{
var value = data[PatternKey];
if (value == null) return null;
return value.ToString();
}
}
/// <summary>
/// Determines the type of the shape from the type attribute
/// </summary>
public string Type
{
get
{
var typeNode = this.data[TypeKey];
if (typeNode == null)
throw new Exception("Type is missing for shape " + this.Name);
return typeNode.ToString();
}
}
public bool HasErrorCode
{
get
{
var errorNode = this.data[ErrorKey];
if (errorNode != null)
return errorNode[ErrorCodeKey] != null;
return false;
}
}
public string ErrorCode
{
get
{
if (!HasErrorCode)
return null;
var errorNode = this.data[ErrorKey];
return errorNode[ErrorCodeKey].ToString();
}
}
/// <summary>
/// Determines if the shape json has a flattened attribute
/// </summary>
public bool IsFlattened
{
get
{
var flattened = data[FlattenedKey];
if (flattened == null || !flattened.IsBoolean) return false;
return (bool)flattened;
}
}
/// <summary>
/// The name of the marshaller. The locationName if it's set, the shapes name otherwise.
/// </summary>
public string MarshallName
{
get
{
return LocationName ?? this._name;
}
}
/// <summary>
/// Looks if there is a locationName for the shape, null otherwise
/// </summary>
public string LocationName
{
get
{
// if list, lookup member/metadata/xmlName
// otherwise, lookup metadata/xmlName
var source = data;
if (IsList)
{
source = data[MemberKey];
if (source == null) return null;
}
var locationName = source[ServiceModel.LocationNameKey];
if (locationName == null) return null;
return locationName.ToString();
}
}
public bool IsPrimitiveType
{
get
{
return PrimitiveTypeNames.ContainsKey(this.Type);
}
}
public string GetPrimitiveType()
{
string type;
if (!PrimitiveTypeNames.TryGetValue(this.Type, out type))
{
throw new Exception("Shape is not a primitive type: " + this.Type);
}
return type;
}
/// <summary>
/// The member names listed in the shape's json required attribute
/// </summary>
public IEnumerable<string> RequiredMembers
{
get
{
var req = new List<string>();
var required = data[RequiredKey];
if (required == null || !required.IsArray) return req;
req.AddRange(from object item in required select item.ToString());
req.Sort();
return req;
}
}
/// <summary>
/// Determines if the shape is Deprecated.
/// </summary>
public bool IsDeprecated
{
get
{
if (data[DeprecatedKey] != null && data[DeprecatedKey].IsBoolean)
return (bool)data[DeprecatedKey];
return false;
}
}
/// <summary>
/// Returns the deprecation message specified in the model or in the customization file.
/// </summary>
public string DeprecationMessage
{
get
{
string message = this.model.Customizations.GetShapeModifier(this._name)?.DeprecationMessage ??
data[DeprecatedMessageKey].CastToString();
if (message == null)
throw new Exception(string.Format("The 'message' property of the 'deprecated' trait is missing for shape {0}.\nFor example: \"ShapeName\":{{ ... \"members\":{{ ... }}, \"deprecated\":true, \"deprecatedMessage\":\"This type is deprecated\"}}", this._name));
return message;
}
}
/// <summary>
/// If the shape is a request or response type, strips off the suffix
/// to yield the parent operation. Null is returned if the shape is a
/// regular model shape.
/// </summary>
public string RelatedOperationName
{
get
{
const string RequestSuffix = "Request";
const string ResponseSuffix = "Response";
const string ResultSuffix = "Result";
var len = Name.Length;
if (Name.EndsWith(RequestSuffix, StringComparison.Ordinal))
return Name.Substring(0, len - RequestSuffix.Length);
if (Name.EndsWith(ResponseSuffix, StringComparison.Ordinal))
return Name.Substring(0, len - ResponseSuffix.Length);
if (Name.EndsWith(ResultSuffix, StringComparison.Ordinal))
return Name.Substring(0, len - ResultSuffix.Length);
return null;
}
}
/// <summary>
/// Returns the marshaller method to use in the generated marshaller code for a
/// shape of primitive type. This is used while marshalling lists and maps.
/// </summary>
public string PrimitiveMarshaller(MarshallLocation marshallLocation)
{
if (this.IsDateTime)
{
var timestampFormat = GetTimestampFormat(marshallLocation);
return "StringUtils.FromDateTimeTo" + timestampFormat;
}
else
{
return "StringUtils.From" + this.GetPrimitiveType();
}
}
/// <summary>
/// Timestamp format for the shape.
/// </summary>
public TimestampFormat GetTimestampFormat(MarshallLocation marshallLocation)
{
var timestampFormat = data.GetTimestampFormat();
if (timestampFormat == TimestampFormat.None)
{
timestampFormat = Member.GetDefaultTimestampFormat(marshallLocation, this.model.Type);
}
return timestampFormat;
}
public bool IsFieldRequired(string fieldName)
{
var requiredList = data[RequiredKey];
if (requiredList != null && requiredList.IsArray)
{
foreach (var name in requiredList)
{
if (string.Equals(name.ToString(), fieldName))
return true;
}
}
return false;
}
/// <summary>
/// Returns true if the structure contains the event trait,
/// not to be confused with the EventStream structure shape
/// </summary>
public bool IsEvent
{
get
{
return this.data.PropertyNames.Contains(EventKey);
}
}
}
}
| 859 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
#region BaseModel
/// <summary>
/// Used to outline the basics of any model for the service
/// They have a service model, json data, and documentation
/// </summary>
public abstract class BaseModel
{
public ServiceModel model { get; protected set; }
public JsonData data { get; protected set; }
protected BaseModel(ServiceModel model, JsonData data)
{
this.model = model;
this.data = data;
}
public virtual string Documentation
{
get
{
var docNode = data[ServiceModel.DocumentationKey];
if (docNode == null)
return string.Empty;
return docNode.ToString();
}
}
}
#endregion
#region OperationInput
/// <summary>
/// For some operations the xmlnamespace and locations are specified on the
/// operation:input. E.g. Route53 ChangeResourceRecordSets.
/// </summary>
public class OperationInput : BaseModel
{
/// <summary>
/// Creates an operation input through the BaseModel
/// </summary>
/// <param name="model">The model of the service</param>
/// <param name="data">The model as a jsonData object</param>
public OperationInput(ServiceModel model, JsonData data)
: base(model, data)
{
}
/// <summary>
/// The name of the location
/// </summary>
public string LocationName
{
get
{
var node = this.data[ServiceModel.LocationNameKey];
if (node == null)
return string.Empty;
return node.ToString();
}
}
/// <summary>
/// The namespace for the xml
/// </summary>
public string XmlNamespace
{
get
{
return data[ServiceModel.XmlNamespaceKey] == null ? string.Empty :
(string)data[ServiceModel.XmlNamespaceKey][ServiceModel.XmlNamespaceUriKey];
//var node = this.data[ServiceModel.XmlNamespaceKey];
//if (node == null)
// return string.Empty;
//return node.ToString();
}
}
}
#endregion
#region Enumeration
/// <summary>
/// Used to create the enumeration class for a service
/// </summary>
public class Enumeration
{
public const string EnumKey = "enum";
ServiceModel model;
readonly string _modelName;
readonly string _outputName;
readonly JsonData _data;
/// <summary>
/// Creates an enumeration that can model parts of the enumeration for the service
/// </summary>
/// <param name="model">The service model that is using the enumartion</param>
/// <param name="name">The name of the enumeration</param>
/// <param name="data">The json data for the enumartion object</param>
public Enumeration(ServiceModel model, string name, JsonData data)
{
this.model = model;
_modelName = name;
_data = data;
var overrideName = model.Customizations.GetOverrideShapeName(_modelName);
_outputName = !string.IsNullOrEmpty(overrideName)
? overrideName.ToUpperFirstCharacter()
: _modelName.ToUpperFirstCharacter();
}
/// <summary>
/// The name of the enumeration as encoded in the original model.
/// </summary>
public string ModelName
{
get { return this._modelName; }
}
/// <summary>
/// The emitted name of the enumeration. If no customization is
/// applied to the shape, this is the same as ModelName.
/// </summary>
public string Name
{
get { return _outputName; }
}
private string Customize(string typeName, string propertyName)
{
var custom = this.model.Customizations.GetPropertyModifier(typeName, propertyName);
if (custom != null)
return custom.EmitName;
return propertyName;
}
/// <summary>
/// A list of all the values for the Enumeration found in the json model
/// </summary>
public IEnumerable<EnumEntry> EnumerationValues
{
get
{
var enumValues = this._data[EnumKey];
var list = (from object value in enumValues
select new EnumEntry(value.ToString())).ToList();
foreach(var item in list)
{
var custom = this.model.Customizations.GetPropertyModifier(this.ModelName, item.MarshallName);
if (custom != null)
item.CustomPropertyName = custom.EmitName;
}
return list.OrderBy(x => x.PropertyName).ToList();
}
}
#region EnumEntry
/// <summary>
/// An enum entry is used to represent a value in the enumeration
/// </summary>
public class EnumEntry
{
/// <summary>
/// Creates an enumentry that represents a value of the enumeration that contains this object
/// </summary>
/// <param name="name"></param>
public EnumEntry(string name)
{
this.MarshallName = name;
}
/// <summary>
/// The name of the marshaller for the EnumEntry
/// </summary>
public string MarshallName
{
get;
private set;
}
private static readonly char[] CapitalizingSeparators =
{
'-', '/', '.', ' ', ':', ',', '+'
};
public string CustomPropertyName { get; set; }
/// <summary>
/// Then name of the entry to be used by the generator to represnet the entry in the code
/// </summary>
public string PropertyName
{
get
{
if (this.CustomPropertyName != null)
return this.CustomPropertyName;
var sb = new StringBuilder();
var tokens = this.MarshallName.Split(CapitalizingSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (var token in tokens)
{
var upperChar = token[0].ToString().ToUpper();
sb.Append(upperChar);
if (token.Length > 1)
{
var remainingName = token.Substring(1);
sb.Append(remainingName);
}
}
var result = sb
.Replace("(", "")
.Replace(")", "")
.ToString();
return result;
}
}
}
#endregion
}
#endregion
}
| 245 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using ServiceClientGenerator.Generators.ProjectFiles;
using System.Xml;
namespace ServiceClientGenerator
{
public class SolutionFileCreator
{
public GeneratorOptions Options { get; set; }
public IEnumerable<ProjectFileConfiguration> ProjectFileConfigurations { get; set; }
/// Regex check to identify framework of a project.
private static readonly Regex FrameworkRegex = new Regex(@"<TargetFramework[^>]*>(.*?)<\/TargetFramework>");
/// <summary>
/// The set of project 'types' (or platforms) that we generate the SDK against.
/// These type names form part of the project filename.
/// </summary>
public abstract class ProjectTypes
{
public const string Net35 = "Net35";
public const string Net45 = "Net45";
public const string NetStandard = "NetStandard";
public const string Partial = "partial";
}
// build configuration platforms used for net 3.5, 4.5 and portable project types
static readonly List<string> StandardPlatformConfigurations = new List<string>
{
"Debug|Any CPU",
"Release|Any CPU"
};
// build configuration platforms used for phone/RT project types
static readonly List<string> PhoneRtPlatformConfigurations = new List<string>
{
"Debug|Any CPU",
"Debug|ARM",
"Debug|x64",
"Debug|x86",
"Release|Any CPU",
"Release|ARM",
"Release|x64",
"Release|x86",
};
private const string GeneratorLibProjectGuid = "{7BEE7C44-BE12-43CC-AFB9-B5852A1F43C8}";
private const string GeneratorLibProjectName = "ServiceClientGeneratorLib";
private const string CommonTestProjectGuid = "{66F78F86-68D7-4538-8EA5-A669A08E1C19}";
private const string CommonTestProjectName = "AWSSDK.CommonTest";
private const string UnitTestUtilityProjectFileName35 = "AWSSDK.UnitTestUtilities.Net35";
private const string UtilityProjectFileGuid35 = "{A23CE153-A4A3-4D3A-A6DC-0DD1B207118E}";
private const string UnitTestUtilityProjectFileName45 = "AWSSDK.UnitTestUtilities.Net45";
private const string UtilityProjectFileGuid45 = "{002B183F-E568-49CD-9D06-CBCFF2C2921F}";
private const string IntegrationTestUtilityName35 = "AWSSDK.IntegrationTestUtilities.Net35";
private const string IntegrationTestUtilityGuid35 = "{924D2906-70D6-4D77-8603-816648B2CCA6}";
private const string IntegrationTestUtilityName45 = "AWSSDK.IntegrationTestUtilities.Net45";
private const string IntegrationTestUtilityGuid45 = "{7AB0DA1C-CA0E-4579-BA82-2B41A9DA15C7}";
private static Regex ProjectReferenceRegex = new Regex("\"([^\"]*)\"");
private static readonly ProjectFileCreator.ProjectConfigurationData GeneratorLibProjectConfig
= new ProjectFileCreator.ProjectConfigurationData
{
ProjectGuid = GeneratorLibProjectGuid,
ConfigurationPlatforms = StandardPlatformConfigurations
};
private static readonly ProjectFileCreator.ProjectConfigurationData CommonTestProjectConfig
= new ProjectFileCreator.ProjectConfigurationData
{
ProjectGuid = CommonTestProjectGuid,
ConfigurationPlatforms = StandardPlatformConfigurations
};
private static readonly Project GeneratorLibProject = new Project
{
Name = GeneratorLibProjectName,
ProjectGuid = GeneratorLibProjectGuid,
ProjectPath = string.Format(@"..\generator\{0}\{0}.csproj", GeneratorLibProjectName)
};
private static readonly Project ServiceSlnGeneratorLibProject = new Project
{
Name = GeneratorLibProjectName,
ProjectGuid = GeneratorLibProjectGuid,
ProjectPath = Path.Combine("..", "..", "..", GeneratorLibProject.ProjectPath)
};
private static readonly Project CommonTestProject = new Project
{
Name = CommonTestProjectName,
ProjectGuid = CommonTestProjectGuid,
ProjectPath = string.Format(@"..\sdk\test\Common\{0}.csproj", CommonTestProjectName)
};
private static readonly Project ServiceSlnCommonTestProject = new Project
{
Name = CommonTestProjectName,
ProjectGuid = CommonTestProjectGuid,
ProjectPath = Path.Combine("..", "..", "..", CommonTestProject.ProjectPath),
RelativePath = string.Format(@"..\..\..\test\Common\{0}.csproj", CommonTestProjectName)
};
private static readonly Project UnitTestUtilityProject35 = new Project
{
Name = UnitTestUtilityProjectFileName35,
ProjectGuid = UtilityProjectFileGuid35,
ProjectPath = string.Format(@"..\..\..\..\sdk\test\UnitTests\Custom\{0}.csproj", UnitTestUtilityProjectFileName35),
RelativePath = string.Format(@"..\..\..\test\UnitTests\Custom\{0}.csproj", UnitTestUtilityProjectFileName35)
};
private static readonly Project UnitTestUtilityProject45 = new Project
{
Name = UnitTestUtilityProjectFileName45,
ProjectGuid = UtilityProjectFileGuid45,
ProjectPath = string.Format(@"..\..\..\..\sdk\test\UnitTests\Custom\{0}.csproj", UnitTestUtilityProjectFileName45),
RelativePath = string.Format(@"..\..\..\test\UnitTests\Custom\{0}.csproj", UnitTestUtilityProjectFileName45)
};
private static readonly Project IntegrationTestUtility35Project = new Project
{
Name = IntegrationTestUtilityName35,
ProjectGuid = IntegrationTestUtilityGuid35,
ProjectPath = string.Format(@"..\..\..\..\sdk\test\IntegrationTests\{0}.csproj", IntegrationTestUtilityName35),
RelativePath = string.Format(@"..\..\..\test\IntegrationTests\{0}.csproj", IntegrationTestUtilityName35)
};
private static readonly Project IntegrationTestUtility45Project = new Project
{
Name = IntegrationTestUtilityName45,
ProjectGuid = IntegrationTestUtilityGuid45,
ProjectPath = string.Format(@"..\..\..\..\sdk\test\IntegrationTests\{0}.csproj", IntegrationTestUtilityName45),
RelativePath = string.Format(@"..\..\..\test\IntegrationTests\{0}.csproj", IntegrationTestUtilityName45)
};
private static readonly List<Project> CoreProjects = new List<Project>{
new Project
{
Name = "AWSSDK.Core.Net35",
ProjectGuid = "{1FACE5D0-97BF-4069-B4F7-0FE28BB160F8}",
ProjectPath = @"..\..\Core\AWSSDK.Core.Net35.csproj"
},
new Project
{
Name = "AWSSDK.Core.Net45",
ProjectGuid = "{7DE3AFA0-1B2D-41B1-82BD-120B8B210B43}",
ProjectPath = @"..\..\Core\AWSSDK.Core.Net45.csproj"
},
new Project
{
Name = "AWSSDK.Core.NetStandard",
ProjectGuid = "{A855B58E-ED32-40AE-AE8F-054F448B9F2C}",
ProjectPath = @"..\..\Core\AWSSDK.Core.NetStandard.csproj"
}
};
private readonly Dictionary<string, ProjectFileCreator.ProjectConfigurationData> _allProjects
= new Dictionary<string, ProjectFileCreator.ProjectConfigurationData>();
public void Execute(IDictionary<string, ProjectFileCreator.ProjectConfigurationData> newProjects)
{
Console.WriteLine("Updating solution files in {0}", Path.GetFullPath(Options.SdkRootFolder));
// transfer the new projects into our set-to-process, then scan for and augment the
// collection with existing projects.
foreach (var projectKey in newProjects.Keys)
{
_allProjects.Add(projectKey, newProjects[projectKey]);
}
AddSupportProjects();
ScanForExistingProjects();
// build project configuraitons for each solution
var net35ProjectConfigs = new List<ProjectFileConfiguration> { GetProjectConfig(ProjectTypes.Net35) };
var net45ProjectConfigs = new List<ProjectFileConfiguration> { GetProjectConfig(ProjectTypes.Net45) };
var netStandardProjectConfigs = new List<ProjectFileConfiguration> {
GetProjectConfig(ProjectTypes.NetStandard)
};
GenerateVS2017ServiceSolution(net35ProjectConfigs);
GenerateVS2017Solution("AWSSDK.Net35.sln", true, false, net35ProjectConfigs);
GenerateVS2017Solution("AWSSDK.Net45.sln", true, false, net45ProjectConfigs);
GenerateVS2017Solution("AWSSDK.NetStandard.sln", true, false, netStandardProjectConfigs);
// Include solutions that Travis CI can build
GenerateVS2017Solution("AWSSDK.Net35.Travis.sln", false, true, net35ProjectConfigs);
GenerateVS2017Solution("AWSSDK.Net45.Travis.sln", false, true, net45ProjectConfigs);
}
// adds any necessary projects to the collection prior to generating the solution file(s)
private void AddSupportProjects()
{
_allProjects.Add(GeneratorLibProjectName, GeneratorLibProjectConfig);
}
/// <summary>
/// Scans the SDK source and test folder locations to detect existing projects that
/// follow our naming convention, adding them to the set of all projects to be
/// processed into the solution files.
/// </summary>
private void ScanForExistingProjects()
{
const string awssdkProjectNamePattern = "AWSSDK.*.*proj";
var foldersToProcess = new[]
{
Path.Combine(Options.SdkRootFolder, GeneratorDriver.SourceSubFoldername),
Path.Combine(Options.SdkRootFolder, GeneratorDriver.TestsSubFoldername)
};
foreach (var rootFolder in foldersToProcess)
{
foreach (var projectFile in Directory.GetFiles(rootFolder, awssdkProjectNamePattern, SearchOption.AllDirectories))
{
var projectName = Path.GetFileNameWithoutExtension(projectFile);
if (_allProjects.ContainsKey(projectName))
continue;
var projectConfig = new ProjectFileCreator.ProjectConfigurationData
{
ProjectGuid = Utils.GetProjectGuid(projectFile),
ConfigurationPlatforms = GetProjectPlatforms(projectName, projectFile)
};
_allProjects.Add(projectName, projectConfig);
}
}
}
private ProjectFileConfiguration GetProjectConfig(string configType)
{
var config = ProjectFileConfigurations
.Single(pfc => string.Equals(pfc.Name, configType, StringComparison.Ordinal));
return config;
}
private static IEnumerable<string> GetProjectPlatformsFromFile(string projectFile)
{
var platforms = new List<string>();
var content = File.ReadAllText(projectFile);
var doc = new XmlDocument();
doc.LoadXml(content);
var searchPhrase = "$(Configuration)|$(Platform)";
var propertyGroups = doc.GetElementsByTagName("PropertyGroup");
foreach (XmlNode pg in propertyGroups)
{
var conditionAttribute = pg.Attributes["Condition"];
if (conditionAttribute != null)
{
var condition = conditionAttribute.Value;
if (condition.IndexOf(searchPhrase, StringComparison.Ordinal) >= 0)
{
var thirdQuote = condition.IndexOfNthOccurrence('\'', 0, 3);
var fourthQuote = condition.IndexOf('\'', thirdQuote);
var platform = condition.Substring(thirdQuote, fourthQuote - thirdQuote);
// Project files use the string "AnyCPU", solution files use "Any CPU"
platform = platform.Replace("AnyCPU", "Any CPU");
platforms.Add(platform);
}
}
}
return platforms;
}
private static IEnumerable<string> GetProjectPlatforms(string projectName, string projectFile)
{
string projectType = GetProjectType(projectName);
var platformConfigurations = GetPlatformConfigurations(projectType);
// Identify the framework of the project file if not already identified.
return IdentifyProjectConfigurations(projectFile, platformConfigurations, projectType);
}
private static string GetProjectType(string projectName)
{
var projectTypeStart = projectName.LastIndexOf('.');
var projectType = projectName.Substring(projectTypeStart + 1);
return projectType;
}
private static IEnumerable<string> GetPlatformConfigurations(string projectType)
{
switch (projectType)
{
case ProjectTypes.Net35:
case ProjectTypes.Net45:
case ProjectTypes.NetStandard:
case ProjectTypes.Partial:
return StandardPlatformConfigurations;
default:
return null;
}
}
/// <summary>
/// Method that opens the project file and does a Regex match for <TargetFramework></TargetFramework>
/// to identify the framework of the csproj.
/// </summary>
private static IEnumerable<string> IdentifyProjectConfigurations(string projectFile, IEnumerable<string> configurations, string projectType)
{
if (!string.IsNullOrEmpty(projectFile) && (configurations == null))
{
var fileContent = File.ReadAllText(projectFile);
var match = FrameworkRegex.Match(fileContent);
configurations = GetPlatformConfigurations(match.Groups[1].ToString());
}
if (configurations != null)
return configurations;
else
throw new Exception(string.Format("Unrecognized platform type in project name - '{0}'", projectType));
}
private static IDictionary<string, string> GetItemGuidDictionary(string solutionsFilePath)
{
IDictionary<string, string> itemGuidDictionary = new Dictionary<string, string>();
if (File.Exists(solutionsFilePath))
{
Regex expression = new Regex(@"Project\(""{(.*)}""\)\s*=\s*""(.*)"",\s*""(.*)"",\s*""(.*)""");
foreach (string line in File.ReadAllLines(solutionsFilePath))
{
Match match = expression.Match(line);
if (match.Success)
{
string itemType = match.Groups[1].ToString();
string itemName = match.Groups[2].ToString();
string itemSource = match.Groups[3].ToString();
string itemGuid = match.Groups[4].ToString();
itemGuidDictionary.Add(itemName, itemGuid);
}
}
}
return itemGuidDictionary;
}
private static string GetSolutionGuid(string solutionsFilePath)
{
if (File.Exists(solutionsFilePath))
{
Regex expression = new Regex(@"\s*SolutionGuid\s*=\s*{(.*)}");
foreach (string line in File.ReadAllLines(solutionsFilePath))
{
Match match = expression.Match(line);
if (match.Success)
{
return match.Groups[1].ToString();
}
}
}
return Guid.NewGuid().ToString("D").ToUpper();
}
private void GenerateVS2017Solution(string solutionFileName, bool includeTests, bool isTravisSolution, IEnumerable<ProjectFileConfiguration> projectFileConfigurations, ICollection<string> serviceProjectsForPartialBuild = null)
{
//
// Since vs2017 .csproj files are not identified by guid, see if we can scan and determine the guid ahead of time to reduce changes
// to .sln files if possible.
//
IDictionary<string, string> projectGuidDictionary = GetItemGuidDictionary(Path.Combine(Options.SdkRootFolder, solutionFileName));
string solutionGuid = GetSolutionGuid(Path.Combine(Options.SdkRootFolder, solutionFileName));
var sdkSourceFolder = Path.Combine(Options.SdkRootFolder, GeneratorDriver.SourceSubFoldername);
var session = new Dictionary<string, object>();
var buildConfigurations = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var solutionProjects = new Dictionary<string, ProjectFileCreator.ProjectConfigurationData>();
var serviceSolutionFolders = new List<ServiceSolutionFolder>();
var serviceProjectsRoot = Path.Combine(sdkSourceFolder, GeneratorDriver.ServicesSubFoldername);
var testServiceProjectsRoot = serviceProjectsRoot.Replace("src", "test");
var services = Directory.GetDirectories(serviceProjectsRoot).Select(c => new { Path = c, IsTestService = false });
var testServices = Directory.GetDirectories(testServiceProjectsRoot).Select(c => new { Path = c, IsTestService = true });
foreach (var servicePath in services.Concat(testServices))
{
var di = new DirectoryInfo(servicePath.Path);
var folder = ServiceSolutionFolderFromPath(di.Name);
// Previously, the project GUID was generated from a random array of bytes, but the output for that operation changed in netstandard.
// To prevent all solution files from being modified, we re-use the GUID for the current service (if there's one available).
if (projectGuidDictionary.ContainsKey(di.Name))
{
folder.ProjectGuid = projectGuidDictionary[di.Name];
}
// If we are generating a partial solution, and the service project has not changed, omit it from the partial solution.
bool omitService = serviceProjectsForPartialBuild != null && !serviceProjectsForPartialBuild.Contains(di.Name, StringComparer.InvariantCultureIgnoreCase);
if (omitService)
{
continue;
}
foreach (var configuration in projectFileConfigurations)
{
string projectFilePattern = string.Format("*.{0}.csproj", configuration.Name);
foreach (var projectFile in Directory.GetFiles(servicePath.Path, projectFilePattern, SearchOption.TopDirectoryOnly))
{
if (isTravisSolution && projectFile.Contains("AWSSDK.MobileAnalytics"))
continue;
string projectName = Path.GetFileNameWithoutExtension(projectFile);
folder.Projects.Add(new Project
{
Name = projectName,
ProjectPath = string.Format(servicePath.IsTestService ? @"test\Services\{0}\{1}" : @"src\Services\{0}\{1}", di.Name, Path.GetFileName(projectFile)),
ProjectGuid = projectGuidDictionary.ContainsKey(projectName) ? projectGuidDictionary[projectName] : Guid.NewGuid().ToString("B").ToUpper(),
});
SelectProjectAndConfigurationsForSolution(projectFile, solutionProjects, buildConfigurations);
}
}
if (folder.Projects.Count > 0)
serviceSolutionFolders.Add(folder);
}
IList<Project> coreProjects = new List<Project>();
var coreProjectsRoot = Path.Combine(sdkSourceFolder, GeneratorDriver.CoreSubFoldername);
foreach (var configuration in projectFileConfigurations)
{
string projectFilePattern = string.Format("*.{0}.csproj", configuration.Name);
foreach (var projectFile in Directory.GetFiles(coreProjectsRoot, projectFilePattern, SearchOption.TopDirectoryOnly))
{
string projectName = Path.GetFileNameWithoutExtension(projectFile);
coreProjects.Add(new Project
{
Name = projectName,
ProjectPath = string.Format(@"src\Core\{0}", Path.GetFileName(projectFile)),
ProjectGuid = projectGuidDictionary.ContainsKey(projectName) ? projectGuidDictionary[projectName] : Guid.NewGuid().ToString("B").ToUpper(),
});
}
}
IList<Project> testProjects = new List<Project>();
IList<Project> integrationTestDependencies = new List<Project>();
if (includeTests)
{
var testProjectsRoot = Path.Combine(Options.SdkRootFolder, GeneratorDriver.TestsSubFoldername);
foreach (var configuration in projectFileConfigurations)
{
string projectFilePattern = string.Format("*.{0}.csproj", configuration.Name);
foreach (var projectFile in Directory.GetFiles(testProjectsRoot, projectFilePattern, SearchOption.AllDirectories)
.Where(projectFile => !Path.GetFileNameWithoutExtension(projectFile).Contains("Utilities") &&
!Path.GetFullPath(projectFile).Contains("Services") &&
!Path.GetFullPath(projectFile).Contains("CSM")))
{
string projectName = Path.GetFileNameWithoutExtension(projectFile);
testProjects.Add(new Project
{
Name = projectName,
ProjectPath = CreateRelativePath(Options.SdkRootFolder, projectFile),
ProjectGuid = projectGuidDictionary.ContainsKey(projectName) ? projectGuidDictionary[projectName] : Guid.NewGuid().ToString("B").ToUpper(),
});
}
if (configuration.Name.Equals(ProjectTypes.Net35, StringComparison.Ordinal) || configuration.Name.Equals(ProjectTypes.Net45, StringComparison.Ordinal))
{
solutionProjects.Add(GeneratorLibProjectName, GeneratorLibProjectConfig);
testProjects.Add(GeneratorLibProject);
SelectBuildConfigurationsForProject(GeneratorLibProjectName, buildConfigurations);
solutionProjects.Add(CommonTestProjectName, CommonTestProjectConfig);
testProjects.Add(CommonTestProject);
SelectBuildConfigurationsForProject(CommonTestProjectName, buildConfigurations);
}
// We must add the CrtIntegration extension to the target framework-specific solutions (at this point there should only be a single projectFileConfiguration)
var platformSpecificCRTName = string.Format("AWSSDK.Extensions.CrtIntegration.{0}", projectFileConfigurations.First().Name);
var crtProject = new Project
{
Name = platformSpecificCRTName,
ProjectPath = $"..\\extensions\\src\\AWSSDK.Extensions.CrtIntegration\\{platformSpecificCRTName}.csproj",
ProjectGuid = projectGuidDictionary.ContainsKey(platformSpecificCRTName) ? projectGuidDictionary[platformSpecificCRTName] : Guid.NewGuid().ToString("B").ToUpper()
};
integrationTestDependencies.Add(crtProject);
solutionProjects.Add(platformSpecificCRTName, new ProjectFileCreator.ProjectConfigurationData
{
ProjectGuid = crtProject.ProjectGuid,
ConfigurationPlatforms = StandardPlatformConfigurations
});
}
}
session["TestProjects"] = testProjects;
session["IntegrationTestDependencies"] = integrationTestDependencies;
session["CoreProjects"] = coreProjects;
session["ServiceSolutionFolders"] = serviceSolutionFolders;
session["SolutionGuid"] = solutionGuid;
var generator = new SolutionFileBclAndNetStandard() { Session = session };
var content = generator.TransformText();
GeneratorDriver.WriteFile(Options.SdkRootFolder, null, solutionFileName, content, true, false);
}
private static string CreateRelativePath(string path1, string path2)
{
// we assume path2 is a strict subpath of path1
return path2.Replace(path1, "").TrimStart(new char[] { ' ', '\\', '/' });
}
/// <summary>
/// Service specific solution generator. A single sln file is created that contains csproj for net35,net45,netstandard and their corresponding integ and unit tests.
/// </summary>
private void GenerateVS2017ServiceSolution(IEnumerable<ProjectFileConfiguration> projectFileConfigurations)
{
var sdkSourceFolder = Path.Combine(Options.SdkRootFolder, GeneratorDriver.SourceSubFoldername);
var buildConfigurations = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var serviceProjectsRoot = Path.Combine(sdkSourceFolder, GeneratorDriver.ServicesSubFoldername);
var coreProjectsRoot = Path.Combine(sdkSourceFolder, GeneratorDriver.CoreSubFoldername);
// Iterating through each service in the service folder
foreach (var servicePath in Directory.GetDirectories(serviceProjectsRoot))
{
var session = new Dictionary<string, object>();
var serviceSolutionFolders = new List<ServiceSolutionFolder>();
var serviceDirectory = new DirectoryInfo(servicePath);
var folder = ServiceSolutionFolderFromPath(serviceDirectory.Name);
var solutionFileName = serviceDirectory.Name + ".sln";
var serviceProjectDependencies = new List<string>();
var testProjects = new List<Project>();
var dependentProjects = new List<string>();
var dependentProjectList = new List<Project>();
var solutionPath = Path.Combine(serviceDirectory.ToString(), solutionFileName);
// Since vs2017 .csproj files are not identified by guid, see if we can scan and determine the guid ahead of time to reduce changes
// to .sln files if possible.
IDictionary<string, string> projectGuidDictionary = GetItemGuidDictionary(solutionPath);
// Previously, the project GUID was generated from a random array of bytes, but the output for that operation changed in netstandard.
// To prevent all solution files from being modified, we re-use the GUID for the current service (if there's one available).
if (projectGuidDictionary.ContainsKey(serviceDirectory.Name))
{
folder.ProjectGuid = projectGuidDictionary[serviceDirectory.Name];
}
// Include only net35,net45,netstandard service csproj
// in the service specific solutions
foreach (var projectFile in Directory.EnumerateFiles(servicePath, "*.*", SearchOption.TopDirectoryOnly)
.Where(s => s.Contains("NetStandard") || s.Contains("Net35") || s.Contains("Net45")))
{
serviceProjectDependencies.AddRange(AddProjectDependencies(projectFile, serviceDirectory.Name, new List<string>()));
serviceProjectDependencies.Add(projectFile);
SelectProjectAndConfigurationsForSolution(projectFile, buildConfigurations);
}
// Include service's Unit and Integ csproj files and its dependencies.
AddTestProjectsAndDependencies(projectFileConfigurations, buildConfigurations, serviceDirectory, projectGuidDictionary, testProjects, dependentProjects);
// Add AWSSDK.CommonTest.csproj
testProjects.Add(ServiceSlnCommonTestProject);
SelectBuildConfigurationsForProject(CommonTestProjectName, buildConfigurations);
foreach (var serviceProjectDependency in serviceProjectDependencies)
{
string projectName = Path.GetFileNameWithoutExtension(serviceProjectDependency);
var filePath = serviceProjectDependency;
if (filePath.Contains(serviceDirectory.Name))
{
filePath = Path.GetFileName(serviceProjectDependency);
}
folder.Projects.Add(new Project
{
Name = projectName,
ProjectPath = filePath,
ProjectGuid = projectGuidDictionary.ContainsKey(projectName) ? projectGuidDictionary[projectName] : Guid.NewGuid().ToString("B").ToUpper()
});
}
if (folder.Projects.Count == 0)
{
continue;
}
ConvertToSlnRelativePath(testProjects, solutionPath);
serviceSolutionFolders.Add(folder);
// Adding core projects to service solution
session["CoreProjects"] = CoreProjects;
// Adding service projects and its dependencies to the service solution
session["ServiceSolutionFolders"] = serviceSolutionFolders;
// Adding test projects to the service solution
session["TestProjects"] = testProjects;
// Set solution guild property
session["SolutionGuid"] = GetSolutionGuid(solutionPath);
var dependentProjectPathList = dependentProjects.Distinct();
var serviceProjectDependenciesNames = serviceProjectDependencies.Select(val => Path.GetFileNameWithoutExtension(val));
foreach (var dependentProject in dependentProjectPathList)
{
if (!serviceProjectDependenciesNames.Contains(Path.GetFileNameWithoutExtension(dependentProject)))
{
var projectName = Path.GetFileNameWithoutExtension(dependentProject);
dependentProjectList.Add(new Project
{
Name = projectName,
ProjectPath = dependentProject,
ProjectGuid = projectGuidDictionary.ContainsKey(projectName) ? projectGuidDictionary[projectName] : Guid.NewGuid().ToString("B").ToUpper()
});
}
}
//Adding integration test service dependencies
session["IntegrationTestDependencies"] = dependentProjectList;
var generator = new SolutionFileBclAndNetStandard() { Session = session };
var content = generator.TransformText();
GeneratorDriver.WriteFile(serviceDirectory.FullName, null, solutionFileName, content, true, false);
}
}
/// <summary>
/// This method converts the test projects path from being generator sln relative to the service specific sln
/// relative path
/// Ex
/// ..\..\..\..\sdk\test\Services\{ServiceName}\UnitTests\AWSSDK.UnitTests.{ServiceName}.Net35.csproj
/// becomes
/// ..\..\..\test\Services\{ServiceName}\UnitTests\AWSSDK.UnitTests.{ServiceName}.Net35.csproj
/// </summary>
private static void ConvertToSlnRelativePath(List<Project> testProjects, string solutionPath)
{
var solutionUri = new Uri(Path.GetFullPath(solutionPath));
foreach (var testProject in testProjects)
{
if (!string.IsNullOrEmpty(testProject.RelativePath))
{
continue;
}
var testProjecturi = new Uri(Path.GetFullPath(testProject.ProjectPath));
testProject.RelativePath = solutionUri.MakeRelativeUri(testProjecturi).ToString().Replace('/', Path.DirectorySeparatorChar);
}
}
/// <summary>
/// Adding Service test projects and its dependecies
/// </summary>
private void AddTestProjectsAndDependencies(IEnumerable<ProjectFileConfiguration> projectFileConfigurations, HashSet<string> buildConfigurations, DirectoryInfo serviceDirectory,
IDictionary<string, string> projectGuidDictionary, IList<Project> testProjects, List<string> dependentProjects)
{
var testProjectsRoot = Path.Combine(Options.SdkRootFolder, GeneratorDriver.TestsSubFoldername, GeneratorDriver.ServicesSubFoldername, serviceDirectory.Name);
foreach (var configuration in projectFileConfigurations)
{
string filePattern = string.Format("*.csproj");
foreach (var projectFile in Directory.GetFiles(testProjectsRoot, filePattern, SearchOption.AllDirectories))
{
string projectName = Path.GetFileNameWithoutExtension(projectFile);
if (GetProjectType(projectName).Equals(ProjectTypes.Partial, StringComparison.Ordinal))
{
continue;
}
if (projectName.Contains("Integration") || projectName.Contains("UnitTests"))
{
dependentProjects.AddRange(AddProjectDependencies
(projectFile, serviceDirectory.Name, new List<string>()));
}
testProjects.Add(new Project
{
Name = projectName,
ProjectPath = projectFile,
ProjectGuid = projectGuidDictionary.ContainsKey(projectName) ? projectGuidDictionary[projectName] : Guid.NewGuid().ToString("B").ToUpper(),
});
}
if (configuration.Name.Equals(ProjectTypes.Net35, StringComparison.Ordinal) || configuration.Name.Equals(ProjectTypes.Net45, StringComparison.Ordinal))
{
testProjects.Add(ServiceSlnGeneratorLibProject);
SelectBuildConfigurationsForProject(GeneratorLibProjectName, buildConfigurations);
testProjects.Add(UnitTestUtilityProject35);
testProjects.Add(UnitTestUtilityProject45);
testProjects.Add(IntegrationTestUtility35Project);
dependentProjects.AddRange(AddProjectDependencies
(IntegrationTestUtility35Project.ProjectPath, serviceDirectory.Name, new List<string>()));
testProjects.Add(IntegrationTestUtility45Project);
dependentProjects.AddRange(AddProjectDependencies
(IntegrationTestUtility45Project.ProjectPath, serviceDirectory.Name, new List<string>()));
}
}
}
/// <summary>
/// Opens a csproj file and recursively adds the project's reference to the sln dependency list
/// </summary>
private List<string> AddProjectDependencies(string projectFile, string serviceName, List<string> depsProjects)
{
// This slash conversion will make sure that the projectFile path works in Linux and Windows environment
projectFile = projectFile.Replace('\\', Path.DirectorySeparatorChar);
foreach (var line in File.ReadAllLines(projectFile))
{
if (line.Contains("ProjectReference"))
{
var matches = ProjectReferenceRegex.Match(line);
var fileName = matches.ToString().Replace("\"", "");
if (!(fileName.Contains("\\Core\\") || fileName.Contains("/Core/") || fileName.Contains($".{serviceName}.") || fileName.Contains("Test") || depsProjects.Contains(fileName)))
{
var split = fileName.Contains('\\') ? fileName.Split('\\') : fileName.Split('/');
// This is in a different folder in than the usual service dependencies.
// Also skipping the recursion since this does not currently have any ProjectReferences beyond Core
if (fileName.Contains("AWSSDK.Extensions.CrtIntegration"))
{
// Build the relative path to \extensions\src\AWSSDK.Extensions.CrtIntegration\AWSSDK.Extensions.CrtIntegration.<target framework>.csproj
var deps = Path.Combine("..", "..", "..", "..", split[split.Length - 4], split[split.Length - 3], split[split.Length - 2], split[split.Length - 1]);
depsProjects.Add(deps);
}
else
{
// Build the relative path to \<service folder>\AWSSDK.<service>.<target framework>.csproj
var deps = Path.Combine("..", split[split.Length - 2], split[split.Length - 1]);
depsProjects.Add(deps);
AddProjectDependencies(Path.Combine(Options.SdkRootFolder, "src", "Services", split[split.Length - 2], split[split.Length - 1]), split[split.Length - 2], depsProjects);
}
}
}
}
return depsProjects;
}
private void AddExtraTestProjects(ProjectFileConfiguration projectConfig, Dictionary<string, ProjectFileCreator.ProjectConfigurationData> solutionProjects, List<Project> testProjects)
{
foreach (var extraTestProject in projectConfig.ExtraTestProjects)
{
var projectPath = @"..\..\..\..\sdk\" + extraTestProject;
var projectGuid = Utils.GetProjectGuid(projectPath);
var testProject = ProjectFromFile(extraTestProject, projectGuid);
var testProjectConfig = new ProjectFileCreator.ProjectConfigurationData
{
ProjectGuid = projectGuid,
ConfigurationPlatforms = GetProjectPlatformsFromFile(projectPath).ToList()
};
solutionProjects.Add(testProject.Name, testProjectConfig);
testProjects.Add(testProject);
}
}
void SelectProjectAndConfigurationsForSolution(string projectFile,
IDictionary<string, ProjectFileCreator.ProjectConfigurationData> solutionProjects,
ISet<string> buildConfigurations)
{
var projectKey = Path.GetFileNameWithoutExtension(projectFile);
solutionProjects.Add(projectKey, _allProjects[projectKey]);
SelectBuildConfigurationsForProject(projectKey, buildConfigurations);
}
void SelectProjectAndConfigurationsForSolution(string projectFile,
ISet<string> buildConfigurations)
{
var projectKey = Path.GetFileNameWithoutExtension(projectFile);
SelectBuildConfigurationsForProject(projectKey, buildConfigurations);
}
void SelectBuildConfigurationsForProject(string projectKey, ISet<string> buildConfigurations)
{
foreach (var cp in _allProjects[projectKey].ConfigurationPlatforms)
{
buildConfigurations.Add(cp);
}
}
Project CoreProjectFromFile(string projectFile)
{
var fi = new FileInfo(projectFile);
var projectName = Path.GetFileNameWithoutExtension(fi.Name);
return new Project
{
Name = Path.GetFileNameWithoutExtension(projectFile),
ProjectGuid = this._allProjects[projectName].ProjectGuid,
ProjectPath = @"src\Core\" + fi.Name
};
}
Project TestProjectFromFile(string folderName, string projectFile)
{
var fi = new FileInfo(projectFile);
var projectName = Path.GetFileNameWithoutExtension(fi.Name);
return new Project
{
Name = Path.GetFileNameWithoutExtension(projectFile),
ProjectGuid = _allProjects[projectName].ProjectGuid,
ProjectPath = string.Format(@"test\{0}\{1}", folderName, fi.Name)
};
}
Project ServiceProjectFromFile(string folderName, string projectFile)
{
var fi = new FileInfo(projectFile);
var projectName = Path.GetFileNameWithoutExtension(fi.Name);
return new Project
{
Name = Path.GetFileNameWithoutExtension(projectFile),
ProjectGuid = this._allProjects[projectName].ProjectGuid,
ProjectPath = string.Format(@"src\Services\{0}\{1}", folderName, fi.Name)
};
}
Project ProjectFromFile(string projectFile, string projectGuid)
{
var fi = new FileInfo(projectFile);
var projectName = Path.GetFileNameWithoutExtension(fi.Name);
return new Project
{
Name = Path.GetFileNameWithoutExtension(projectFile),
ProjectGuid = projectGuid,
ProjectPath = projectFile
};
}
ServiceSolutionFolder ServiceSolutionFolderFromPath(string folderName)
{
return new ServiceSolutionFolder(folderName.Replace("Amazon.", ""));
}
public class Project
{
public string ProjectGuid { get; set; }
public string ProjectPath { get; set; }
public string Name { get; set; }
public string FolderGuid { get; set; }
/// <summary>
/// This property is being used only by service specific sln's test projects
/// to denote a path relative to the sln files.
/// </summary>
public string RelativePath { get; set; }
}
public class ServiceSolutionFolder
{
public string Name { get; private set; }
public List<Project> Projects { get; private set; }
public string ProjectGuid { get; set; }
public ServiceSolutionFolder(string folderName)
{
Name = folderName;
Projects = new List<Project>();
ProjectGuid = Guid.NewGuid().ToString("B").ToUpper();
}
}
}
}
| 866 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator
{
class UnitTestProjectFileCreator
{
private readonly string TemplateName = "VS2017ProjectFile";
private GeneratorOptions _options;
private IEnumerable<ProjectFileConfiguration> _configurations;
private string _serviceName;
private bool _isLegacyProj;
public UnitTestProjectFileCreator(GeneratorOptions options, IEnumerable<ProjectFileConfiguration> configurations)
{
_options = options;
_configurations = configurations;
_isLegacyProj = true;
}
public UnitTestProjectFileCreator(GeneratorOptions options, IEnumerable<ProjectFileConfiguration> configurations, string serviceName)
{
_options = options;
_configurations = configurations;
_serviceName = serviceName;
_isLegacyProj = false;
}
public void Execute(string unitTestRoot, IEnumerable<ServiceConfiguration> serviceConfigurations, bool useDllReference)
{
foreach (var configuration in _configurations)
{
IList<ProjectFileCreator.ProjectReference> projectReferences;
IList<ProjectFileCreator.ProjectReference> serviceProjectReferences;
string projectName;
if (_isLegacyProj)
{
projectName = string.Format("AWSSDK.UnitTests.{0}.csproj", configuration.Name);
serviceProjectReferences = new List<ProjectFileCreator.ProjectReference>()
{
new ProjectFileCreator.ProjectReference
{
IncludePath = $@"..\..\src\Services\*\*.{configuration.Name}.csproj"
},
new ProjectFileCreator.ProjectReference
{
IncludePath = $@"..\..\test\Services\*\*.{configuration.Name}.csproj"
}
};
}
else
{
projectName = string.Format("AWSSDK.UnitTests.{0}.{1}.csproj", _serviceName, configuration.Name);
serviceProjectReferences = ServiceProjectReferences(unitTestRoot, serviceConfigurations, configuration.Name);
}
string projectGuid = Utils.GetProjectGuid(Path.Combine(unitTestRoot, projectName));
projectReferences = GetCommonReferences(unitTestRoot, configuration.Name, useDllReference);
var projectProperties = new Project()
{
TargetFrameworks = configuration.TargetFrameworkVersions,
DefineConstants = configuration.CompilationConstants.Concat(new string[] { "DEBUG" }).ToList(),
ReferenceDependencies = configuration.DllReferences,
CompileRemoveList = configuration.PlatformExcludeFolders,
Services = configuration.VisualStudioServices,
FrameworkPathOverride = configuration.FrameworkPathOverride,
PackageReferences = configuration.PackageReferences,
SupressWarnings = configuration.NoWarn,
OutputPathOverride = configuration.OutputPathOverride,
SignBinaries = false
};
if (_isLegacyProj)
{
projectProperties.AssemblyName = string.Format("AWSSDK.UnitTests.{0}", configuration.Name);
projectProperties.IndividualFileIncludes = new List<string> { "../Services/*/UnitTests/**/*.cs" };
projectProperties.EmbeddedResources = configuration.EmbeddedResources;
projectProperties.FxcopAnalyzerRuleSetFilePath = @"..\..\AWSDotNetSDK.ruleset";
projectProperties.FxcopAnalyzerRuleSetFilePathForBuild = @"..\..\AWSDotNetSDKForBuild.ruleset";
}
else
{
projectProperties.AssemblyName = string.Format("AWSSDK.UnitTests.{0}.{1}", _serviceName, configuration.Name);
//Check for embedded resources
var embeddedResourcePath = Path.Combine(unitTestRoot, "Custom", "EmbeddedResource");
if (Directory.Exists(embeddedResourcePath))
{
projectProperties.EmbeddedResources = new List<string> { Path.Combine("Custom", "EmbeddedResource", "*") };
}
projectProperties.FxcopAnalyzerRuleSetFilePath = @"..\..\..\..\AWSDotNetSDK.ruleset";
projectProperties.FxcopAnalyzerRuleSetFilePathForBuild = @"..\..\..\..\AWSDotNetSDKForBuild.ruleset";
}
if (serviceProjectReferences != null)
{
Array.ForEach(serviceProjectReferences.ToArray(), x => projectReferences.Add(x));
}
projectProperties.ProjectReferences = projectReferences;
GenerateProjectFile(projectProperties, unitTestRoot, projectName);
}
}
private IList<ProjectFileCreator.ProjectReference> GetCommonReferences(string unitTestRoot, string projectType, bool useDllReference)
{
IList<ProjectFileCreator.ProjectReference> references = new List<ProjectFileCreator.ProjectReference>();
//
// Core project reference
//
if (!useDllReference)
{
string coreProjectName = string.Format("AWSSDK.Core.{0}", projectType);
string coreIncludePath = Path.Combine("..", "..", "src", "Core", coreProjectName + ".csproj");
if (!_isLegacyProj)
{
coreIncludePath = Path.Combine("..", "..", coreIncludePath);
}
string coreProjectPath = Path.Combine(unitTestRoot, coreIncludePath);
references.Add(new ProjectFileCreator.ProjectReference
{
Name = coreProjectName,
IncludePath = coreIncludePath
});
}
//
// CommonTest project reference
//
string commonTestProjectName = "AWSSDK.CommonTest";
string commonTestIncludePath = Path.Combine("..", "Common", commonTestProjectName + ".csproj");
if (!_isLegacyProj)
{
commonTestIncludePath = Path.Combine("..", "..", commonTestIncludePath);
}
references.Add(new ProjectFileCreator.ProjectReference
{
Name = commonTestProjectName,
IncludePath = commonTestIncludePath
});
string projectName, projectPath;
if (_isLegacyProj)
{
projectName = "ServiceClientGeneratorLib";
projectPath = string.Format("..\\..\\..\\generator\\ServiceClientGeneratorLib\\{0}.csproj", projectName);
}
else
{
projectName = $"AWSSDK.UnitTestUtilities.{projectType}";
projectPath = Path.Combine("..", "..", "..", "UnitTests", "Custom", projectName + ".csproj");
}
references.Add(new ProjectFileCreator.ProjectReference
{
Name = projectName,
IncludePath = projectPath
});
// Add reference to CRT extension to all unit test projects now
// that any service can start using flexible checksums
var crtExtension = new ProjectFileCreator.ProjectReference
{
Name = $"AWSSDK.Extensions.CrtIntegration.{projectType}"
};
if (_isLegacyProj) // unit test projects with all services, which need CRT also but have a different relative path
{
crtExtension.IncludePath = Path.Combine(new string[] { "..", "..", "..", "extensions", "src",
"AWSSDK.Extensions.CrtIntegration", $"AWSSDK.Extensions.CrtIntegration.{projectType}.csproj" });
}
else // service-specific project
{
crtExtension.IncludePath = Path.Combine(new string[] {"..", "..", "..", "..", "..", "extensions", "src",
"AWSSDK.Extensions.CrtIntegration", $"AWSSDK.Extensions.CrtIntegration.{projectType}.csproj"});
}
references.Add(crtExtension);
return references;
}
private IList<ProjectFileCreator.ProjectReference> ServiceProjectReferences(string unitTestRoot,
IEnumerable<ServiceConfiguration> serviceConfigurations,
string projectType)
{
HashSet<string> guidSet = new HashSet<string>();
List<ProjectFileCreator.ProjectReference> references = new List<ProjectFileCreator.ProjectReference>();
foreach (var configuration in serviceConfigurations)
{
string projectName = string.Format("{0}.{1}", configuration.AssemblyTitle, projectType);
string includePath = Path.Combine("..", "..", "src", "Services", configuration.ServiceFolderName, projectName + ".csproj");
if (!_isLegacyProj)
{
includePath = Path.Combine("..", "..", includePath);
}
// for test service unit tests project the actual service is generated one level up the tree
if (configuration.IsTestService)
{
includePath = Path.Combine("..", projectName + ".csproj");
}
string guid = Utils.GetProjectGuid(Path.Combine(unitTestRoot, includePath));
if (guidSet.Contains(guid))
{
// ServiceConfiguration list contains two entries for DynamoDBv2 and DynamoDBStreams
// which resolve to the same project.
continue;
}
references.Add(new ProjectFileCreator.ProjectReference
{
Name = projectName,
IncludePath = includePath,
ProjectGuid = guid
});
guidSet.Add(guid);
}
references.Sort();
return references;
}
private void GenerateProjectFile(Project projectProperties, string unitTestProjectRoot, string projectFilename)
{
var projectName = Path.GetFileNameWithoutExtension(projectFilename);
string generatedContent = null;
try
{
var projectTemplateType = Type.GetType(
"ServiceClientGenerator.Generators.ProjectFiles." +
TemplateName);
dynamic generator = Activator.CreateInstance(projectTemplateType);
generator.Project = projectProperties;
generatedContent = generator.TransformText();
}
catch (Exception)
{
throw new ArgumentException("Project template name "
+ TemplateName + " is not recognized");
}
GeneratorDriver.WriteFile(unitTestProjectRoot, string.Empty, projectFilename, generatedContent);
}
}
}
| 258 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
namespace ServiceClientGenerator
{
public static class Utils
{
public static string GetVersion(string fileVersionText)
{
var fileVersion = new Version(fileVersionText);
var version = new Version(fileVersion.Major, fileVersion.Minor);
var text = version.ToString();
return text;
}
public static int IndexOfNthOccurrence(this string self, char value, int startIndex, int n)
{
int index = startIndex;
for (int i = 0; i < n; i++)
{
index = self.IndexOf(value, index) + 1;
if (index < 0)
return index;
}
return index;
}
public static JsonData SafeGet(this JsonData self, string propertyName)
{
JsonData data;
try
{
data = self[propertyName];
}
catch
{
data = null;
}
return data;
}
public static string CastToString(this JsonData self)
{
//Casting a null JsonData reference to string result in an exception
if (self == null)
return null;
return (string)self;
}
public static string NewProjectGuid
{
get
{
return Guid.NewGuid().ToString("B").ToUpper();
}
}
public static string GetProjectGuid(string projectPath)
{
if (!File.Exists(projectPath))
return NewProjectGuid;
var xdoc = new XmlDocument();
xdoc.Load(projectPath);
var propertyGroups = xdoc.GetElementsByTagName("PropertyGroup");
int propertyGroupIndex;
if (string.Equals(Path.GetExtension(projectPath), ".xproj", StringComparison.CurrentCultureIgnoreCase))
propertyGroupIndex = 1;
else
propertyGroupIndex = 0;
var element = ((XmlElement)propertyGroups[propertyGroupIndex]).GetElementsByTagName("ProjectGuid")[0];
if (element == null)
return NewProjectGuid;
var projectGuid = element.InnerText;
return projectGuid;
}
public static string SafeGetString(this JsonData self, string propertyName)
{
var val = self.SafeGet(propertyName);
if (null == val || !val.IsString)
return String.Empty;
return val.ToString();
}
public static IDictionary<string, JsonData> GetMap(this JsonData self)
{
var result = new Dictionary<string, JsonData>();
if (self != null || self.IsObject)
{
foreach (var key in self.PropertyNames)
{
result[key] = self.SafeGet(key);
}
}
return result;
}
public static IDictionary<string, string> GetStringMap(this JsonData self)
{
var result = new Dictionary<string, string>();
if (self != null || self.IsObject)
{
foreach (var key in self.PropertyNames)
{
var tmp = self.SafeGet(key);
if (tmp.IsString)
result[key] = tmp.ToString();
}
}
return result;
}
public static Member GetMemberByName(this IList<Member> self, string name)
{
return self.Where(m => m.ModeledName.Equals(name, StringComparison.OrdinalIgnoreCase))
.SingleOrDefault();
}
/// <summary>
/// Parses the timestampFormat attribute if specified and returns it.
/// </summary>
public static TimestampFormat GetTimestampFormat(this JsonData self)
{
var value = self[Shape.TimestampFormatKey];
if (value == null) { return TimestampFormat.None; }
return Enum.TryParse<TimestampFormat>(value.ToString(), true, out var parsedValue) ?
parsedValue :
throw new Exception("Encountered unknown timestampFormat: "+ parsedValue);
}
public static string JsonDataToString(JsonData data)
{
return (data == null)
? null
: data.ToString();
}
public static List<string> GetServiceDirectories(GeneratorOptions options)
{
var serviceDirectories = new List<string>();
if (string.IsNullOrEmpty(options.ServiceModels))
{
serviceDirectories.AddRange(Directory.GetDirectories(options.ModelsFolder));
serviceDirectories.AddRange(Directory.GetDirectories(options.TestModelsFolder));
}
else
{
var services = options.ServiceModels.Split(';');
// only get specified models folders
foreach (var service in services)
{
serviceDirectories.AddRange(Directory.GetDirectories(options.ModelsFolder, service));
serviceDirectories.AddRange(Directory.GetDirectories(options.TestModelsFolder, service));
}
}
return serviceDirectories;
}
}
}
| 176 |
aws-sdk-net | aws | C# | using System;
using System.IO;
using System.Linq;
namespace ServiceClientGenerator.DefaultConfiguration
{
/// <inheritdoc cref="LoadDefaultConfiguration"/>
public interface IDefaultConfigurationController
{
/// <summary>
/// Fully loads and populates <see cref="DefaultConfigurationModel"/> by parsing the
/// sdk-default-configurations.json file from disk. Also adds the 'Legacy'
/// <see cref="DefaultConfigurationMode"/> with the correct defaults.
/// </summary>
/// <param name="repositoryRootDirectoryPath">
/// Full path to the root directory, ie contains the 'sdk' directory.
/// </param>
/// <remarks>
/// The sdk-default-configuration.json file is placed into the
/// repository by an upstream process in ServiceBuildAutomation.
/// </remarks>
DefaultConfigurationModel LoadDefaultConfiguration(string repositoryRootDirectoryPath);
}
/// <inheritdoc cref="IDefaultConfigurationController"/>
public class DefaultConfigurationController : IDefaultConfigurationController
{
private readonly IFileReader _fileReader;
private readonly IDefaultConfigurationParser _defaultConfigurationParser;
public DefaultConfigurationController(
IFileReader fileReader,
IDefaultConfigurationParser defaultConfigurationParser)
{
_fileReader = fileReader;
_defaultConfigurationParser = defaultConfigurationParser;
}
/// <inheritdoc cref="IDefaultConfigurationController.LoadDefaultConfiguration"/>
public DefaultConfigurationModel LoadDefaultConfiguration(string repositoryRootDirectoryPath)
{
var filePath = Path.Combine(repositoryRootDirectoryPath, "sdk","src","Core","sdk-default-configuration.json");
string json;
try
{
json = _fileReader.ReadAllText(filePath);
}
catch (Exception e)
{
throw new Exception($"Error reading Json from [{filePath}]: {e.Message}", e);
}
var parsedModel = _defaultConfigurationParser.Parse(json);
EnrichLegacyMode(parsedModel);
return parsedModel;
}
private void EnrichLegacyMode(DefaultConfigurationModel parsedModel)
{
var legacyMode =
parsedModel
.Modes
.FirstOrDefault(x => string.Equals(x.Name, "Legacy", StringComparison.OrdinalIgnoreCase));
if (legacyMode == null)
throw new Exception(
"Did not find required Default Configuration mode 'Legacy'. " +
$"Found: {string.Join(",", parsedModel.Modes.Select(x => x.Name))}");
legacyMode.RetryMode = RequestRetryMode.Legacy;
legacyMode.S3UsEast1RegionalEndpoint = S3UsEast1RegionalEndpointValue.Legacy;
legacyMode.StsRegionalEndpoints = StsRegionalEndpointsValue.Legacy;
// default to null for timeouts - this preserves the ServiceConfig
// behavior of defaulting configurable timeouts to null
legacyMode.TimeToFirstByteTimeout = null;
legacyMode.ConnectTimeout = null;
legacyMode.HttpRequestTimeout = null;
legacyMode.TlsNegotiationTimeout = null;
}
}
} | 84 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace ServiceClientGenerator.DefaultConfiguration
{
/// <summary>
/// Model representing the default configuration modes as built
/// from the sdk-default-configurations.json file.
/// </summary>
public class DefaultConfigurationModel
{
public List<DefaultConfigurationMode> Modes { get; set; }
= new List<DefaultConfigurationMode>();
/// <summary>
/// Provides documentation on each configuration option, ie
/// <see cref="DefaultConfigurationMode.S3UsEast1RegionalEndpoint"/>.
/// <para />
/// Key is a Property in <see cref="DefaultConfigurationMode"/>, value is the
/// Documentation describing the configuration option that Property represents.
/// </summary>
public Dictionary<string, string> ConfigurationOptionDocumentation { get; set; }
= new Dictionary<string, string>();
}
[DebuggerDisplay("{"+ nameof(Name) + "}")]
public class DefaultConfigurationMode
{
/// <summary>
/// Identifies a specific configuration mode. Example legacy, mobile, cross-region, etc
/// </summary>
public string Name { get; set; }
/// <summary>
/// Description of this Configuration Mode
/// </summary>
public string Documentation { get; set; }
/// <summary>
/// A retry mode specifies how the SDK attempts retries.
/// See https://docs.aws.amazon.com/sdkref/latest/guide/setting-global-retry_mode.html
/// </summary>
public RequestRetryMode RetryMode { get; set; }
/// <summary>
/// Specifies how the SDK determines the AWS service endpoint that it uses to talk to the AWS Security Token Service (AWS STS).
/// See https://docs.aws.amazon.com/sdkref/latest/guide/setting-global-sts_regional_endpoints.html
/// </summary>
public StsRegionalEndpointsValue StsRegionalEndpoints { get; set; }
/// <summary>
/// Specifies how the SDK determines the AWS service endpoint that it uses to talk to the Amazon S3 for the us-east-1 region
/// </summary>
public S3UsEast1RegionalEndpointValue S3UsEast1RegionalEndpoint { get; set; }
/// <summary>
/// The amount of time after making an initial connect attempt on a socket, where if the client does not
/// receive a completion of the connect handshake, the client gives up and fails the operation.
/// </summary>
public TimeSpan? ConnectTimeout { get; set; }
/// <summary>
/// The maximum amount of time that a TLS handshake is allowed to take from the time the CLIENT HELLO message is sent to
/// the client and server have fully negotiated ciphers and exchanged keys
/// </summary>
public TimeSpan? TlsNegotiationTimeout { get; set; }
/// <summary>
/// How long an application will attempt to read the first byte over an established,
/// open connection after write request before timing out.
/// </summary>
public TimeSpan? TimeToFirstByteTimeout { get; set; }
/// <summary>
/// This timeout measures the time between when the first byte is sent over an established,
/// open connection and when the last byte is received from the service.
/// If the response is not received by the timeout, then the request is considered timed out.
/// </summary>
public TimeSpan? HttpRequestTimeout { get; set; }
}
/// <summary>
/// RetryMode determines which request retry mode is used for requests that do
/// not complete successfully.
/// </summary>
/// <remarks>This is a copy of Amazon.Runtime.RequestRetryMode</remarks>
public enum RequestRetryMode
{
/// <summary>
/// Legacy request retry strategy.
/// </summary>
Legacy,
/// <summary>
/// Standardized request retry strategy that is consistent across all SDKs.
/// </summary>
Standard,
/// <summary>
/// An experimental request retry strategy that builds on the Standard strategy
/// and introduces congestion control through client side rate limiting.
/// </summary>
Adaptive
}
/// <summary>
/// Sts Regional Endpoints Value determines whether or not
/// to send the sts request to the regional endpoint or to
/// the global sts endpoint
/// </summary>
/// <remarks>This is a copy of Amazon.Runtime.StsRegionalEndpointsValue</remarks>
public enum StsRegionalEndpointsValue
{
/// <summary>
/// Send the request to the global sts endpoint
/// if the region is a legacy global region
/// </summary>
Legacy,
/// <summary>
/// Send the request to the regional endpoint
/// </summary>
Regional
}
/// <summary>
/// S3 US East 1 endpoint value determines whether or not
/// to send the us-east-1 s3 requests to the regional endpoint or to
/// the legacy global endpoint
/// </summary>
/// <remarks>This is a copy of Amazon.Runtime.S3UsEast1RegionalEndpointValue</remarks>
public enum S3UsEast1RegionalEndpointValue
{
/// <summary>
/// Sends the requests to the legacy global s3 endpoint for us-east-1
/// </summary>
Legacy,
/// <summary>
/// Sends the request to the regional s3 endpoint for us-east-1
/// </summary>
Regional
}
} | 133 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Json.LitJson;
namespace ServiceClientGenerator.DefaultConfiguration
{
public interface IDefaultConfigurationParser
{
/// <summary>
/// Parses the passed <paramref name="json"/> to populate a
/// <see cref="DefaultConfigurationModel"/>
/// </summary>
DefaultConfigurationModel Parse(string json);
}
public class DefaultConfigurationParser : IDefaultConfigurationParser
{
/// <inheritdoc />
public DefaultConfigurationModel Parse(string json)
{
try
{
var dataModel = JsonMapper.ToObject<SdkDefaultConfigurationJsonDataModel>(json);
return ConvertDataModel(dataModel);
}
catch (Exception e)
{
throw new Exception(
$"Error processing Default Configuration Json: {e.Message} \r\n\r\n" +
$"Json: \r\n{json}", e);
}
}
private DefaultConfigurationModel ConvertDataModel(SdkDefaultConfigurationJsonDataModel dataModel)
{
var modes =
dataModel
.documentation
.Modes
.Select(x => new
{
DocumentationModel = x,
ModeModel = dataModel.Modes.FirstOrDefault(m => m.Name == x.ModeName)
})
.Select(x =>
new DefaultConfigurationMode
{
Name = x.DocumentationModel.ModeName.ToPascalCase(),
Documentation = x.DocumentationModel.Documentation,
RetryMode =
ApplyModifiersEnum(
EnumParse<RequestRetryMode>([email protected]),
x.ModeModel.ModifiersForConfiguration(nameof(SdkDefaultConfigurationJsonDataModel.BaseConfig.retryMode))),
S3UsEast1RegionalEndpoint =
ApplyModifiersEnum(
EnumParse<S3UsEast1RegionalEndpointValue>([email protected]),
x.ModeModel.ModifiersForConfiguration(nameof(SdkDefaultConfigurationJsonDataModel.BaseConfig.s3UsEast1RegionalEndpoints))),
StsRegionalEndpoints =
ApplyModifiersEnum(
EnumParse<StsRegionalEndpointsValue>([email protected]),
x.ModeModel.ModifiersForConfiguration(nameof(SdkDefaultConfigurationJsonDataModel.BaseConfig.stsRegionalEndpoints))),
ConnectTimeout =
ApplyModifiersTimeSpan(
[email protected],
x.ModeModel.ModifiersForConfiguration(nameof(SdkDefaultConfigurationJsonDataModel.BaseConfig.connectTimeoutInMillis))),
TlsNegotiationTimeout =
ApplyModifiersTimeSpan(
[email protected],
x.ModeModel.ModifiersForConfiguration(nameof(SdkDefaultConfigurationJsonDataModel.BaseConfig.tlsNegotiationTimeoutInMillis))),
TimeToFirstByteTimeout =
ApplyModifiersTimeSpan(
[email protected],
x.ModeModel.ModifiersForConfiguration(nameof(SdkDefaultConfigurationJsonDataModel.BaseConfig.timeToFirstByteTimeoutInMillis))),
HttpRequestTimeout =
ApplyModifiersTimeSpan(
[email protected],
x.ModeModel.ModifiersForConfiguration(nameof(SdkDefaultConfigurationJsonDataModel.BaseConfig.httpRequestTimeoutInMillis)))
})
.ToList();
return new DefaultConfigurationModel
{
Modes = modes,
ConfigurationOptionDocumentation =
dataModel
.documentation
.Configuration
.ToDictionary(
kvp => kvp.ConfigurationName.ToUpperFirstCharacter(),
kvp => kvp.Documentation)
};
}
private TimeSpan? ApplyModifiersTimeSpan(int? baseTimeInMillis, IEnumerable<SdkDefaultConfigurationJsonDataModel.Modifier> modifiers)
{
modifiers = modifiers ?? Enumerable.Empty<SdkDefaultConfigurationJsonDataModel.Modifier>();
TimeSpan? workingValue =
baseTimeInMillis.HasValue
? (TimeSpan?) TimeSpan.FromMilliseconds(baseTimeInMillis.Value)
: null;
foreach (var modifier in modifiers)
{
switch (modifier.Operation)
{
case SdkDefaultConfigurationJsonDataModel.ModifierOperation.add:
workingValue = (workingValue ?? TimeSpan.Zero).Add(TimeSpan.FromMilliseconds(double.Parse(modifier.Value.ToString())));
break;
case SdkDefaultConfigurationJsonDataModel.ModifierOperation.multiply:
workingValue = TimeSpan.FromMilliseconds((workingValue?.TotalMilliseconds ?? 1) * double.Parse(modifier.Value.ToString()));
break;
case SdkDefaultConfigurationJsonDataModel.ModifierOperation.@override:
workingValue = TimeSpan.FromMilliseconds(double.Parse(modifier.Value.ToString()));
break;
default:
throw new ArgumentOutOfRangeException($"Error: Update switch statement to handle case [{modifier.Operation}]");
}
}
return workingValue;
}
private T ApplyModifiersEnum<T>(T baseValue, IEnumerable<SdkDefaultConfigurationJsonDataModel.Modifier> modifiers)
where T: struct
{
modifiers = modifiers ?? new SdkDefaultConfigurationJsonDataModel.Modifier[0];
var workingValue = baseValue;
foreach (var modifier in modifiers)
{
switch (modifier.Operation)
{
case SdkDefaultConfigurationJsonDataModel.ModifierOperation.@override:
workingValue = EnumParse<T>(modifier.Value?.ToString());
break;
case SdkDefaultConfigurationJsonDataModel.ModifierOperation.add:
case SdkDefaultConfigurationJsonDataModel.ModifierOperation.multiply:
throw new InvalidOperationException($"Can not apply Operation [{modifier.Operation}] to Enum");
default:
throw new ArgumentOutOfRangeException($"Error: Update switch statement to handle case [{modifier.Operation}]");
}
}
return workingValue;
}
private T EnumParse<T>(string s)
where T : struct
{
s = s ?? "";
if (Enum.TryParse<T>(s, ignoreCase: true, out var result))
return result;
throw new Exception(
$"Failed parsing [{s}] as [{typeof(T).Name}]. " +
$"Valid values are [{string.Join(",", Enum.GetNames(typeof(T)))}]");
}
}
} | 177 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Json.LitJson;
namespace ServiceClientGenerator.DefaultConfiguration
{
/// <summary>
/// Represents the sdk-default-configuration.json file so that it be serialized with
/// <see cref="JsonMapper.ToObject{T}(string)"/>
///
/// Also contains some helper conversions for navigating the deserialized model.
/// </summary>
/// <remarks>
/// See ServiceClientGeneratorTests.Content.sdk-default-configuration.json for example
/// </remarks>
internal class SdkDefaultConfigurationJsonDataModel
{
public int version { get; set; }
public BaseConfig @base { get; set; }
public ModesDictionary modes { get; set; }
public Documentation documentation { get; set; }
public Mode[] Modes =>
modes
.Select(x => new Mode
{
Name = x.Key,
Modifiers = x.Value.ToConfigurationModifiers()
})
.ToArray();
public class BaseConfig
{
public string retryMode { get; set; }
public string stsRegionalEndpoints { get; set; }
public string s3UsEast1RegionalEndpoints { get; set; }
public int? connectTimeoutInMillis { get; set; }
public int? tlsNegotiationTimeoutInMillis { get; set; }
public int? timeToFirstByteTimeoutInMillis { get; set; }
public int? httpRequestTimeoutInMillis { get; set; }
}
/// <summary>
/// Key is mode.Name
/// </summary>
public class ModesDictionary : Dictionary<string, ConfigurationModifiersDictionary> { }
[DebuggerDisplay("Mode {" + nameof(Name) + "}")]
public class Mode
{
public string Name { get; set; }
public ConfigurationModifiers[] Modifiers { get; set; }
}
/// <summary>
/// Key is the configuration, as defined in BaseConfig. Ie <see cref="BaseConfig.retryMode"/>
/// </summary>
public class ConfigurationModifiersDictionary : Dictionary<string, ModifierDictionary>
{
public ConfigurationModifiers[] ToConfigurationModifiers() =>
this
.Select(kvp => new ConfigurationModifiers
{
ConfigurationName = kvp.Key,
Modifiers = kvp.Value.ToModifiers()
})
.ToArray();
}
[DebuggerDisplay("Configuration {" + nameof(ConfigurationName) + "}")]
public class ConfigurationModifiers
{
/// <summary>
/// Configuration Name, as defined in BaseConfig. Ie <see cref="BaseConfig.retryMode"/>
/// </summary>
public string ConfigurationName { get; set; }
public Modifier[] Modifiers { get; set; }
}
public class ModifierDictionary : Dictionary<string, object>
{
public Modifier[] ToModifiers() =>
this
.Select(kvp => new Modifier
{
Operation = (ModifierOperation) Enum.Parse(typeof(ModifierOperation), kvp.Key),
Value = kvp.Value
})
.ToArray();
}
[DebuggerDisplay("{" +nameof(Operation) + "}: {" + nameof(Value) + "}")]
public class Modifier
{
public ModifierOperation Operation { get; set; }
public object Value { get; set; }
}
public enum ModifierOperation
{
/// <summary>
/// It specifies the factor to be multiplied by the value of the corresponding option under base
/// </summary>
multiply,
/// <summary>
/// It specifies the number to be added to the value of the corresponding option under base
/// </summary>
add,
/// <summary>
/// This value overrides the value of the corresponding option under base.
/// The type depends on the context - see the specific type being overridden in the base for the proper type.
/// </summary>
@override
}
public class Documentation
{
public Dictionary<string, string> modes { get; set; }
public DocumentationModeEntry[] Modes =>
modes
.Select(kvp => new DocumentationModeEntry
{
ModeName = kvp.Key,
Documentation = kvp.Value
})
.ToArray();
public Dictionary<string, string> configuration { get; set; }
public DocumentationConfigurationEntry[] Configuration =>
configuration
.Select(kvp => new DocumentationConfigurationEntry
{
ConfigurationName = kvp.Key,
Documentation = kvp.Value
})
.ToArray();
public class DocumentationModeEntry
{
/// <summary>
/// Equivalent to <see cref="Mode.Name"/>
/// </summary>
public string ModeName { get; set; }
public string Documentation { get; set; }
}
public class DocumentationConfigurationEntry
{
/// <summary>
/// Configuration Name, as defined in BaseConfig. Ie <see cref="BaseConfig.retryMode"/>
/// </summary>
public string ConfigurationName { get; set; }
public string Documentation { get; set; }
}
}
}
internal static class ModeExtensions
{
/// <summary>
/// Convenience method that gathers all <see cref="SdkDefaultConfigurationJsonDataModel.Modifier"/>s
/// that are associated with <paramref name="configurationName"/> into a single array.
/// </summary>
/// <param name="configurationName">
/// <see cref="SdkDefaultConfigurationJsonDataModel.ConfigurationModifiers.ConfigurationName"/>
/// </param>
public static SdkDefaultConfigurationJsonDataModel.Modifier[] ModifiersForConfiguration(
this SdkDefaultConfigurationJsonDataModel.Mode mode,
string configurationName)
{
return mode
?.Modifiers
.Where(m => m.ConfigurationName == configurationName)
.SelectMany(x => x.Modifiers)
.ToArray();
}
}
} | 182 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System;
using System.Linq;
namespace ServiceClientGenerator.Endpoints
{
/// <summary>
/// Object model for Function argument
/// </summary>
public class Argument
{
/// <summary>
/// Builds typed function argument from json data
/// </summary>
public static Argument BuildFrom(JsonData node)
{
if (node.IsBoolean)
{
return new BoolArgument { Value = (bool)node };
}
if (node.IsString)
{
return new StringArgument { Value = (string)node };
}
if (node.IsInt)
{
return new IntegerArgument { Value = (int)node };
}
if (node.IsObject)
{
if (node.PropertyNames.Contains("ref"))
{
return new ReferenceArgument() { ReferenceName = node.SafeGetString("ref") };
}
if (node.PropertyNames.Contains("fn"))
{
return new FunctionArgument { Value = new Function(node.SafeGetString("fn"), node["argv"], node.SafeGetString("assign")) };
}
}
throw new ArgumentException("Unknown argument type");
}
}
public class StringArgument : Argument
{
public string Value { get; set; }
}
public class IntegerArgument : Argument
{
public int Value { get; set; }
}
public class BoolArgument : Argument
{
public bool Value { get; set; }
}
public class ReferenceArgument : Argument
{
public string ReferenceName { get; set; }
}
public class FunctionArgument : Argument
{
public Function Value { get; set; }
}
}
| 65 |
aws-sdk-net | aws | C# | 
namespace ServiceClientGenerator.Endpoints
{
/// <summary>
/// Object model for ClientContextParameter
/// ClientContextParameter is used to extend ClientConfig with new properties
/// </summary>
public class ClientContextParameter
{
public string name { get; set; }
public string documentation { get; set; }
public string type { get; set; }
public string nativeType { get { return type.ToNativeType(); } }
}
}
| 16 |
aws-sdk-net | aws | C# | using System;
using System.Linq;
using System.Text;
namespace ServiceClientGenerator.Endpoints
{
using Json.LitJson;
using ServiceClientGenerator;
using ServiceClientGenerator.Endpoints.Partitions;
using System.Collections.Generic;
using System.Data;
/// <summary>
/// Translates Endpoints RuleSet to valid set of C# IF statements.
/// Every rule translates to IF(condition1 && condition2 && ...).
/// Tree rule translates to more inner IFs.
/// Every condition is a call to standard function, that can have multiple parameters including other function calls.
/// Condition can return a result that can be stored as internal reference which can be used in other rules/conditions.
/// Every final IF statement either returns an Endpoint or throws meaningful AmazonClientException.
/// </summary>
/// <example>
/// This shows example of generated code.
/// <code>
/// if (StringEquals(refs["Region"], "us-east-1") && BooleanEquals(refs["UseFIPS"], false) && BooleanEquals(refs["UseDualStack"], false))
/// {
/// return new Endpoint(Interpolate(@"{url#scheme}://{url#authority}{url#path}", refs));
/// }
/// </code>
/// </example>
public static class CodeGen
{
const int INITIAL_INDENT = 3;
const int INDENT_SIZE = 4;
/// <summary>
/// Translates Endpoints RuleSet to valid set of C# IF statements
/// </summary>
public static string GenerateRules(RuleSet rules)
{
var code = new StringBuilder();
foreach (Rule rule in rules.rules)
{
GenerateRule(rule, code, INITIAL_INDENT);
}
return code.ToString();
}
private static void GenerateRule(Rule rule, StringBuilder code, int indent)
{
const string AND = @" && ";
var codeIndent = new string(' ', indent * INDENT_SIZE);
var singleIndent = new string(' ', INDENT_SIZE);
var innerIndent = codeIndent;
var nonEmptyConditions = rule.conditions.Length > 0;
if (nonEmptyConditions)
{
code.Append($@"{codeIndent}if (");
foreach (var condition in rule.conditions)
{
GenerateStandardFunction(condition.Function, code, true);
code.Append(AND);
}
code.Remove(code.Length - AND.Length, AND.Length);
code.Append($@")");
code.AppendLine();
code.AppendLine($@"{codeIndent}{{");
innerIndent = codeIndent + singleIndent;
}
switch (rule.Type)
{
case RuleType.Error:
{
var value = MaybeInterpolate(rule.error);
code.AppendLine($@"{innerIndent}throw new AmazonClientException({value});");
break;
}
case RuleType.Endpoint:
{
string url = GenerateUrl(rule.endpoint.url);
var properties = rule.endpoint.properties != null ? rule.endpoint.properties.ToJson().SanitizeQuotes() : String.Empty;
var headers = rule.endpoint.headers != null ? rule.endpoint.headers.ToJson().SanitizeQuotes() : String.Empty;
code.AppendLine($@"{innerIndent}return new Endpoint({url}, InterpolateJson(@""{properties}"", refs), InterpolateJson(@""{headers}"", refs));");
break;
}
case RuleType.Tree:
{
foreach(var subRule in rule.rules)
{
GenerateRule(subRule, code, indent + (nonEmptyConditions ? 1 : 0));
}
break;
}
default: throw new Exception("Unknown rule type.");
}
if (nonEmptyConditions)
{
code.AppendLine($@"{codeIndent}}}");
}
}
/// <summary>
/// Url can be defined as template string | reference | function
/// </summary>
private static string GenerateUrl(JsonData url)
{
if (url.IsString)
{
return MaybeInterpolate((string)url);
}
if (url.IsObject)
{
if (url.PropertyNames.Contains("ref"))
{
return $"(string)refs[\"{url["ref"]}\"]";
}
if (url.PropertyNames.Contains("fn"))
{
var function = new StringBuilder();
GenerateStandardFunction(new Function((string)url["fn"], url["argv"]), function);
return $"(string){function}";
}
}
throw new Exception("Unknown Endpoint Url definition.");
}
private static string MaybeInterpolate(string s)
{
s = s.SanitizeQuotes();
return s.Contains('{') ? $@"Interpolate(@""{s}"", refs)" : $@"""{s}""";
}
private static void GenerateStandardFunction(Function function, StringBuilder code, bool isCondition = false)
{
const string COMMA_AND_SPACE = @", ";
if (!string.IsNullOrEmpty(function.Assign))
{
code.Append($@"(refs[""{function.Assign}""] = ");
}
switch (function.Name)
{
case "not":
{
code.Append(@"!");
GenerateFunctionArgument(function.Name, 0, function.Arguments[0], code);
break;
}
default:
{
code.Append($@"{GetFunctionName(function.Name)}(");
for (int i = 0; i < function.Arguments.Count; i++)
{
var arg = function.Arguments[i];
GenerateFunctionArgument(function.Name, i, arg, code);
code.Append(COMMA_AND_SPACE);
}
code.Remove(code.Length - COMMA_AND_SPACE.Length, COMMA_AND_SPACE.Length);
code.Append(@")");
break;
}
}
if (!string.IsNullOrEmpty(function.Assign))
{
code.Append(@") != null");
}
else if (isCondition && !IsBooleanFunction(function.Name))
{
code.Append(@" != null");
}
}
private static string GetFunctionName(string name)
{
if (name == "stringEquals" || name == "booleanEquals") return "Equals";
return name.Replace("aws.", "").ToUpperFirstCharacter();
}
private static bool IsBooleanFunction(string name)
{
switch (name)
{
case "not":
case "isSet":
case "stringEquals":
case "booleanEquals":
case "isValidHostLabel":
case "aws.isVirtualHostableS3Bucket":
return true;
default:
return false;
}
}
// functions parameter types
private static Dictionary<string, List<string>> functionParamTypes = new Dictionary<string, List<string>>
{
["aws.partition"] = new List<string> { "string" },
["aws.parseArn"] = new List<string> { "string" },
["aws.isVirtualHostableS3Bucket"] = new List<string> { "string", "bool" },
["isValidHostLabel"] = new List<string> { "string", "bool" },
["parseURL"] = new List<string> { "string" },
["uriEncode"] = new List<string> { "string" },
["substring"] = new List<string> { "string", "int", "int", "bool" }
};
private static void GenerateFunctionArgument(string functionName, int argumentIndex, Argument argument, StringBuilder code)
{
switch (argument)
{
case StringArgument arg:
{
var value = MaybeInterpolate(arg.Value);
code.Append($"{value}");
break;
}
case IntegerArgument arg:
{
code.Append($"{arg.Value}");
break;
}
case BoolArgument arg:
{
code.Append($"{arg.Value.ToString().ToLower()}"); // true | false
break;
}
case ReferenceArgument arg:
{
AddTypeCast(functionName, argumentIndex, code);
code.Append($@"refs[""{arg.ReferenceName}""]");
break;
}
case FunctionArgument arg:
{
AddTypeCast(functionName, argumentIndex, code);
GenerateStandardFunction(arg.Value, code);
break;
}
default: throw new Exception("Unknown argument type.");
}
}
private static void AddTypeCast(string functionName, int argumentIndex, StringBuilder code)
{
if (functionParamTypes.ContainsKey(functionName))
{
var argumentType = functionParamTypes[functionName][argumentIndex];
code.Append($@"({argumentType})");
}
}
}
}
| 261 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceClientGenerator.Endpoints
{
/// <summary>
/// Object model for Condition.
/// </summary>
public class Condition
{
/// <summary>
/// Standard function name (lower-case)
/// </summary>
public string fn { get; set; }
/// <summary>
/// Standard function arguments
/// </summary>
public JsonData argv { get; set; }
private Function _function;
/// <summary>
/// Object model for standard function
/// </summary>
public Function Function
{
get
{
if (_function == null)
{
_function = new Function(fn, argv, assign);
}
return _function;
}
}
/// <summary>
/// Name of the internal reference you can assign function result to.
/// This reference can be used in other ruleset conditions/functions as a parameter.
/// </summary>
public string assign { get; set; }
}
}
| 47 |
aws-sdk-net | aws | C# | namespace ServiceClientGenerator.Endpoints
{
/// <summary>
/// Object model for ContextParameter
/// ContextParameter is used to map operation parameter value to ruleset parameter
/// </summary>
public class ContextParameter
{
public string name { get; set; }
}
}
| 12 |
aws-sdk-net | aws | C# | namespace ServiceClientGenerator.Endpoints
{
/// <summary>
/// Object model for Endpoints Parameter's deprecated attribute
/// Used to mark parameter as [Obsolete]
/// </summary>
public class Deprecated
{
/// <summary>
/// Deprecation message
/// </summary>
public string message { get; set; }
/// <summary>
/// Deprecated since
/// </summary>
public string since { get; set; }
}
}
| 19 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System.Collections.Generic;
namespace ServiceClientGenerator.Endpoints
{
/// <summary>
/// Object model for Endpoint data
/// </summary>
public class EndpointData
{
/// <summary>
/// Endpoint URL
/// </summary>
public JsonData url { get; set; }
/// <summary>
/// Property bag for various properties assosiated with Endpoint
/// </summary>
public JsonData properties { get; set; }
/// <summary>
/// Set of headers required for Endpoint
/// </summary>
public JsonData headers { get; set; }
}
}
| 25 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System.Collections.Generic;
namespace ServiceClientGenerator.Endpoints
{
/// <summary>
/// Object model for Function
/// </summary>
public class Function
{
public Function(string name, JsonData arguments, string assign = null)
{
Name = name;
foreach (JsonData arg in arguments)
{
Arguments.Add(Argument.BuildFrom(arg));
}
Assign = assign;
}
public string Name { get; set; }
public List<Argument> Arguments { get; set; } = new List<Argument>(); // string value | boolean value | Reference | Function
/// <summary>
/// Assign function to internal reference which can be used in other ruleset conditions
/// </summary>
public string Assign { get; set; }
}
}
| 31 |
aws-sdk-net | aws | C# | using Json.LitJson;
namespace ServiceClientGenerator.Endpoints
{
/// <summary>
/// Object model for Endpoints Parameter
/// </summary>
public class Parameter
{
/// <summary>
/// Parameter type
/// </summary>
public string type { get; set; }
/// <summary>
/// Parameter builtIn type
/// </summary>
public string builtIn { get; set; }
/// <summary>
/// Parameter default value
/// </summary>
public JsonData @default { get; set; }
/// <summary>
/// Parameter required
/// </summary>
public bool required { get; set; }
/// <summary>
/// Parameter documentation
/// </summary>
public string documentation { get; set; }
/// <summary>
/// Parameter deprecation information
/// </summary>
public Deprecated deprecated { get; set; }
/// <summary>
/// Native C# value for parameter's default value
/// </summary>
public string DefaultValue
{
get
{
if (@default == null) return null;
if (@default.IsBoolean) return ((bool)@default).ToString().ToLower(); // true | false
if (@default.IsString) return $@"""{@default}""";
return null;
}
}
}
}
| 50 |
aws-sdk-net | aws | C# | using System;
namespace ServiceClientGenerator.Endpoints
{
/// <summary>
/// Rule Types
/// </summary>
public enum RuleType
{
/// <summary>
/// Rule resolves to error
/// </summary>
Error,
/// <summary>
/// Rule resolves to endpoint
/// </summary>
Endpoint,
/// <summary>
/// Rule delegates resolution to inner (tree) rules
/// </summary>
Tree
}
/// <summary>
/// Object model for Endpoints Rule
/// </summary>
public class Rule
{
/// <summary>
/// Rule type raw value
/// </summary>
public string type { get; set; }
/// <summary>
/// Rule type
/// </summary>
public RuleType Type
{
get
{
switch (type.ToLower())
{
case "tree": return RuleType.Tree;
case "endpoint": return RuleType.Endpoint;
case "error": return RuleType.Error;
default: throw new Exception("Unknown rule type.");
}
}
}
/// <summary>
/// Rule documentation
/// </summary>
public string documentation { get; set; }
/// <summary>
/// Set of conditions for a rule.
/// Rule is resolved when all conditions are met (logical AND)
/// Rule can be resolved into endpoint, error or delegate resolution to other inner rules (tree rule)
/// </summary>
public Condition[] conditions { get; set; }
/// <summary>
/// Rule resolves to an endpoint
/// </summary>
public EndpointData endpoint { get; set; }
/// <summary>
/// Rule resolves to an error
/// </summary>
public string error { get; set; }
/// <summary>
/// Rule delegates final resolution to inner (tree) rules
/// </summary>
public Rule[] rules { get; set; }
}
}
| 79 |
aws-sdk-net | aws | C# | using System.Collections.Generic;
namespace ServiceClientGenerator.Endpoints
{
/// <summary>
/// Object model for Endpoints RuleSet
/// </summary>
public class RuleSet
{
/// <summary>
/// RuleSet version
/// </summary>
public string version { get; set; }
/// <summary>
/// RuleSet applies to ServiceId
/// </summary>
public string serviceId { get; set; }
/// <summary>
/// Set of RuleSet parameters
/// </summary>
public Dictionary<string, Parameter> parameters { get; set; }
/// <summary>
/// Set of RuleSet rules
/// </summary>
public Rule[] rules { get; set; }
}
}
| 28 |
aws-sdk-net | aws | C# | using Json.LitJson;
namespace ServiceClientGenerator.Endpoints
{
/// <summary>
/// Object model for StaticContextParameter
/// StaticContextParameter used to map static value from service operation to ruleset parameter
/// </summary>
public class StaticContextParameter
{
/// <summary>
/// Parameter name
/// </summary>
public string name { get; set; }
/// <summary>
/// Parameter value
/// </summary>
public JsonData value { get; set; }
/// <summary>
/// Parameter native C# value
/// </summary>
public string nativeValue { get { return value.ToNativeValue(); } }
}
}
| 27 |
aws-sdk-net | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 Json.LitJson;
using System.Collections.Generic;
namespace ServiceClientGenerator.Endpoints.Partitions
{
/// <summary>
/// Object model for json partition data.
/// </summary>
public class Partition
{
public string id { get; set; }
public string regionRegex { get; set; }
public Dictionary<string, JsonData> regions { get; set; }
public PartitionAttributes outputs { get; set; }
}
} | 30 |
aws-sdk-net | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
namespace ServiceClientGenerator.Endpoints.Partitions
{
/// <summary>
/// Object model for json partition attributes data.
/// </summary>
public class PartitionAttributes
{
public string name { get; set; }
public string dnsSuffix { get; set; }
public string dualStackDnsSuffix { get; set; }
public bool supportsFIPS { get; set; }
public bool supportsDualStack { get; set; }
}
} | 29 |
aws-sdk-net | aws | C# | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.Collections.Generic;
namespace ServiceClientGenerator.Endpoints.Partitions
{
/// <summary>
/// Object model for json partitions data.
/// </summary>
public class Partitions
{
public string version { get; set; }
public List<Partition> partitions { get; set; }
}
}
| 28 |
aws-sdk-net | aws | C# | namespace ServiceClientGenerator.Endpoints.Tests
{
/// <summary>
/// Object model for AuthSchema.
/// </summary>
public class AuthSchema
{
public string signingName { get; set; }
public bool disableDoubleEncoding { get; set; }
public string name { get; set; }
public string signingRegion { get; set; }
public string[] signingRegionSet { get; set; }
}
} | 14 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System.Collections.Generic;
namespace ServiceClientGenerator.Endpoints.Tests
{
/// <summary>
/// Object model for Endpoint.
/// </summary>
public class Endpoint
{
public string url { get; set; }
public EndpointProperties properties { get; set; }
public JsonData headers { get; set; }
}
}
| 16 |
aws-sdk-net | aws | C# | namespace ServiceClientGenerator.Endpoints.Tests
{
/// <summary>
/// Object model for EndpointProperties.
/// </summary>
public class EndpointProperties
{
public AuthSchema[] authSchemes { get; set; }
}
} | 10 |
aws-sdk-net | aws | C# | namespace ServiceClientGenerator.Endpoints.Tests
{
/// <summary>
/// Object model for EndpointTests.
/// </summary>
public class EndpointTests
{
public string service { get; set; }
public string version { get; set; }
public Test[] testCases { get; set; }
}
}
| 13 |
aws-sdk-net | aws | C# | using Json.LitJson;
namespace ServiceClientGenerator.Endpoints.Tests
{
/// <summary>
/// Object model for Expectation.
/// </summary>
public class Expectation
{
public Endpoint endpoint { get; set; }
public string error { get; set; }
}
} | 13 |
aws-sdk-net | aws | C# | using Json.LitJson;
using System.Collections.Generic;
namespace ServiceClientGenerator.Endpoints.Tests
{
/// <summary>
/// Object model for Test.
/// </summary>
public class Test
{
public string documentation { get; set; }
public Dictionary<string, JsonData> @params { get; set; }
public string[] tags { get; set; }
public Expectation expect { get; set; }
public List<JsonData> operationInputs { get; set; }
}
}
| 18 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators
{
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using ServiceClientGenerator.DefaultConfiguration;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class BaseGenerator : BaseGeneratorBase
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public virtual string TransformText()
{
this.Write("\r\n\r\n");
return this.GenerationEnvironment.ToString();
}
#line 10 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
// An object that contains all the information about a service
public ServiceConfiguration Config { get; set; }
/// <summary>
/// Model representing the default configuration modes as built
/// from the sdk-default-configurations.json file.
/// </summary>
public DefaultConfigurationModel DefaultConfigurationModel { get; set; }
// Adds the Amazon Apache 2.0 license
public void AddLicenseHeader()
{
#line default
#line hidden
#line 23 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(@"/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the ""License"").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the ""license"" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the ");
#line default
#line hidden
#line 40 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(Path.GetFileName(this.Config.ModelPath)));
#line default
#line hidden
#line 40 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" service model.\r\n */\r\n");
#line default
#line hidden
#line 42 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
// Adds documentation to the begin operation based on the name
public void AddBeginAsyncDocumentation(Operation operation)
{
#line default
#line hidden
#line 48 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <summary>\r\n /// Initiates the asynchronous execution of the ");
#line default
#line hidden
#line 50 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 50 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" operation.\r\n /// </summary>\r\n /// \r\n /// <param name=\"reque" +
"st\">Container for the necessary parameters to execute the ");
#line default
#line hidden
#line 53 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 53 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" operation on Amazon");
#line default
#line hidden
#line 53 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
#line 53 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(@"Client.</param>
/// <param name=""callback"">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name=""state"">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking End");
#line default
#line hidden
#line 58 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 58 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\r\n /// operation.</returns>\r\n");
#line default
#line hidden
#line 60 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
if(!string.IsNullOrEmpty(operation.RestAPIDocUrl))
{
#line default
#line hidden
#line 63 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <seealso href=\"");
#line default
#line hidden
#line 64 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.RestAPIDocUrl));
#line default
#line hidden
#line 64 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\">REST API Reference for ");
#line default
#line hidden
#line 64 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 64 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" Operation</seealso>\r\n");
#line default
#line hidden
#line 65 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
}
// Generates the end operation async documentation
public void AddEndAsyncDocumentation(Operation operation)
{
#line default
#line hidden
#line 72 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <summary>\r\n /// Finishes the asynchronous execution of the ");
#line default
#line hidden
#line 74 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 74 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" operation.\r\n /// </summary>\r\n /// \r\n /// <param name=\"async" +
"Result\">The IAsyncResult returned by the call to Begin");
#line default
#line hidden
#line 77 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 77 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(".</param>\r\n /// \r\n /// <returns>Returns a ");
#line default
#line hidden
#line 79 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 79 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("Result from ");
#line default
#line hidden
#line 79 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
#line 79 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(".</returns>\r\n");
#line default
#line hidden
#line 80 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
if(!string.IsNullOrEmpty(operation.RestAPIDocUrl))
{
#line default
#line hidden
#line 83 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <seealso href=\"");
#line default
#line hidden
#line 84 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.RestAPIDocUrl));
#line default
#line hidden
#line 84 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\">REST API Reference for ");
#line default
#line hidden
#line 84 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 84 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" Operation</seealso>\r\n");
#line default
#line hidden
#line 85 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
}
// Generates Client documentation
public void FormatServiceClientDocumentation(string documentation)
{
documentation = CleanupDocumentation(documentation);
#line default
#line hidden
#line 93 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <summary>\r\n /// Implementation for accessing ");
#line default
#line hidden
#line 95 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
#line 95 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\r\n ///\r\n");
#line default
#line hidden
#line 97 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
WriteCommentBlock(" ", documentation);
#line default
#line hidden
#line 99 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// </summary>\r\n");
#line default
#line hidden
#line 101 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
// Generates interface documentation
public void FormatServiceInterfaceDocumentation(string documentation)
{
documentation = CleanupDocumentation(documentation);
#line default
#line hidden
#line 108 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <summary>\r\n /// Interface for accessing ");
#line default
#line hidden
#line 110 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
#line 110 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\r\n ///\r\n");
#line default
#line hidden
#line 112 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
WriteCommentBlock(" ", documentation);
#line default
#line hidden
#line 114 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// </summary>\r\n");
#line default
#line hidden
#line 116 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
// Adds documentation to the class based on the shape
public void FormatClassDocumentation(Shape structure)
{
if(structure == null)
{
#line default
#line hidden
#line 124 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <summary>\r\n\t/// Empty class reserved for future use.\r\n /// </summary>\r" +
"\n");
#line default
#line hidden
#line 128 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
return;
}
var documentation = CleanupDocumentation(structure.Documentation);
#line default
#line hidden
#line 132 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <summary>\r\n");
#line default
#line hidden
#line 134 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
WriteCommentBlock(" ", documentation);
#line default
#line hidden
#line 136 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// </summary>\r\n");
#line default
#line hidden
#line 138 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
// Adds documentation to the members of a structure
public void FormatPropertyDocumentation(Member member, string documentationPreface = "")
{
if (documentationPreface != null && documentationPreface != "")
{
if (!documentationPreface.EndsWith("."))
{
documentationPreface += ".";
}
documentationPreface = "<p>" + documentationPreface + "</p> ";
}
var documentation = CleanupDocumentation(string.Format("Gets and sets the property {0}. {1}{2}", member.PropertyName, documentationPreface, member.Documentation));
#line default
#line hidden
#line 154 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <summary>\r\n");
#line default
#line hidden
#line 156 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
WriteCommentBlock(" ", documentation);
#line default
#line hidden
#line 158 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// </summary>\r\n");
#line default
#line hidden
#line 160 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
public void FormatOperationDocumentationSync(Operation operation, bool includeRequest)
{
FormatOperationDocumentationHelper(operation, includeRequest, false);
}
public void FormatOperationDocumentationAsync(Operation operation, bool includeRequest)
{
FormatOperationDocumentationHelper(operation, includeRequest, true);
}
// Documents the operation in a client or interface and optionally includes request param
private void FormatOperationDocumentationHelper(Operation operation, bool includeRequest, bool isAsync)
{
var documentation = CleanupDocumentation(operation.Documentation);
#line default
#line hidden
#line 178 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\r\n /// <summary>\r\n");
#line default
#line hidden
#line 181 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
WriteCommentBlock(" ", documentation);
#line default
#line hidden
#line 183 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// </summary>\r\n");
#line default
#line hidden
#line 185 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
if (includeRequest)
{
#line default
#line hidden
#line 188 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <param name=\"request\">Container for the necessary parameters to execu" +
"te the ");
#line default
#line hidden
#line 189 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 189 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" service method.</param>\r\n");
#line default
#line hidden
#line 190 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
if (isAsync)
{
// follows Async Pattern
#line default
#line hidden
#line 196 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <param name=\"cancellationToken\">\r\n /// A cancellation toke" +
"n that can be used by other objects or threads to receive notice of cancellation" +
".\r\n /// </param>\r\n");
#line default
#line hidden
#line 200 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
#line default
#line hidden
#line 202 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// \r\n /// <returns>The response from the ");
#line default
#line hidden
#line 204 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 204 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" service method, as returned by ");
#line default
#line hidden
#line 204 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
#line 204 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(".</returns>\r\n");
#line default
#line hidden
#line 205 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
// Skip adding exceptions in the ndoc because we are not generating exceptions from the service model.
if(this.Config.Namespace != "Amazon.S3")
{
foreach(var exception in operation.Exceptions)
{
this.FormatExceptionDocumentation(exception);
}
}
if(!string.IsNullOrEmpty(operation.RestAPIDocUrl))
{
#line default
#line hidden
#line 217 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <seealso href=\"");
#line default
#line hidden
#line 218 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.RestAPIDocUrl));
#line default
#line hidden
#line 218 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\">REST API Reference for ");
#line default
#line hidden
#line 218 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 218 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" Operation</seealso>\r\n");
#line default
#line hidden
#line 219 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
}
// Generates operation documentation with a param tag for each member in the list
public void FormatOperationDocumentation(Operation operation, List<Member> members, bool isSync)
{
var documentation = CleanupDocumentation(operation.Documentation);
#line default
#line hidden
#line 228 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\r\n /// <summary>\r\n");
#line default
#line hidden
#line 231 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
WriteCommentBlock(" ", documentation);
#line default
#line hidden
#line 233 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// </summary>\r\n");
#line default
#line hidden
#line 235 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
foreach(var item in members)
{
#line default
#line hidden
#line 237 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <param name=\"");
#line default
#line hidden
#line 238 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(GeneratorHelpers.CamelCaseParam(item.PropertyName)));
#line default
#line hidden
#line 238 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\">");
#line default
#line hidden
#line 238 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(item.GetParamDocumentationForOperation(operation.Name)));
#line default
#line hidden
#line 238 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("</param>\r\n");
#line default
#line hidden
#line 239 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
if (!isSync)
{
#line default
#line hidden
#line 243 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <param name=\"cancellationToken\">\r\n /// A cancellation toke" +
"n that can be used by other objects or threads to receive notice of cancellation" +
".\r\n /// </param>\r\n");
#line default
#line hidden
#line 247 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
#line default
#line hidden
#line 249 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// \r\n /// <returns>The response from the ");
#line default
#line hidden
#line 251 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 251 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" service method, as returned by ");
#line default
#line hidden
#line 251 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
#line 251 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(".</returns>\r\n");
#line default
#line hidden
#line 252 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
if (!this.Config.ServiceModel.Customizations.SuppressSimpleMethodExceptionDocs)
{
foreach(var exception in operation.Exceptions)
{
this.FormatExceptionDocumentation(exception);
}
}
if(!string.IsNullOrEmpty(operation.RestAPIDocUrl))
{
#line default
#line hidden
#line 263 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <seealso href=\"");
#line default
#line hidden
#line 264 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.RestAPIDocUrl));
#line default
#line hidden
#line 264 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\">REST API Reference for ");
#line default
#line hidden
#line 264 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 264 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" Operation</seealso>\r\n");
#line default
#line hidden
#line 265 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
}
public void FormatOperationRequestDocumentation(Operation operation)
{
var documentation = CleanupDocumentation(operation.Documentation);
#line default
#line hidden
#line 272 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\t/// <summary>\r\n\t/// Container for the parameters to the ");
#line default
#line hidden
#line 274 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 274 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" operation.\r\n");
#line default
#line hidden
#line 275 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
WriteCommentBlock(" ", documentation);
#line default
#line hidden
#line 277 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\t/// </summary>\r\n");
#line default
#line hidden
#line 279 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
// Generates documentation for an exception, added to operation documentation
public void FormatExceptionDocumentation(ExceptionShape exceptionShape)
{
var documentation = CleanupDocumentation(exceptionShape.Documentation);
#line default
#line hidden
#line 287 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <exception cref=\"");
#line default
#line hidden
#line 288 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
#line 288 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(".Model.");
#line default
#line hidden
#line 288 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exceptionShape.Name));
#line default
#line hidden
#line 288 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\">\r\n");
#line default
#line hidden
#line 289 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
WriteCommentBlock(" ", documentation);
#line default
#line hidden
#line 291 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// </exception>\r\n");
#line default
#line hidden
#line 293 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
// Generates documentation for a result that is empty
public void FormatVoidResultDocumentation(string operationName)
{
#line default
#line hidden
#line 299 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\t/// <summary>\r\n\t///\tReturns information about the ");
#line default
#line hidden
#line 301 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operationName));
#line default
#line hidden
#line 301 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" response metadata.\r\n\t///\tThe ");
#line default
#line hidden
#line 302 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operationName));
#line default
#line hidden
#line 302 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" operation has a void result type.\r\n\t/// </summary>\r\n");
#line default
#line hidden
#line 304 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
// Writes a block for an xml comment with correct line endings
// Every \n (new line) in the block is written on a new line of the block
private void WriteCommentBlock(string spaceBlock, string block)
{
foreach(var line in block.Split('\n'))
{
this.Write("{0}/// {1}\r\n", spaceBlock, line);
}
}
// Removes unneccesary tags from the documentation and formats paragraph tags correctly
public string CleanupDocumentation(string documentation)
{
documentation = documentation
.Replace("\r", "")
.Replace("\n", "")
.Replace("<br>", "")
.Replace("<p>", "\n<para>\n")
.Replace("</p>", "\n</para>\n")
.Replace("<fullname>", "")
.Replace("</fullname>", "")
.Replace("<function>", "")
.Replace("</function>","")
.Replace("<p/>","")
.Trim();
// Remove examples because these will be wire protocol examples
documentation = RemoveSnippets(documentation, "<examples>", "</examples>");
// Remove commented out documentation
documentation = RemoveSnippets(documentation, "<!--", "-->");
documentation = RemoveSnippets(documentation, "<!--", "-->");
documentation = RemoveSnippets(documentation, "<?oxy_delete",">");
documentation = RemoveSnippets(documentation, "<?oxy_insert_start",">");
documentation = RemoveSnippets(documentation, "<?oxy_insert_end",">");
// Remove the first para tags since it just be the first paragraph in the summary.
// This also helps clean up documentation that only contains one para block.
if(documentation.StartsWith("<para>"))
{
int closePos= documentation.IndexOf("</para>");
if (closePos < 0)
// note: documentation was transformed a few lines above
throw new Exception("Documentation is missing closing tag (ie </p> or </para>): " + documentation);
var firstParaContent= documentation.Substring("<para>".Length, closePos - "<para>".Length);
documentation = firstParaContent + documentation.Substring(closePos + "</para>".Length);
}
// Insert line breaks around 80 character line length
StringBuilder sb = new StringBuilder();
int position = 0;
int currentLineLength = 0;
while(position < documentation.Length)
{
char c = documentation[position];
if(c == '\n')
{
currentLineLength = 0;
sb.Append(c);
}
else if(c == ' ' && currentLineLength > 80)
{
currentLineLength = 0;
sb.Append("\n");
}
else
{
currentLineLength++;
sb.Append(c);
}
position++;
}
return sb.ToString().Trim();
}
private string RemoveSnippets(string documentation, string startToken, string endToken)
{
int startPos = documentation.IndexOf(startToken);
while(startPos != -1)
{
int closePos = documentation.IndexOf(endToken, startPos);
documentation = documentation.Substring(0, startPos) + documentation.Substring(closePos + endToken.Length);
startPos = documentation.IndexOf(startToken);
}
return documentation;
}
// Generates the comment block for simple constructors, each member is added as a param tag with the shape's documentation or
// a generic comment if no documentation is found
public void FormatSimpleConstructorDocumentation(string className, IList<Member> members)
{
#line default
#line hidden
#line 407 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <summary>\r\n /// Instantiates ");
#line default
#line hidden
#line 409 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(className));
#line default
#line hidden
#line 409 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" with the parameterized properties\r\n /// </summary>\r\n");
#line default
#line hidden
#line 411 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
foreach (var member in members)
{
#line default
#line hidden
#line 414 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <param name=\"");
#line default
#line hidden
#line 415 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(GeneratorHelpers.CamelCaseParam(member.PropertyName)));
#line default
#line hidden
#line 415 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\">");
#line default
#line hidden
#line 415 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.GetParamDocumentationForConstructor(className)));
#line default
#line hidden
#line 415 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("</param>\r\n");
#line default
#line hidden
#line 416 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
}
#line default
#line hidden
#line 421 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
// Generates methods for the client that have request members as parameters for easy calls to the operation
// Only generates them if they are specified in the customizations of the service
public void AddSimpleClientMethods(Operation operation, bool isSync)
{
if (this.Config.ServiceModel.Customizations.SimpleMethodsModel.CreateSimpleMethods(operation.Name))
{
var forms = this.Config.ServiceModel.Customizations.SimpleMethodsModel.SimpleMethods[operation.Name].Forms;
var members = this.Config.ServiceModel.FindShape(operation.RequestStructure.Name).Members;
foreach (var form in forms)
{
string currentParams = this.Config.ServiceModel.Customizations.SimpleMethodsModel.GetSimpleParameters(form, members);
var docMembers = this.Config.ServiceModel.Customizations.SimpleMethodsModel.GetFormMembers(form, members);
this.FormatOperationDocumentation(operation, docMembers, isSync);
if (isSync)
{
if(operation.IsDeprecated)
{
#line default
#line hidden
#line 441 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\t\t[Obsolete(\"");
#line default
#line hidden
#line 442 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.DeprecationMessage));
#line default
#line hidden
#line 442 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\")]\r\n");
#line default
#line hidden
#line 443 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
#line default
#line hidden
#line 445 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" public virtual ");
#line default
#line hidden
#line 446 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 446 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("Response ");
#line default
#line hidden
#line 446 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 446 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("(");
#line default
#line hidden
#line 446 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(currentParams));
#line default
#line hidden
#line 446 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(")\r\n");
#line default
#line hidden
#line 447 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
else
{
if (!string.IsNullOrEmpty(currentParams))
currentParams += ", ";
if(operation.IsDeprecated)
{
#line default
#line hidden
#line 455 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\t\t[Obsolete(\"");
#line default
#line hidden
#line 456 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.DeprecationMessage));
#line default
#line hidden
#line 456 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\")]\r\n");
#line default
#line hidden
#line 457 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
#line default
#line hidden
#line 459 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" public virtual Task<");
#line default
#line hidden
#line 460 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 460 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("Response> ");
#line default
#line hidden
#line 460 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 460 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("Async(");
#line default
#line hidden
#line 460 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(currentParams));
#line default
#line hidden
#line 460 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("System.Threading.CancellationToken cancellationToken = default(CancellationToken)" +
")\r\n");
#line default
#line hidden
#line 461 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
#line default
#line hidden
#line 463 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" {\r\n var request = new ");
#line default
#line hidden
#line 465 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 465 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("Request();\r\n");
#line default
#line hidden
#line 466 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
foreach (var member in docMembers)
{
#line default
#line hidden
#line 469 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" request.");
#line default
#line hidden
#line 470 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 470 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" = ");
#line default
#line hidden
#line 470 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(GeneratorHelpers.CamelCaseParam(member.PropertyName)));
#line default
#line hidden
#line 470 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(";\r\n");
#line default
#line hidden
#line 471 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
if (isSync)
{
#line default
#line hidden
#line 476 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" return ");
#line default
#line hidden
#line 477 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 477 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("(request);\r\n");
#line default
#line hidden
#line 478 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
else
{
#line default
#line hidden
#line 482 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" return ");
#line default
#line hidden
#line 483 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 483 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("Async(request, cancellationToken);\r\n");
#line default
#line hidden
#line 484 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
#line default
#line hidden
#line 486 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" }\r\n\r\n");
#line default
#line hidden
#line 489 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
}
}
#line default
#line hidden
#line 494 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
// Generates methods for the interface that have request members as parameters for easy calls to the operation
// Only generates them if they are specified in the customizations of the service
public void AddSimpleClientMethodInterfaces(Operation operation, bool isSync)
{
if (this.Config.ServiceModel.Customizations.SimpleMethodsModel.CreateSimpleMethods(operation.Name))
{
var forms = this.Config.ServiceModel.Customizations.SimpleMethodsModel.SimpleMethods[operation.Name].Forms;
var members = this.Config.ServiceModel.FindShape(operation.RequestStructure.Name).Members;
foreach (var form in forms)
{
string currentParams = this.Config.ServiceModel.Customizations.SimpleMethodsModel.GetSimpleParameters(form, members);
var docMembers = this.Config.ServiceModel.Customizations.SimpleMethodsModel.GetFormMembers(form, members);
this.FormatOperationDocumentation(operation, docMembers, isSync);
if (isSync)
{
if(operation.IsDeprecated)
{
#line default
#line hidden
#line 514 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\t\t[Obsolete(\"");
#line default
#line hidden
#line 515 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.DeprecationMessage));
#line default
#line hidden
#line 515 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\")]\r\n");
#line default
#line hidden
#line 516 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
#line default
#line hidden
#line 518 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" ");
#line default
#line hidden
#line 519 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 519 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("Response ");
#line default
#line hidden
#line 519 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 519 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("(");
#line default
#line hidden
#line 519 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(currentParams));
#line default
#line hidden
#line 519 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 520 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
else
{
if (!string.IsNullOrEmpty(currentParams))
currentParams += ", ";
if(operation.IsDeprecated)
{
#line default
#line hidden
#line 528 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\t\t[Obsolete(\"");
#line default
#line hidden
#line 529 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.DeprecationMessage));
#line default
#line hidden
#line 529 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("\")]\r\n");
#line default
#line hidden
#line 530 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
#line default
#line hidden
#line 532 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" Task<");
#line default
#line hidden
#line 533 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 533 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("Response> ");
#line default
#line hidden
#line 533 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
#line 533 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("Async(");
#line default
#line hidden
#line 533 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(currentParams));
#line default
#line hidden
#line 533 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("System.Threading.CancellationToken cancellationToken = default(CancellationToken)" +
");\r\n");
#line default
#line hidden
#line 534 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
}
}
}
#line default
#line hidden
#line 541 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
// Generates constructors for operation requests that have request members in the parameters for easy creation of requests
// Only generates them if they are specified in the customizations of the service
public void AddSimpleRequestConstructors(string className, Shape structure, string nameSpace)
{
if (this.Config.ServiceModel.Customizations.SimpleConstructorsModel.CreateSimpleConstructors(className))
{
var forms = this.Config.ServiceModel.Customizations.SimpleConstructorsModel.SimpleConstructors[className].Forms;
var members = structure.Members;
#line default
#line hidden
#line 550 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" /// <summary>\r\n /// Empty constructor used to set properties inde" +
"pendently even when a simple constructor is available\r\n /// </summary>\r\n " +
" public ");
#line default
#line hidden
#line 553 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(className));
#line default
#line hidden
#line 553 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("() { }\r\n\r\n");
#line default
#line hidden
#line 555 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
foreach (var form in forms)
{
string currentParams = this.Config.ServiceModel.Customizations.SimpleConstructorsModel.GetSimpleParameters(form, members);
var docMembers = this.Config.ServiceModel.Customizations.SimpleConstructorsModel.GetFormMembers(form, members);
#line default
#line hidden
#line 561 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
FormatSimpleConstructorDocumentation(className, docMembers);
#line default
#line hidden
#line 561 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" public ");
#line default
#line hidden
#line 562 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(className));
#line default
#line hidden
#line 562 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write("(");
#line default
#line hidden
#line 562 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(currentParams));
#line default
#line hidden
#line 562 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(")\r\n {\r\n");
#line default
#line hidden
#line 564 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
foreach (var member in docMembers)
{
#line default
#line hidden
#line 567 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" ");
#line default
#line hidden
#line 568 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.VariableName));
#line default
#line hidden
#line 568 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" = ");
#line default
#line hidden
#line 568 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(GeneratorHelpers.CamelCaseParam(member.PropertyName)));
#line default
#line hidden
#line 568 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(";\r\n");
#line default
#line hidden
#line 569 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
#line default
#line hidden
#line 572 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
this.Write(" }\r\n\r\n");
#line default
#line hidden
#line 575 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\BaseGenerator.tt"
}
}
}
#line default
#line hidden
}
#line default
#line hidden
#region Base class
/// <summary>
/// Base class for this transformation
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public class BaseGeneratorBase
{
#region Fields
private global::System.Text.StringBuilder generationEnvironmentField;
private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
private global::System.Collections.Generic.List<int> indentLengthsField;
private string currentIndentField = "";
private bool endsWithNewline;
private global::System.Collections.Generic.IDictionary<string, object> sessionField;
#endregion
#region Properties
/// <summary>
/// The string builder that generation-time code is using to assemble generated output
/// </summary>
protected System.Text.StringBuilder GenerationEnvironment
{
get
{
if ((this.generationEnvironmentField == null))
{
this.generationEnvironmentField = new global::System.Text.StringBuilder();
}
return this.generationEnvironmentField;
}
set
{
this.generationEnvironmentField = value;
}
}
/// <summary>
/// The error collection for the generation process
/// </summary>
public System.CodeDom.Compiler.CompilerErrorCollection Errors
{
get
{
if ((this.errorsField == null))
{
this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
}
return this.errorsField;
}
}
/// <summary>
/// A list of the lengths of each indent that was added with PushIndent
/// </summary>
private System.Collections.Generic.List<int> indentLengths
{
get
{
if ((this.indentLengthsField == null))
{
this.indentLengthsField = new global::System.Collections.Generic.List<int>();
}
return this.indentLengthsField;
}
}
/// <summary>
/// Gets the current indent we use when adding lines to the output
/// </summary>
public string CurrentIndent
{
get
{
return this.currentIndentField;
}
}
/// <summary>
/// Current transformation session
/// </summary>
public virtual global::System.Collections.Generic.IDictionary<string, object> Session
{
get
{
return this.sessionField;
}
set
{
this.sessionField = value;
}
}
#endregion
#region Transform-time helpers
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void Write(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
{
return;
}
// If we're starting off, or if the previous text ended with a newline,
// we have to append the current indent first.
if (((this.GenerationEnvironment.Length == 0)
|| this.endsWithNewline))
{
this.GenerationEnvironment.Append(this.currentIndentField);
this.endsWithNewline = false;
}
// Check if the current text ends with a newline
if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
{
this.endsWithNewline = true;
}
// This is an optimization. If the current indent is "", then we don't have to do any
// of the more complex stuff further down.
if ((this.currentIndentField.Length == 0))
{
this.GenerationEnvironment.Append(textToAppend);
return;
}
// Everywhere there is a newline in the text, add an indent after it
textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
// If the text ends with a newline, then we should strip off the indent added at the very end
// because the appropriate indent will be added when the next time Write() is called
if (this.endsWithNewline)
{
this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
}
else
{
this.GenerationEnvironment.Append(textToAppend);
}
}
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void WriteLine(string textToAppend)
{
this.Write(textToAppend);
this.GenerationEnvironment.AppendLine();
this.endsWithNewline = true;
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void Write(string format, params object[] args)
{
this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void WriteLine(string format, params object[] args)
{
this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Raise an error
/// </summary>
public void Error(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
this.Errors.Add(error);
}
/// <summary>
/// Raise a warning
/// </summary>
public void Warning(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
error.IsWarning = true;
this.Errors.Add(error);
}
/// <summary>
/// Increase the indent
/// </summary>
public void PushIndent(string indent)
{
if ((indent == null))
{
throw new global::System.ArgumentNullException("indent");
}
this.currentIndentField = (this.currentIndentField + indent);
this.indentLengths.Add(indent.Length);
}
/// <summary>
/// Remove the last indent that was added with PushIndent
/// </summary>
public string PopIndent()
{
string returnValue = "";
if ((this.indentLengths.Count > 0))
{
int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
if ((indentLength > 0))
{
returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
}
}
return returnValue;
}
/// <summary>
/// Remove any indentation
/// </summary>
public void ClearIndent()
{
this.indentLengths.Clear();
this.currentIndentField = "";
}
#endregion
#region ToString Helpers
/// <summary>
/// Utility class to produce culture-oriented representation of an object as a string.
/// </summary>
public class ToStringInstanceHelper
{
private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture;
/// <summary>
/// Gets or sets format provider to be used by ToStringWithCulture method.
/// </summary>
public System.IFormatProvider FormatProvider
{
get
{
return this.formatProviderField ;
}
set
{
if ((value != null))
{
this.formatProviderField = value;
}
}
}
/// <summary>
/// This is called from the compile/run appdomain to convert objects within an expression block to a string
/// </summary>
public string ToStringWithCulture(object objectToConvert)
{
if ((objectToConvert == null))
{
throw new global::System.ArgumentNullException("objectToConvert");
}
System.Type t = objectToConvert.GetType();
System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
typeof(System.IFormatProvider)});
if ((method == null))
{
return objectToConvert.ToString();
}
else
{
return ((string)(method.Invoke(objectToConvert, new object[] {
this.formatProviderField })));
}
}
}
private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
/// <summary>
/// Helper to produce culture-oriented representation of an object as a string
/// </summary>
public ToStringInstanceHelper ToStringHelper
{
get
{
return this.toStringHelperField;
}
}
#endregion
}
#endregion
}
| 2,269 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.CodeAnalysis
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisAssemblyInfo.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class CodeAnalysisAssemblyInfo : BaseGenerator
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
this.Write(@"
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle(""");
#line 13 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisAssemblyInfo.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.AssemblyTitle));
#line default
#line hidden
this.Write("\")]\r\n[assembly: AssemblyDescription(\"");
#line 14 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisAssemblyInfo.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.AssemblyDescription(versionIdentifier: "3.5")));
#line default
#line hidden
this.Write(@""")]
[assembly: AssemblyConfiguration("""")]
[assembly: AssemblyProduct(""Amazon Web Services SDK for .NET"")]
[assembly: AssemblyCompany(""Amazon.com, Inc"")]
[assembly: AssemblyCopyright(""Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved."")]
[assembly: AssemblyTrademark("""")]
[assembly: AssemblyCulture("""")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion(""1.0.*"")]
[assembly: AssemblyVersion(""");
#line 37 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisAssemblyInfo.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ServiceVersion));
#line default
#line hidden
this.Write("\")]\r\n[assembly: AssemblyFileVersion(\"");
#line 38 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisAssemblyInfo.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ServiceFileVersion));
#line default
#line hidden
this.Write("\")]\r\n\r\n");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 97 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.CodeAnalysis
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using ServiceClientGenerator;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisProjectFile.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class CodeAnalysisProjectFile : BaseGenerator
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
this.Write(@"<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<ProjectGuid>");
#line 12 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisProjectFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Session["ProjectGuid"]));
#line default
#line hidden
this.Write("</ProjectGuid>\r\n <RootNamespace>");
#line 13 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisProjectFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Session["RootNamespace"]));
#line default
#line hidden
this.Write("</RootNamespace>\r\n <AssemblyName>");
#line 14 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisProjectFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Session["AssemblyName"]));
#line default
#line hidden
this.Write(@"</AssemblyName>
<GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
<GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
<GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
</PropertyGroup>
<ItemGroup>
<PackageReference Include=""Microsoft.CodeAnalysis"" Version=""4.6.0"" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include=""Generated\PropertyValueRules.xml"">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
");
#line 34 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisProjectFile.tt"
foreach(string resource in ((IList<string>)this.Session["EmbeddedResources"]))
{
#line default
#line hidden
this.Write(" <EmbeddedResource Include=\"");
#line 38 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisProjectFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(resource));
#line default
#line hidden
this.Write("\">\r\n <CopyToOutputDirectory>Always</CopyToOutputDirectory>\r\n </EmbeddedRe" +
"source>\r\n");
#line 41 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisProjectFile.tt"
}
#line default
#line hidden
this.Write(" </ItemGroup>\r\n\r\n <ItemGroup>\r\n <ProjectReference Include=\"..\\..\\SharedAnaly" +
"sisCode\\SharedAnalysisCode.csproj\" />\r\n </ItemGroup>\r\n</Project>");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 114 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.CodeAnalysis
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using ServiceClientGenerator;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class CodeAnalysisSolutionFile : BaseGenerator
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
this.Write(@"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.6.33815.320
MinimumVisualStudioVersion = 10.0.40219.1
Project(""{2150E333-8FDC-42A3-9474-1A3956D46DE8}"") = ""ServiceAnalysis"", ""ServiceAnalysis"", ""{1523203C-CD16-4B4A-8F9D-8ECCA3A327AA}""
EndProject
");
#line 14 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
foreach(var project in (List<CodeAnalysisSolutionCreator.Project>)this.Session["CodeAnalysisProjects"])
{
#line default
#line hidden
this.Write("Project(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"");
#line 18 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.Name));
#line default
#line hidden
this.Write("\", \"");
#line 18 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.ProjectPath));
#line default
#line hidden
this.Write("\", \"");
#line 18 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.ProjectGuid));
#line default
#line hidden
this.Write("\"\r\nEndProject\r\n");
#line 20 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
}
#line default
#line hidden
this.Write(@"Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""SharedAnalysisCode"", ""code-analysis\SharedAnalysisCode\SharedAnalysisCode.csproj"", ""{16E2A13F-F4F6-4774-A2D8-AD8127E7EE4F}""
EndProject
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""MockAnalyzer"", ""code-analysis\MockAnalyzer\MockAnalyzer.csproj"", ""{9BC3B08B-9F09-444E-AD15-67045FA3AF19}""
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
");
#line 34 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
foreach(var project in (List<CodeAnalysisSolutionCreator.Project>)this.Session["CodeAnalysisProjects"])
{
#line default
#line hidden
this.Write("\t\t");
#line 38 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.ProjectGuid));
#line default
#line hidden
this.Write(".Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t");
#line 39 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.ProjectGuid));
#line default
#line hidden
this.Write(".Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t");
#line 40 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.ProjectGuid));
#line default
#line hidden
this.Write(".Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t");
#line 41 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.ProjectGuid));
#line default
#line hidden
this.Write(".Release|Any CPU.Build.0 = Release|Any CPU\r\n");
#line 42 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
}
#line default
#line hidden
this.Write(@" {16E2A13F-F4F6-4774-A2D8-AD8127E7EE4F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{16E2A13F-F4F6-4774-A2D8-AD8127E7EE4F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{16E2A13F-F4F6-4774-A2D8-AD8127E7EE4F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{16E2A13F-F4F6-4774-A2D8-AD8127E7EE4F}.Release|Any CPU.Build.0 = Release|Any CPU
{9BC3B08B-9F09-444E-AD15-67045FA3AF19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9BC3B08B-9F09-444E-AD15-67045FA3AF19}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9BC3B08B-9F09-444E-AD15-67045FA3AF19}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9BC3B08B-9F09-444E-AD15-67045FA3AF19}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
");
#line 58 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
foreach(var project in (List<CodeAnalysisSolutionCreator.Project>)this.Session["CodeAnalysisProjects"])
{
#line default
#line hidden
this.Write("\t\t");
#line 62 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.ProjectGuid));
#line default
#line hidden
this.Write(" = {1523203C-CD16-4B4A-8F9D-8ECCA3A327AA}\r\n");
#line 63 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\CodeAnalysisSolutionFile.tt"
}
#line default
#line hidden
this.Write("\tEndGlobalSection\r\nEndGlobal\r\n");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 184 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.CodeAnalysis
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\PropertyValueAssignmentAnalyzer.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class PropertyValueAssignmentAnalyzer : BaseGenerator
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
this.Write(@"using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Reflection;
using System.Linq;
using System.Xml.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Amazon.CodeAnalysis.Shared;
namespace ");
#line 20 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\PropertyValueAssignmentAnalyzer.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".CodeAnalysis\r\n{\r\n\t[DiagnosticAnalyzer(LanguageNames.CSharp)]\r\n\tpublic class Prop" +
"ertyValueAssignmentAnalyzer : AbstractPropertyValueAssignmentAnalyzer\r\n\t{\r\n\t\tpub" +
"lic override string GetServiceName()\r\n\t\t{\r\n\t\t\treturn \"");
#line 27 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\PropertyValueAssignmentAnalyzer.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("\";\r\n\t\t}\r\n\t}\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 69 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.CodeAnalysis
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixManifest.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class VsixManifest : VsixManifestBase
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public virtual string TransformText()
{
this.Write(@"<?xml version=""1.0"" encoding=""utf-8""?>
<PackageManifest Version=""2.0.0"" xmlns=""http://schemas.microsoft.com/developer/vsx-schema/2011"" xmlns:d=""http://schemas.microsoft.com/developer/vsx-schema-design/2011"">
<Metadata>
<Identity Id=""AWSCodeAnalysisTestExtension.Vsix..23f1a666-6de9-464a-8a5d-9b0791bf42ff"" Version=""1.0"" Language=""en-US"" Publisher=""AWS""/>
<DisplayName>AWSCodeAnalysisTestExtension.Vsix</DisplayName>
<Description xml:space=""preserve"">This is a sample diagnostic extension for the .NET Compiler Platform (""Roslyn"").</Description>
</Metadata>
<Installation>
<InstallationTarget Version=""[14.0,]"" Id=""Microsoft.VisualStudio.Pro"" />
<InstallationTarget Version=""[14.0,]"" Id=""Microsoft.VisualStudio.VSWinDesktopExpress"" />
<InstallationTarget Version=""[14.0,]"" Id=""Microsoft.VisualStudio.VWDExpress"" />
<InstallationTarget Version=""[14.0,]"" Id=""Microsoft.VisualStudio.VSWinExpress"" />
</Installation>
<Dependencies>
<Dependency Id=""Microsoft.Framework.NDP"" DisplayName=""Microsoft .NET Framework"" d:Source=""Manual"" Version=""[4.5.2,)"" />
</Dependencies>
<Assets>
");
#line 23 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixManifest.tt"
foreach(var project in (List<CodeAnalysisSolutionCreator.Project>)this.Session["CodeAnalysisProjects"])
{
#line default
#line hidden
this.Write(" <Asset Type=\"Microsoft.VisualStudio.MefComponent\" d:Source=\"Project\" d:Projec" +
"tName=\"");
#line 27 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixManifest.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.Name));
#line default
#line hidden
this.Write("\" Path=\"|");
#line 27 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixManifest.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.Name));
#line default
#line hidden
this.Write("|\"/>\r\n <Asset Type=\"Microsoft.VisualStudio.Analyzer\" d:Source=\"Project\" d:Proj" +
"ectName=\"");
#line 28 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixManifest.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.Name));
#line default
#line hidden
this.Write("\" Path=\"|");
#line 28 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixManifest.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.Name));
#line default
#line hidden
this.Write("|\"/>\r\n");
#line 29 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixManifest.tt"
}
#line default
#line hidden
this.Write(" </Assets>\r\n <Prerequisites>\r\n <Prerequisite Id=\"Microsoft.VisualStudio.Comp" +
"onent.CoreEditor\" Version=\"[14.0,]\" DisplayName=\"Visual Studio core editor\" />\r\n" +
" </Prerequisites>\r\n</PackageManifest>\r\n");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
#region Base class
/// <summary>
/// Base class for this transformation
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public class VsixManifestBase
{
#region Fields
private global::System.Text.StringBuilder generationEnvironmentField;
private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
private global::System.Collections.Generic.List<int> indentLengthsField;
private string currentIndentField = "";
private bool endsWithNewline;
private global::System.Collections.Generic.IDictionary<string, object> sessionField;
#endregion
#region Properties
/// <summary>
/// The string builder that generation-time code is using to assemble generated output
/// </summary>
public System.Text.StringBuilder GenerationEnvironment
{
get
{
if ((this.generationEnvironmentField == null))
{
this.generationEnvironmentField = new global::System.Text.StringBuilder();
}
return this.generationEnvironmentField;
}
set
{
this.generationEnvironmentField = value;
}
}
/// <summary>
/// The error collection for the generation process
/// </summary>
public System.CodeDom.Compiler.CompilerErrorCollection Errors
{
get
{
if ((this.errorsField == null))
{
this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
}
return this.errorsField;
}
}
/// <summary>
/// A list of the lengths of each indent that was added with PushIndent
/// </summary>
private System.Collections.Generic.List<int> indentLengths
{
get
{
if ((this.indentLengthsField == null))
{
this.indentLengthsField = new global::System.Collections.Generic.List<int>();
}
return this.indentLengthsField;
}
}
/// <summary>
/// Gets the current indent we use when adding lines to the output
/// </summary>
public string CurrentIndent
{
get
{
return this.currentIndentField;
}
}
/// <summary>
/// Current transformation session
/// </summary>
public virtual global::System.Collections.Generic.IDictionary<string, object> Session
{
get
{
return this.sessionField;
}
set
{
this.sessionField = value;
}
}
#endregion
#region Transform-time helpers
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void Write(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
{
return;
}
// If we're starting off, or if the previous text ended with a newline,
// we have to append the current indent first.
if (((this.GenerationEnvironment.Length == 0)
|| this.endsWithNewline))
{
this.GenerationEnvironment.Append(this.currentIndentField);
this.endsWithNewline = false;
}
// Check if the current text ends with a newline
if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
{
this.endsWithNewline = true;
}
// This is an optimization. If the current indent is "", then we don't have to do any
// of the more complex stuff further down.
if ((this.currentIndentField.Length == 0))
{
this.GenerationEnvironment.Append(textToAppend);
return;
}
// Everywhere there is a newline in the text, add an indent after it
textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
// If the text ends with a newline, then we should strip off the indent added at the very end
// because the appropriate indent will be added when the next time Write() is called
if (this.endsWithNewline)
{
this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
}
else
{
this.GenerationEnvironment.Append(textToAppend);
}
}
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void WriteLine(string textToAppend)
{
this.Write(textToAppend);
this.GenerationEnvironment.AppendLine();
this.endsWithNewline = true;
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void Write(string format, params object[] args)
{
this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void WriteLine(string format, params object[] args)
{
this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Raise an error
/// </summary>
public void Error(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
this.Errors.Add(error);
}
/// <summary>
/// Raise a warning
/// </summary>
public void Warning(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
error.IsWarning = true;
this.Errors.Add(error);
}
/// <summary>
/// Increase the indent
/// </summary>
public void PushIndent(string indent)
{
if ((indent == null))
{
throw new global::System.ArgumentNullException("indent");
}
this.currentIndentField = (this.currentIndentField + indent);
this.indentLengths.Add(indent.Length);
}
/// <summary>
/// Remove the last indent that was added with PushIndent
/// </summary>
public string PopIndent()
{
string returnValue = "";
if ((this.indentLengths.Count > 0))
{
int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
if ((indentLength > 0))
{
returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
}
}
return returnValue;
}
/// <summary>
/// Remove any indentation
/// </summary>
public void ClearIndent()
{
this.indentLengths.Clear();
this.currentIndentField = "";
}
#endregion
#region ToString Helpers
/// <summary>
/// Utility class to produce culture-oriented representation of an object as a string.
/// </summary>
public class ToStringInstanceHelper
{
private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture;
/// <summary>
/// Gets or sets format provider to be used by ToStringWithCulture method.
/// </summary>
public System.IFormatProvider FormatProvider
{
get
{
return this.formatProviderField ;
}
set
{
if ((value != null))
{
this.formatProviderField = value;
}
}
}
/// <summary>
/// This is called from the compile/run appdomain to convert objects within an expression block to a string
/// </summary>
public string ToStringWithCulture(object objectToConvert)
{
if ((objectToConvert == null))
{
throw new global::System.ArgumentNullException("objectToConvert");
}
System.Type t = objectToConvert.GetType();
System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
typeof(System.IFormatProvider)});
if ((method == null))
{
return objectToConvert.ToString();
}
else
{
return ((string)(method.Invoke(objectToConvert, new object[] {
this.formatProviderField })));
}
}
}
private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
/// <summary>
/// Helper to produce culture-oriented representation of an object as a string
/// </summary>
public ToStringInstanceHelper ToStringHelper
{
get
{
return this.toStringHelperField;
}
}
#endregion
}
#endregion
}
| 379 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.CodeAnalysis
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixTestProfileFile.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class VsixTestProfileFile : VsixTestProfileFileBase
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public virtual string TransformText()
{
this.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"14.0\" DefaultTarge" +
"ts=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n <Prop" +
"ertyGroup>\r\n <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>\r\n " +
" <VSToolsPath Condition=\"\'$(VSToolsPath)\' == \'\'\">$(MSBuildExtensionsPath32)\\Mi" +
"crosoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n </PropertyGroup>\r\n" +
" <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Com" +
"mon.props\" Condition=\"Exists(\'$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Mi" +
"crosoft.Common.props\')\" />\r\n <PropertyGroup>\r\n <Configuration Condition=\" \'$" +
"(Configuration)\' == \'\' \">Debug</Configuration>\r\n <Platform Condition=\" \'$(Pla" +
"tform)\' == \'\' \">AnyCPU</Platform>\r\n <SchemaVersion>2.0</SchemaVersion>\r\n <" +
"ProjectTypeGuids>{82b43b9b-a64c-4715-b499-d71e9ca2bd60};{FAE04EC0-301F-11D3-BF4B" +
"-00C04F79EFBC}</ProjectTypeGuids>\r\n <ProjectGuid>{11EAD86F-28B2-4DD6-AA76-72B" +
"B3B4AE80C}</ProjectGuid>\r\n <OutputType>Library</OutputType>\r\n <AppDesigner" +
"Folder>Properties</AppDesignerFolder>\r\n <RootNamespace>AWSCodeAnalysisTestExt" +
"ension</RootNamespace>\r\n <AssemblyName>AWSCodeAnalysisTestExtension</Assembly" +
"Name>\r\n <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>\r\n <Generat" +
"ePkgDefFile>false</GeneratePkgDefFile>\r\n <IncludeAssemblyInVSIXContainer>fals" +
"e</IncludeAssemblyInVSIXContainer>\r\n <IncludeDebugSymbolsInVSIXContainer>fals" +
"e</IncludeDebugSymbolsInVSIXContainer>\r\n <IncludeDebugSymbolsInLocalVSIXDeplo" +
"yment>false</IncludeDebugSymbolsInLocalVSIXDeployment>\r\n <CopyBuildOutputToOu" +
"tputDirectory>false</CopyBuildOutputToOutputDirectory>\r\n <CopyOutputSymbolsTo" +
"OutputDirectory>false</CopyOutputSymbolsToOutputDirectory>\r\n <VSSDKTargetPlat" +
"formRegRootSuffix>Roslyn</VSSDKTargetPlatformRegRootSuffix>\r\n </PropertyGroup>\r" +
"\n <PropertyGroup Condition=\" \'$(Configuration)|$(Platform)\' == \'Debug|AnyCPU\' \"" +
">\r\n <DebugSymbols>true</DebugSymbols>\r\n <DebugType>full</DebugType>\r\n <" +
"Optimize>false</Optimize>\r\n <OutputPath>bin\\Debug\\</OutputPath>\r\n <DefineC" +
"onstants>DEBUG;TRACE</DefineConstants>\r\n <ErrorReport>prompt</ErrorReport>\r\n " +
" <WarningLevel>4</WarningLevel>\r\n </PropertyGroup>\r\n <PropertyGroup Conditio" +
"n=\" \'$(Configuration)|$(Platform)\' == \'Release|AnyCPU\' \">\r\n <DebugType>pdbonl" +
"y</DebugType>\r\n <Optimize>true</Optimize>\r\n <OutputPath>bin\\Release\\</Outp" +
"utPath>\r\n <DefineConstants>TRACE</DefineConstants>\r\n <ErrorReport>prompt</" +
"ErrorReport>\r\n <WarningLevel>4</WarningLevel>\r\n </PropertyGroup>\r\n <Propert" +
"yGroup>\t\t\t\t\r\n <StartAction>Program</StartAction>\r\n <StartProgram>$(DevEnvD" +
"ir)devenv.exe</StartProgram>\r\n <StartArguments>/rootsuffix Roslyn</StartArgum" +
"ents>\r\n </PropertyGroup>\r\n <ItemGroup>\r\n <None Include=\"source.extension.vs" +
"ixmanifest\">\r\n <SubType>Designer</SubType>\r\n </None>\r\n </ItemGroup>\r\n " +
"<ItemGroup>\r\n");
#line 60 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixTestProfileFile.tt"
foreach(var project in (List<CodeAnalysisSolutionCreator.Project>)this.Session["CodeAnalysisProjects"])
{
#line default
#line hidden
this.Write(" <ProjectReference Include=\"../ServiceAnalysis/");
#line 64 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixTestProfileFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.ShortName));
#line default
#line hidden
this.Write("/");
#line 64 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixTestProfileFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.Name));
#line default
#line hidden
this.Write(".csproj\">\r\n <Project>");
#line 65 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixTestProfileFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.ProjectGuid));
#line default
#line hidden
this.Write("</Project>\r\n <Name>");
#line 66 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixTestProfileFile.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(project.Name));
#line default
#line hidden
this.Write("</Name>\r\n </ProjectReference>\r\n");
#line 68 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\CodeAnalysis\VsixTestProfileFile.tt"
}
#line default
#line hidden
this.Write(@" </ItemGroup>
<Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
<Import Project=""$(VSToolsPath)\VSSDK\Microsoft.VsSDK.targets"" Condition=""'$(VSToolsPath)' != ''"" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name=""BeforeBuild"">
</Target>
<Target Name=""AfterBuild"">
</Target>
-->
</Project>");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
#region Base class
/// <summary>
/// Base class for this transformation
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public class VsixTestProfileFileBase
{
#region Fields
private global::System.Text.StringBuilder generationEnvironmentField;
private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
private global::System.Collections.Generic.List<int> indentLengthsField;
private string currentIndentField = "";
private bool endsWithNewline;
private global::System.Collections.Generic.IDictionary<string, object> sessionField;
#endregion
#region Properties
/// <summary>
/// The string builder that generation-time code is using to assemble generated output
/// </summary>
public System.Text.StringBuilder GenerationEnvironment
{
get
{
if ((this.generationEnvironmentField == null))
{
this.generationEnvironmentField = new global::System.Text.StringBuilder();
}
return this.generationEnvironmentField;
}
set
{
this.generationEnvironmentField = value;
}
}
/// <summary>
/// The error collection for the generation process
/// </summary>
public System.CodeDom.Compiler.CompilerErrorCollection Errors
{
get
{
if ((this.errorsField == null))
{
this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
}
return this.errorsField;
}
}
/// <summary>
/// A list of the lengths of each indent that was added with PushIndent
/// </summary>
private System.Collections.Generic.List<int> indentLengths
{
get
{
if ((this.indentLengthsField == null))
{
this.indentLengthsField = new global::System.Collections.Generic.List<int>();
}
return this.indentLengthsField;
}
}
/// <summary>
/// Gets the current indent we use when adding lines to the output
/// </summary>
public string CurrentIndent
{
get
{
return this.currentIndentField;
}
}
/// <summary>
/// Current transformation session
/// </summary>
public virtual global::System.Collections.Generic.IDictionary<string, object> Session
{
get
{
return this.sessionField;
}
set
{
this.sessionField = value;
}
}
#endregion
#region Transform-time helpers
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void Write(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
{
return;
}
// If we're starting off, or if the previous text ended with a newline,
// we have to append the current indent first.
if (((this.GenerationEnvironment.Length == 0)
|| this.endsWithNewline))
{
this.GenerationEnvironment.Append(this.currentIndentField);
this.endsWithNewline = false;
}
// Check if the current text ends with a newline
if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
{
this.endsWithNewline = true;
}
// This is an optimization. If the current indent is "", then we don't have to do any
// of the more complex stuff further down.
if ((this.currentIndentField.Length == 0))
{
this.GenerationEnvironment.Append(textToAppend);
return;
}
// Everywhere there is a newline in the text, add an indent after it
textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
// If the text ends with a newline, then we should strip off the indent added at the very end
// because the appropriate indent will be added when the next time Write() is called
if (this.endsWithNewline)
{
this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
}
else
{
this.GenerationEnvironment.Append(textToAppend);
}
}
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void WriteLine(string textToAppend)
{
this.Write(textToAppend);
this.GenerationEnvironment.AppendLine();
this.endsWithNewline = true;
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void Write(string format, params object[] args)
{
this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void WriteLine(string format, params object[] args)
{
this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Raise an error
/// </summary>
public void Error(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
this.Errors.Add(error);
}
/// <summary>
/// Raise a warning
/// </summary>
public void Warning(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
error.IsWarning = true;
this.Errors.Add(error);
}
/// <summary>
/// Increase the indent
/// </summary>
public void PushIndent(string indent)
{
if ((indent == null))
{
throw new global::System.ArgumentNullException("indent");
}
this.currentIndentField = (this.currentIndentField + indent);
this.indentLengths.Add(indent.Length);
}
/// <summary>
/// Remove the last indent that was added with PushIndent
/// </summary>
public string PopIndent()
{
string returnValue = "";
if ((this.indentLengths.Count > 0))
{
int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
if ((indentLength > 0))
{
returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
}
}
return returnValue;
}
/// <summary>
/// Remove any indentation
/// </summary>
public void ClearIndent()
{
this.indentLengths.Clear();
this.currentIndentField = "";
}
#endregion
#region ToString Helpers
/// <summary>
/// Utility class to produce culture-oriented representation of an object as a string.
/// </summary>
public class ToStringInstanceHelper
{
private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture;
/// <summary>
/// Gets or sets format provider to be used by ToStringWithCulture method.
/// </summary>
public System.IFormatProvider FormatProvider
{
get
{
return this.formatProviderField ;
}
set
{
if ((value != null))
{
this.formatProviderField = value;
}
}
}
/// <summary>
/// This is called from the compile/run appdomain to convert objects within an expression block to a string
/// </summary>
public string ToStringWithCulture(object objectToConvert)
{
if ((objectToConvert == null))
{
throw new global::System.ArgumentNullException("objectToConvert");
}
System.Type t = objectToConvert.GetType();
System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
typeof(System.IFormatProvider)});
if ((method == null))
{
return objectToConvert.ToString();
}
else
{
return ((string)(method.Invoke(objectToConvert, new object[] {
this.formatProviderField })));
}
}
}
private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
/// <summary>
/// Helper to produce culture-oriented representation of an object as a string
/// </summary>
public ToStringInstanceHelper ToStringHelper
{
get
{
return this.toStringHelperField;
}
}
#endregion
}
#endregion
}
| 404 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Endpoints
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class EndpointParameters : BaseGenerator
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
AddLicenseHeader();
#line default
#line hidden
this.Write("\r\nusing Amazon.Runtime;\r\nusing Amazon.Runtime.Endpoints;\r\n\r\nnamespace ");
#line 13 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Endpoints\r\n{\r\n /// <summary>\r\n /// Contains parameters used for resolving " +
"");
#line 16 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write(" endpoints\r\n /// Parameters can be sourced from client config and service oper" +
"ations\r\n /// Used by internal ");
#line 18 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("EndpointProvider and ");
#line 18 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(Config.ClassName));
#line default
#line hidden
this.Write("EndpointResolver\r\n /// Can be used by custom EndpointProvider, see ClientConfi" +
"g.EndpointProvider\r\n /// </summary>\r\n public class ");
#line 21 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("EndpointParameters : EndpointParameters\r\n {\r\n /// <summary>\r\n //" +
"/ ");
#line 24 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("EndpointParameters constructor\r\n /// </summary>\r\n public ");
#line 26 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("EndpointParameters()\r\n {\r\n");
#line 28 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
foreach(var param in this.Config.EndpointsRuleSet.parameters) {
if (param.Value.DefaultValue != null) {
#line default
#line hidden
this.Write(" ");
#line 31 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(param.Key));
#line default
#line hidden
this.Write(" = ");
#line 31 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(param.Value.DefaultValue));
#line default
#line hidden
this.Write(";\r\n");
#line 32 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
}
}
#line default
#line hidden
this.Write(" }\r\n");
#line 35 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
foreach(var param in this.Config.EndpointsRuleSet.parameters) {
var paramType = param.Value.type.ToNativeType(true);
var paramName = param.Key;
#line default
#line hidden
this.Write("\r\n /// <summary>\r\n /// ");
#line 41 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(param.Key));
#line default
#line hidden
this.Write(" parameter\r\n /// </summary>\r\n");
#line 43 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
if (param.Value.deprecated != null) {
var message = $@"{param.Value.deprecated.message}";
if (param.Value.deprecated.since != null)
{
message = $@"Deprecated since {param.Value.deprecated.since}. " + message;
}
#line default
#line hidden
this.Write(" [Obsolete(\"");
#line 50 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(message));
#line default
#line hidden
this.Write("\")]\r\n");
#line 51 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
}
#line default
#line hidden
this.Write(" public ");
#line 52 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(paramType));
#line default
#line hidden
this.Write(" ");
#line 52 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(paramName));
#line default
#line hidden
this.Write(" \r\n { \r\n get { return (");
#line 54 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(paramType));
#line default
#line hidden
this.Write(")this[\"");
#line 54 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(paramName));
#line default
#line hidden
this.Write("\"]; }\r\n set { this[\"");
#line 55 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(paramName));
#line default
#line hidden
this.Write("\"] = value; } \r\n }\r\n");
#line 57 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointParameters.tt"
}
#line default
#line hidden
this.Write(" }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 217 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Endpoints
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using ServiceClientGenerator.Endpoints;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class EndpointProvider : BaseGenerator
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 7 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
AddLicenseHeader();
#line default
#line hidden
this.Write("\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing Amazon.Runtime;\r\nusing " +
"Amazon.Runtime.Endpoints;\r\nusing static Amazon.Runtime.Internal.Endpoints.Standa" +
"rdLibrary.Fn;\r\n\r\nnamespace ");
#line 17 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Internal\r\n{\r\n /// <summary>\r\n /// Amazon ");
#line 20 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write(" endpoint provider.\r\n /// Resolves endpoint for given set of ");
#line 21 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("EndpointParameters.\r\n /// Can throw AmazonClientException if endpoint resoluti" +
"on is unsuccessful.\r\n /// </summary>\r\n public class Amazon");
#line 24 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("EndpointProvider : IEndpointProvider\r\n {\r\n /// <summary>\r\n /// R" +
"esolve endpoint for ");
#line 27 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("EndpointParameters\r\n /// </summary>\r\n public Endpoint ResolveEndpoi" +
"nt(EndpointParameters parameters)\r\n {\r\n if (parameters == null" +
") \r\n throw new ArgumentNullException(\"parameters\");\r\n\r\n");
#line 34 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
foreach(var param in this.Config.EndpointsRuleSet.parameters) {
if (param.Value.required) {
#line default
#line hidden
this.Write(" if (parameters[\"");
#line 37 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(param.Key));
#line default
#line hidden
this.Write("\"] == null)\r\n throw new AmazonClientException(\"");
#line 38 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(param.Key));
#line default
#line hidden
this.Write(" parameter must be set for endpoint resolution\");\r\n");
#line 39 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
}}
#line default
#line hidden
this.Write("\r\n var refs = new Dictionary<string, object>()\r\n {\r\n");
#line 43 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
foreach(var param in this.Config.EndpointsRuleSet.parameters) {
#line default
#line hidden
this.Write(" [\"");
#line 44 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(param.Key));
#line default
#line hidden
this.Write("\"] = parameters[\"");
#line 44 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(param.Key));
#line default
#line hidden
this.Write("\"],\r\n");
#line 45 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
}
#line default
#line hidden
this.Write(" };\r\n");
#line 47 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProvider.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(CodeGen.GenerateRules(this.Config.EndpointsRuleSet)));
#line default
#line hidden
this.Write("\r\n throw new AmazonClientException(\"Cannot resolve endpoint\");\r\n " +
" }\r\n }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 155 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Endpoints
{
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class EndpointProviderTests : Generators.BaseGenerator
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 7 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
AddLicenseHeader();
#line default
#line hidden
this.Write("\r\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\r\nusing Amazon.Runtime;\r\nusi" +
"ng ");
#line 13 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Endpoints;\r\nusing ");
#line 14 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Internal;\r\n\r\nnamespace AWSSDK_DotNet35.UnitTests.Endpoints\r\n{\r\n [TestClass]\r\n" +
" public partial class ");
#line 19 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("EndpointsTests\r\n {\r\n");
#line 21 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
foreach(var test in this.Config.EndpointTests.testCases)
{
#line default
#line hidden
this.Write(" [TestMethod]\r\n [TestCategory(\"UnitTest\")]\r\n [TestCategory(\"" +
"Endpoints\")]\r\n [TestCategory(\"");
#line 28 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.TestCategory));
#line default
#line hidden
this.Write("\")]\r\n [Description(\"");
#line 29 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(test.documentation));
#line default
#line hidden
this.Write("\")]\r\n");
#line 30 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
if (test.expect.error != null) {
#line default
#line hidden
this.Write(" [ExpectedException(typeof(AmazonClientException), @\"");
#line 31 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(test.expect.error.SanitizeQuotes()));
#line default
#line hidden
this.Write("\")]\r\n");
#line 32 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
}
#line default
#line hidden
this.Write(" public void ");
#line 33 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(ToTestName(test.documentation)));
#line default
#line hidden
this.Write("_Test()\r\n {\r\n var parameters = new ");
#line 35 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("EndpointParameters();\r\n");
#line 36 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
if (test.@params != null)
foreach(var param in test.@params)
{
#line default
#line hidden
this.Write(" parameters[\"");
#line 41 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(param.Key));
#line default
#line hidden
this.Write("\"] = ");
#line 41 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(param.Value.ToNativeValue()));
#line default
#line hidden
this.Write(";\r\n");
#line 42 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
}
#line default
#line hidden
this.Write(" var endpoint = new Amazon");
#line 45 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("EndpointProvider().ResolveEndpoint(parameters);\r\n");
#line 46 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
if (test.expect.endpoint != null)
{
#line default
#line hidden
this.Write(" Assert.AreEqual(\"");
#line 50 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(test.expect.endpoint.url));
#line default
#line hidden
this.Write("\", endpoint.URL);\r\n");
#line 51 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
}
#line default
#line hidden
this.Write(" }\r\n\r\n");
#line 56 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointProviderTests.tt"
}
#line default
#line hidden
this.Write(" }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 207 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace ServiceClientGenerator.Generators.Endpoints
{
public partial class EndpointProviderTests
{
// all non-alphanumeric and undescores
private static readonly Regex regex = new Regex("[^a-zA-Z0-9_]");
private readonly Dictionary<string, uint> _versions = new Dictionary<string, uint>();
/// <summary>
/// Converts test's documentation to a valid unique test function name.
/// e.g. "invalid access point ARN: Not S3" -> "Invalid_access_point_ARN_Not_S3_e54f317d56234714a52e6e6062b7d188".
/// "42 is the ultimate answer" -> "_42_is_the_ultimate_answer_e54f317d56234714a52e6e6062b7d177".
/// </summary>
public string ToTestName(string documentation)
{
documentation = documentation.Trim().Replace(" ", "_");
if (char.IsDigit(documentation.First()))
{
documentation = "_" + documentation;
}
var name = regex
.Replace(documentation, string.Empty)
.Replace("__", "_")
.ToUpperFirstCharacter();
if (!_versions.ContainsKey(name))
{
_versions.Add(name, 0);
}
else
{
var version = _versions[name] + 1;
_versions[name] = version;
name = $"{name}_{version}";
}
return name;
}
}
}
| 46 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Endpoints
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using ServiceClientGenerator.Endpoints;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class EndpointResolver : BaseGenerator
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 7 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
AddLicenseHeader();
#line default
#line hidden
this.Write("\r\nusing System;\r\nusing Amazon.");
#line 12 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(Config.ServiceNameRoot));
#line default
#line hidden
this.Write(".Model;\r\nusing Amazon.Runtime;\r\nusing Amazon.Runtime.Internal;\r\nusing Amazon.Runt" +
"ime.Endpoints;\r\nusing Amazon.Util;\r\nusing ");
#line 17 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(Config.Namespace));
#line default
#line hidden
this.Write(".Endpoints;\r\n\r\n#pragma warning disable 1591\r\n\r\nnamespace ");
#line 21 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(Config.Namespace));
#line default
#line hidden
this.Write(".Internal\r\n{\r\n /// <summary>\r\n /// Amazon ");
#line 24 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write(" endpoint resolver.\r\n /// Custom PipelineHandler responsible for resolving end" +
"point and setting authentication parameters for ");
#line 25 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write(" service requests.\r\n /// Collects values for ");
#line 26 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("EndpointParameters and then tries to resolve endpoint by calling \r\n /// Resolv" +
"eEndpoint method on GlobalEndpoints.Provider if present, otherwise uses ");
#line 27 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("EndpointProvider.\r\n /// Responsible for setting authentication and http header" +
"s provided by resolved endpoint.\r\n /// </summary>\r\n public class Amazon");
#line 30 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(Config.ClassName));
#line default
#line hidden
this.Write("EndpointResolver : BaseEndpointResolver\r\n {\r\n protected override void S" +
"erviceSpecificHandler(IExecutionContext executionContext, EndpointParameters par" +
"ameters)\r\n {\r\n");
#line 34 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
if (Config.ServiceId == "S3") {
#line default
#line hidden
this.Write(@" // Special handling of SigV2 for S3
if (parameters[""Bucket""] != null)
{
// SigV2 support, CanonicalResourcePrefix required for proper signing
executionContext.RequestContext.Request.CanonicalResourcePrefix = ""/"" + parameters[""Bucket""];
}
// Special handling of SigV2
if (executionContext.RequestContext.ClientConfig.SignatureVersion == ""2"")
{
executionContext.RequestContext.Request.SignatureVersion = SignatureVersion.SigV2;
}
// If the marshalled request has the SSE header and it is set to KMS, force SigV4 for this request.
// Current operations that may set this header: CopyObject, CopyPart, InitiateMultipart, PutObject
string sseHeaderValue;
if (executionContext.RequestContext.Request.Headers.TryGetValue(HeaderKeys.XAmzServerSideEncryptionHeader, out sseHeaderValue) &&
(string.Equals(sseHeaderValue, ServerSideEncryptionMethod.AWSKMS.Value, StringComparison.Ordinal) || string.Equals(sseHeaderValue, ServerSideEncryptionMethod.AWSKMSDSSE.Value, StringComparison.Ordinal)))
{
executionContext.RequestContext.Request.SignatureVersion = SignatureVersion.SigV4;
}
");
#line 56 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
}
#line default
#line hidden
this.Write("\r\n");
#line 58 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
if (!this.dontInjectHostPrefixForServices.Contains(Config.ServiceId)) {
#line default
#line hidden
this.Write(" InjectHostPrefix(executionContext.RequestContext);\r\n");
#line 60 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
}
#line default
#line hidden
this.Write(" }\r\n\r\n protected override EndpointParameters MapEndpointsParameters" +
"(IRequestContext requestContext)\r\n {\r\n var config = (Amazon");
#line 65 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(Config.ClassName));
#line default
#line hidden
this.Write("Config)requestContext.ClientConfig;\r\n var result = new ");
#line 66 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(Config.ClassName));
#line default
#line hidden
this.Write("EndpointParameters();\r\n");
#line 67 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.AssignBuiltins()));
#line default
#line hidden
this.Write("\r\n");
#line 68 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.AssignClientContext()));
#line default
#line hidden
this.Write("\r\n");
#line 69 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
if (Config.EndpointsRuleSet.parameters.ContainsKey("Region")) {
#line default
#line hidden
this.Write(@" // The region needs to be determined from the ServiceURL if not set.
var regionEndpoint = config.RegionEndpoint;
if (regionEndpoint == null && !string.IsNullOrEmpty(config.ServiceURL))
{
var regionName = AWSSDKUtils.DetermineRegion(config.ServiceURL);
result.Region = RegionEndpoint.GetBySystemName(regionName).SystemName;
}
// To support legacy endpoint overridding rules in the endpoints.json
if (result.Region == ""us-east-1-regional"")
{
result.Region = ""us-east-1"";
}
// Use AlternateEndpoint region override if set
if (requestContext.Request.AlternateEndpoint != null)
{
result.Region = requestContext.Request.AlternateEndpoint.SystemName;
}
");
#line 90 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
}
#line default
#line hidden
#line 91 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
if (Config.ClassName == "S3") {
#line default
#line hidden
this.Write(@" // Special handling of GetPreSignedUrlRequest
if (requestContext.Request.RequestName == ""GetPreSignedUrlRequest"")
{
var request = (GetPreSignedUrlRequest)requestContext.Request.OriginalRequest;
result.Bucket = request.BucketName;
return result;
}
");
#line 99 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
}
#line default
#line hidden
this.Write("\r\n // Assign staticContextParams and contextParam per operation\r\n");
#line 102 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\EndpointResolver.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.AssignOperationContext()));
#line default
#line hidden
this.Write("\r\n return result;\r\n }\r\n }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 249 |
aws-sdk-net | aws | C# | using System.Text;
using System.Linq;
using ServiceClientGenerator.Endpoints;
using System;
using System.Collections.Generic;
namespace ServiceClientGenerator.Generators.Endpoints
{
public partial class EndpointResolver
{
private HashSet<string> dontInjectHostPrefixForServices = new HashSet<string>() { "S3 Control" };
private string GetValueSource(Parameter parameter)
{
switch (parameter.builtIn)
{
case "AWS::Region": return "config.RegionEndpoint?.SystemName";
case "AWS::UseFIPS": return "config.UseFIPSEndpoint";
case "AWS::UseDualStack": return "config.UseDualstackEndpoint";
case "SDK::Endpoint": return "config.ServiceURL";
case "AWS::S3::ForcePathStyle": return "config.ForcePathStyle";
case "AWS::S3::Accelerate": return "config.UseAccelerateEndpoint";
case "AWS::S3::UseArnRegion": return "config.UseArnRegion";
case "AWS::S3Control::UseArnRegion": return "config.UseArnRegion";
case "AWS::S3::DisableMultiRegionAccessPoints": return "config.DisableMultiregionAccessPoints";
case "AWS::S3::UseGlobalEndpoint": return "config.USEast1RegionalEndpointValue == S3UsEast1RegionalEndpointValue.Legacy";
case "AWS::STS::UseGlobalEndpoint": return "config.StsRegionalEndpoints == StsRegionalEndpointsValue.Legacy";
default: throw new Exception("Unknown builtIn");
}
}
private const string indent = " "; // 12 spaces
private const string innerIndent = " "; // 16 spaces
private string AssignBuiltins()
{
var parameters = Config.EndpointsRuleSet.parameters;
var code = new StringBuilder();
foreach (var param in parameters.Where(c => c.Value.builtIn != null))
{
code.AppendLine($@"{indent}result.{param.Key} = {GetValueSource(param.Value)};");
}
return code.ToString();
}
private string AssignClientContext()
{
var parameters = Config.ServiceModel.ClientContextParameters;
var code = new StringBuilder();
foreach (var param in parameters)
{
string valueSource = $"config.{param.name}";
Parameter parameter;
if (Config.EndpointsRuleSet.parameters.TryGetValue(param.name, out parameter) && parameter.builtIn != null)
{
valueSource = GetValueSource(Config.EndpointsRuleSet.parameters[param.name]);
}
code.AppendLine($@"{indent}result.{param.name} = {valueSource};");
}
return code.ToString();
}
private string AssignOperationContext()
{
var code = new StringBuilder();
var ops = Config.ServiceModel.Operations.Where(x => x.StaticContextParameters.Count > 0 || x.RequestStructure?.Members.Any(c => c.ContextParameter != null) == true);
foreach (var op in ops)
{
code.AppendLine($@"{indent}if (requestContext.RequestName == ""{op.Name}Request"") {{");
foreach (var param in op.StaticContextParameters)
{
code.AppendLine($@"{innerIndent}result.{param.name} = {param.nativeValue};");
}
if (op.RequestStructure == null)
{
continue;
}
var members = op.RequestStructure.Members.Where(c => c.ContextParameter != null).ToList();
if (members.Count > 0)
{
code.AppendLine($@"{innerIndent}var request = ({op.Name}Request)requestContext.OriginalRequest;");
foreach (var member in members)
{
code.AppendLine($@"{innerIndent}result.{member.ContextParameter.name} = request.{member.PropertyName};");
}
}
code.AppendLine($@"{innerIndent}return result;");
code.AppendLine($@"{indent}}}");
}
return code.ToString();
}
}
}
| 98 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Endpoints
{
using System.Linq;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class PartitionsTemplate : PartitionsTemplateBase
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public virtual string TransformText()
{
this.Write(@"/*******************************************************************************
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the ""License""). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the ""license"" file accompanying this file.
* This file 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.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*
*/
namespace Amazon.Runtime.Internal.Endpoints.StandardLibrary
{
/// <summary>
/// Generated implementation of partition-specific data.
/// Based on the data from partitions.json
/// </summary>
public partial class Partition
{
static Partition()
{
");
#line 33 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
foreach(var partition in Partitions.partitions) {
#line default
#line hidden
this.Write(" var ");
#line 34 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(partition.id.ToVariableName()));
#line default
#line hidden
this.Write(" = new PartitionAttributesShape\r\n {\r\n name = \"");
#line 36 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(partition.outputs.name));
#line default
#line hidden
this.Write("\",\r\n dnsSuffix = \"");
#line 37 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(partition.outputs.dnsSuffix));
#line default
#line hidden
this.Write("\",\r\n dualStackDnsSuffix = \"");
#line 38 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(partition.outputs.dualStackDnsSuffix));
#line default
#line hidden
this.Write("\",\r\n supportsFIPS = ");
#line 39 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(partition.outputs.supportsFIPS.ToString().ToLower()));
#line default
#line hidden
this.Write(",\r\n supportsDualStack = ");
#line 40 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(partition.outputs.supportsDualStack.ToString().ToLower()));
#line default
#line hidden
this.Write("\r\n };\r\n _partitionsByRegex.Add(@\"");
#line 42 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(partition.regionRegex));
#line default
#line hidden
this.Write("\", ");
#line 42 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(partition.id.ToVariableName()));
#line default
#line hidden
this.Write(");\r\n");
#line 43 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
foreach(var region in partition.regions.Keys) {
#line default
#line hidden
this.Write(" _partitionsByRegionName.Add(\"");
#line 44 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(region));
#line default
#line hidden
this.Write("\", ");
#line 44 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(partition.id.ToVariableName()));
#line default
#line hidden
this.Write(");\r\n");
#line 45 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
}
#line default
#line hidden
this.Write("\r\n");
#line 47 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
}
#line default
#line hidden
this.Write(" _defaultPartition = aws;\r\n }\r\n }\r\n}\r\n\r\n");
return this.GenerationEnvironment.ToString();
}
#line 53 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Endpoints\PartitionsTemplate.tt"
public ServiceClientGenerator.Endpoints.Partitions.Partitions Partitions { get; set; }
#line default
#line hidden
}
#line default
#line hidden
#region Base class
/// <summary>
/// Base class for this transformation
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public class PartitionsTemplateBase
{
#region Fields
private global::System.Text.StringBuilder generationEnvironmentField;
private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
private global::System.Collections.Generic.List<int> indentLengthsField;
private string currentIndentField = "";
private bool endsWithNewline;
private global::System.Collections.Generic.IDictionary<string, object> sessionField;
#endregion
#region Properties
/// <summary>
/// The string builder that generation-time code is using to assemble generated output
/// </summary>
protected System.Text.StringBuilder GenerationEnvironment
{
get
{
if ((this.generationEnvironmentField == null))
{
this.generationEnvironmentField = new global::System.Text.StringBuilder();
}
return this.generationEnvironmentField;
}
set
{
this.generationEnvironmentField = value;
}
}
/// <summary>
/// The error collection for the generation process
/// </summary>
public System.CodeDom.Compiler.CompilerErrorCollection Errors
{
get
{
if ((this.errorsField == null))
{
this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
}
return this.errorsField;
}
}
/// <summary>
/// A list of the lengths of each indent that was added with PushIndent
/// </summary>
private System.Collections.Generic.List<int> indentLengths
{
get
{
if ((this.indentLengthsField == null))
{
this.indentLengthsField = new global::System.Collections.Generic.List<int>();
}
return this.indentLengthsField;
}
}
/// <summary>
/// Gets the current indent we use when adding lines to the output
/// </summary>
public string CurrentIndent
{
get
{
return this.currentIndentField;
}
}
/// <summary>
/// Current transformation session
/// </summary>
public virtual global::System.Collections.Generic.IDictionary<string, object> Session
{
get
{
return this.sessionField;
}
set
{
this.sessionField = value;
}
}
#endregion
#region Transform-time helpers
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void Write(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
{
return;
}
// If we're starting off, or if the previous text ended with a newline,
// we have to append the current indent first.
if (((this.GenerationEnvironment.Length == 0)
|| this.endsWithNewline))
{
this.GenerationEnvironment.Append(this.currentIndentField);
this.endsWithNewline = false;
}
// Check if the current text ends with a newline
if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
{
this.endsWithNewline = true;
}
// This is an optimization. If the current indent is "", then we don't have to do any
// of the more complex stuff further down.
if ((this.currentIndentField.Length == 0))
{
this.GenerationEnvironment.Append(textToAppend);
return;
}
// Everywhere there is a newline in the text, add an indent after it
textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
// If the text ends with a newline, then we should strip off the indent added at the very end
// because the appropriate indent will be added when the next time Write() is called
if (this.endsWithNewline)
{
this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
}
else
{
this.GenerationEnvironment.Append(textToAppend);
}
}
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void WriteLine(string textToAppend)
{
this.Write(textToAppend);
this.GenerationEnvironment.AppendLine();
this.endsWithNewline = true;
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void Write(string format, params object[] args)
{
this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void WriteLine(string format, params object[] args)
{
this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Raise an error
/// </summary>
public void Error(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
this.Errors.Add(error);
}
/// <summary>
/// Raise a warning
/// </summary>
public void Warning(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
error.IsWarning = true;
this.Errors.Add(error);
}
/// <summary>
/// Increase the indent
/// </summary>
public void PushIndent(string indent)
{
if ((indent == null))
{
throw new global::System.ArgumentNullException("indent");
}
this.currentIndentField = (this.currentIndentField + indent);
this.indentLengths.Add(indent.Length);
}
/// <summary>
/// Remove the last indent that was added with PushIndent
/// </summary>
public string PopIndent()
{
string returnValue = "";
if ((this.indentLengths.Count > 0))
{
int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
if ((indentLength > 0))
{
returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
}
}
return returnValue;
}
/// <summary>
/// Remove any indentation
/// </summary>
public void ClearIndent()
{
this.indentLengths.Clear();
this.currentIndentField = "";
}
#endregion
#region ToString Helpers
/// <summary>
/// Utility class to produce culture-oriented representation of an object as a string.
/// </summary>
public class ToStringInstanceHelper
{
private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture;
/// <summary>
/// Gets or sets format provider to be used by ToStringWithCulture method.
/// </summary>
public System.IFormatProvider FormatProvider
{
get
{
return this.formatProviderField ;
}
set
{
if ((value != null))
{
this.formatProviderField = value;
}
}
}
/// <summary>
/// This is called from the compile/run appdomain to convert objects within an expression block to a string
/// </summary>
public string ToStringWithCulture(object objectToConvert)
{
if ((objectToConvert == null))
{
throw new global::System.ArgumentNullException("objectToConvert");
}
System.Type t = objectToConvert.GetType();
System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
typeof(System.IFormatProvider)});
if ((method == null))
{
return objectToConvert.ToString();
}
else
{
return ((string)(method.Invoke(objectToConvert, new object[] {
this.formatProviderField })));
}
}
}
private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
/// <summary>
/// Helper to produce culture-oriented representation of an object as a string
/// </summary>
public ToStringInstanceHelper ToStringHelper
{
get
{
return this.toStringHelperField;
}
}
#endregion
}
#endregion
}
| 445 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Examples
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class ExampleCode : Generators.BaseGenerator
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
this.Write("using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing Syste" +
"m.Text;\r\nusing System.Threading.Tasks;\r\n\r\nusing ");
#line 12 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(";\r\nusing ");
#line 13 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model;\r\n\r\nnamespace AWSSDKDocSamples.");
#line 15 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Generated\r\n{\r\n\tclass ");
#line 17 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("Samples : ISample\r\n\t{\r\n");
#line 19 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
foreach(var operation in this.Config.ServiceModel.Operations)
{
foreach(var example in operation.Examples)
{
#line default
#line hidden
this.Write("\t\tpublic void ");
#line 25 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
#line 25 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
this.Write("()\r\n\t\t{\r\n\t\t\t#region ");
#line 27 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(example.Id));
#line default
#line hidden
this.Write("\r\n\r\n\t\t\tvar client = new Amazon");
#line 29 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("Client();\r\n\t\t\tvar response = client.");
#line 30 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
this.Write("(new ");
#line 30 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
this.Write("Request \r\n\t\t\t{\r\n");
#line 32 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
var lines = example.GetRequestAssignments(currentIndent: 16);
foreach(var line in lines)
{
#line default
#line hidden
this.Write("\t\t\t\t");
#line 37 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(line));
#line default
#line hidden
this.Write("\r\n");
#line 38 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
}
#line default
#line hidden
this.Write("\t\t\t});\r\n\r\n");
#line 43 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
var responses = example.GetResponseAssignments();
foreach(var resp in responses)
{
#line default
#line hidden
this.Write("\t\t\t");
#line 48 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(resp));
#line default
#line hidden
this.Write("\r\n");
#line 49 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
}
#line default
#line hidden
this.Write("\r\n\t\t\t#endregion\r\n\t\t}\r\n\r\n");
#line 56 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleCode.tt"
}
}
#line default
#line hidden
this.Write("\t\t\r\n\t\t# region ISample Members\r\n\t\tpublic virtual void Run()\r\n\t\t{\r\n\r\n\t\t}\r\n\t\t# endr" +
"egion\r\n\r\n\t}\r\n}\r\n");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 186 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Examples
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class ExampleMetadata : Generators.BaseGenerator
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
this.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<docs>\r\n");
#line 8 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
var servicename = this.Config.Namespace.Split('.').Last();
foreach(var operation in this.Config.ServiceModel.Operations)
{
foreach(var example in operation.Examples)
{
#line default
#line hidden
this.Write("\t<doc>\r\n\t\t<members>\r\n\t\t\t<member name=\"M:");
#line 17 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".IAmazon");
#line 17 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write(".");
#line 17 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
this.Write("(");
#line 17 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.");
#line 17 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
this.Write("Request)\" />\r\n\t\t\t<member name=\"M:");
#line 18 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Amazon");
#line 18 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ClassName));
#line default
#line hidden
this.Write("Client.");
#line 18 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
this.Write("(");
#line 18 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.");
#line 18 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
this.Write("Request)\" />\r\n\t\t\t<member name=\"T:");
#line 19 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.");
#line 19 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
this.Write("Request\" />\r\n\t\t\t<member name=\"T:");
#line 20 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.");
#line 20 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Name));
#line default
#line hidden
this.Write("Response\" />\r\n\t\t</members>\r\n\t\t<value>\r\n\t\t\t<example>\r\n\t\t\t\t<para>\r\n\t\t\t\t\t");
#line 25 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(example.Description));
#line default
#line hidden
this.Write("\r\n\t\t\t\t</para>\r\n\t\t\t\t<code\r\n\t\t\t\t\ttitle=\"");
#line 28 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(example.Title));
#line default
#line hidden
this.Write("\"\r\n\t\t\t\t\tsource=\".\\AWSSDKDocSamples\\");
#line 29 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(servicename));
#line default
#line hidden
this.Write("\\");
#line 29 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(servicename));
#line default
#line hidden
this.Write(".GeneratedSamples.cs\"\r\n\t\t\t\t\tregion=\"");
#line 30 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(example.Id));
#line default
#line hidden
this.Write("\" />\r\n\t\t\t</example>\r\n\t\t</value>\r\n\t</doc>\r\n");
#line 34 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Examples\ExampleMetadata.tt"
}
}
#line default
#line hidden
this.Write("</docs>");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 195 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class AWSQueryEC2ResponseUnmarshaller : BaseResponseUnmarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("namespace ");
#line 11 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Response U" +
"nmarshaller for ");
#line 14 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" operation\r\n /// </summary> \r\n public class ");
#line 16 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@"ResponseUnmarshaller : EC2ResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name=""context""></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
");
#line 25 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("Response response = new ");
#line 25 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("Response();\r\n\r\n");
#line 27 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
if (this.HasSuppressedResult)
{
#line default
#line hidden
this.Write(" while (context.Read())\r\n {\r\n\t\t\t\r\n\t\t\t}\r\n");
#line 34 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(@" int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth = 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
");
#line 49 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
if(this.Structure != null)
{
if(this.IsWrapped)
{
#line default
#line hidden
this.Write(" if ( context.TestExpression(\".\", targetDepth))\r\n " +
" {\r\n response.");
#line 57 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(MemberAccessorFor(this.Structure.Name)));
#line default
#line hidden
this.Write(" = ");
#line 57 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Structure.Name));
#line default
#line hidden
this.Write("Unmarshaller.Instance.Unmarshall(context);\r\n continue;\r\n " +
" }\r\n");
#line 60 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
else
{
foreach (var member in this.Structure.Members)
{
var testExpression = GeneratorHelpers.DetermineAWSQueryTestExpression(member);
#line default
#line hidden
this.Write(" if (context.TestExpression(\"");
#line 68 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(testExpression));
#line default
#line hidden
this.Write("\", targetDepth))\r\n {\r\n var unmarshaller" +
" = ");
#line 70 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n");
#line 71 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
if (member.IsList)
{
#line default
#line hidden
this.Write(" var item = unmarshaller.Unmarshall(context);\r\n " +
" response.");
#line 76 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(MemberAccessorFor(member.PropertyName)));
#line default
#line hidden
this.Write(".Add(item);\r\n");
#line 77 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(" response.");
#line 82 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(MemberAccessorFor(member.PropertyName)));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n");
#line 83 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" continue;\r\n }\r\n");
#line 88 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
}
}
#line default
#line hidden
this.Write(" } \r\n }\r\n");
#line 95 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(@"
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name=""context""></param>
/// <param name=""innerException""></param>
/// <param name=""statusCode""></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
");
#line 112 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
foreach (var exception in this.Operation.Exceptions)
{
#line default
#line hidden
this.Write(" if (errorResponse.Code != null && errorResponse.Code.Equals(\"");
#line 116 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Code));
#line default
#line hidden
this.Write("\"))\r\n {\r\n return new ");
#line 118 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Name));
#line default
#line hidden
this.Write("(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, e" +
"rrorResponse.RequestId, statusCode);\r\n }\r\n");
#line 120 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" return new ");
#line 123 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.BaseException));
#line default
#line hidden
this.Write("(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, e" +
"rrorResponse.RequestId, statusCode);\r\n }\r\n");
#line 125 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.AddResponseSingletonMethod();
#line default
#line hidden
this.Write(" }\r\n}\r\n");
return this.GenerationEnvironment.ToString();
}
#line 130 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
// if the result fields have been wrapped in a subordinate structure, wire the accessor
// to use it when addressing a member
string MemberAccessorFor(string memberName)
{
return string.IsNullOrEmpty(WrappedResultMember) ? memberName : WrappedResultMember;
}
#line default
#line hidden
}
#line default
#line hidden
}
| 324 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class AWSQueryExceptionUnmarshaller : BaseResponseUnmarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("namespace ");
#line 11 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Response U" +
"nmarshaller for ");
#line 14 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" operation\r\n /// </summary> \r\n public class ");
#line 16 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("Unmarshaller : IErrorResponseUnmarshaller<");
#line 16 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(", XmlUnmarshallerContext>\r\n {\r\n /// <summary>\r\n /// Unmarshaller" +
" the response from the service to the response class.\r\n /// </summary> \r" +
"\n /// <param name=\"context\"></param>\r\n /// <returns></returns>\r\n " +
" public ");
#line 23 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@" Unmarshall(XmlUnmarshallerContext context)
{
return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse());
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name=""context""></param>
/// <param name=""errorResponse""></param>
/// <returns></returns>
public ");
#line 34 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" Unmarshall(XmlUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse" +
" errorResponse)\r\n {\r\n ");
#line 36 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" response = new ");
#line 36 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@"(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
");
#line 49 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
if(this.Structure != null)
{
foreach (var member in this.Structure.Members)
{
var testExpression = GeneratorHelpers.DetermineAWSQueryTestExpression(member);
#line default
#line hidden
this.Write(" if (context.TestExpression(\"");
#line 56 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(testExpression));
#line default
#line hidden
this.Write("\", targetDepth))\r\n {\r\n");
#line 58 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
if (member.IsMap || member.IsList)
{
#line default
#line hidden
this.Write(" var item = ");
#line 62 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(".Unmarshall(context);\r\n response.");
#line 63 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(MemberAccessorFor(member.PropertyName)));
#line default
#line hidden
this.Write(".Add(item);\r\n");
#line 64 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(" response.");
#line 69 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(MemberAccessorFor(member.PropertyName)));
#line default
#line hidden
this.Write(" = ");
#line 69 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(".Unmarshall(context);\r\n");
#line 70 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" }\r\n");
#line 74 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
}
}
#line default
#line hidden
this.Write(" }\r\n }\r\n return response;\r\n }\r\n\r\n");
#line 83 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
this.AddStructureSingletonMethod();
#line default
#line hidden
this.Write(" }\r\n}\r\n");
return this.GenerationEnvironment.ToString();
}
#line 88 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryExceptionUnmarshaller.tt"
// if the result fields have been wrapped in a subordinate structure, wire the accessor
// to use it when addressing a member
string MemberAccessorFor(string memberName)
{
if (string.IsNullOrEmpty(WrappedResultMember))
return memberName;
return string.Concat(WrappedResultMember, ".", memberName);
}
#line default
#line hidden
}
#line default
#line hidden
}
| 247 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class AWSQueryRequestMarshaller : BaseRequestMarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("namespace ");
#line 11 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// ");
#line 14 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write(" Request Marshaller\r\n /// </summary> \r\n public class ");
#line 16 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("RequestMarshaller : IMarshaller<IRequest, ");
#line 16 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write(@"Request> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name=""input""></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((");
#line 25 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write(@"Request)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name=""publicRequest""></param>
/// <returns></returns>
public IRequest Marshall(");
#line 33 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("Request publicRequest)\r\n {\r\n IRequest request = new DefaultRequ" +
"est(publicRequest, \"");
#line 35 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write("\");\r\n request.Parameters.Add(\"Action\", \"");
#line 36 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("\");\r\n request.Parameters.Add(\"Version\", \"");
#line 37 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ServiceModel.APIVersion));
#line default
#line hidden
this.Write("\");\r\n\r\n if(publicRequest != null)\r\n {\r\n");
#line 41 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
var requestStructure = this.Operation.RequestStructure;
if(requestStructure != null)
ProcessMembers(0, "", "publicRequest", requestStructure.Members);
#line default
#line hidden
this.Write(" }\r\n return request;\r\n }\r\n\t\t\t");
#line 49 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.AddRequestSingletonMethod();
#line default
#line hidden
this.Write(" }\r\n}\r\n\r\n");
return this.GenerationEnvironment.ToString();
}
#line 55 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
void ProcessMembers(int level, string parameterContext, string variableName, IEnumerable<Member> members)
{
string variableNameFragment = variableName.Replace(".", string.Empty);
foreach(var member in members)
{
if (GeneratorHelpers.UseCustomMarshall(member, this.Operation))
continue;
var marshallName = GeneratorHelpers.DetermineAWSQueryMarshallName(member, this.Operation);
#line default
#line hidden
#line 66 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 66 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" if(");
#line default
#line hidden
#line 66 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 66 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 66 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 66 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("())\r\n");
#line default
#line hidden
#line 67 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 67 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" {\r\n");
#line default
#line hidden
#line 68 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
if(member.IsList )
{
string context = ComposeContext(parameterContext, marshallName);
string listItemContext = ComposeContext(context,
GeneratorHelpers.DetermineAWSQueryListMemberPrefix(member),
variableNameFragment + "listValueIndex",
GeneratorHelpers.DetermineAWSQueryListMemberSuffix(this.Operation, member));
#line default
#line hidden
#line 77 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 77 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" int ");
#line default
#line hidden
#line 77 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableNameFragment));
#line default
#line hidden
#line 77 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("listValueIndex = 1;\r\n");
#line default
#line hidden
#line 78 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 78 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" foreach(var ");
#line default
#line hidden
#line 78 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableNameFragment));
#line default
#line hidden
#line 78 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("listValue in ");
#line default
#line hidden
#line 78 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 78 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 78 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 78 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(")\r\n");
#line default
#line hidden
#line 79 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 79 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" {\r\n");
#line default
#line hidden
#line 80 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
if(member.Shape.ListShape.IsStructure)
{
ProcessMembers(level + 2, listItemContext, variableNameFragment + "listValue", member.Shape.ListShape.Members);
}
else
{
if(string.IsNullOrEmpty(member.CustomMarshallerTransformation))
{
#line default
#line hidden
#line 90 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 90 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 90 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listItemContext));
#line default
#line hidden
#line 90 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", ");
#line default
#line hidden
#line 90 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.Shape.ListShape.PrimitiveMarshaller(MarshallLocation.Body)));
#line default
#line hidden
#line 90 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 90 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableNameFragment));
#line default
#line hidden
#line 90 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("listValue));\r\n");
#line default
#line hidden
#line 91 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
else
{
#line default
#line hidden
#line 96 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 96 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 96 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listItemContext));
#line default
#line hidden
#line 96 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", ");
#line default
#line hidden
#line 96 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.CustomMarshallerTransformation + "(" + variableNameFragment + "listValue)"));
#line default
#line hidden
#line 96 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 97 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
}
#line default
#line hidden
#line 101 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 101 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" ");
#line default
#line hidden
#line 101 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableNameFragment));
#line default
#line hidden
#line 101 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("listValueIndex++;\r\n");
#line default
#line hidden
#line 102 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 102 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" }\r\n");
#line default
#line hidden
#line 103 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
else if(member.IsMap)
{
string context = ComposeContext(parameterContext, marshallName);
string mapItemContext = ComposeContext(context, member.Shape.IsFlattened ? "" : "entry", "mapIndex");
string mapKeyContext = ComposeContext(mapItemContext, member.Shape.KeyMarshallName);
string mapValueContext = ComposeContext(mapItemContext, member.Shape.ValueMarshallName);
#line default
#line hidden
#line 112 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 112 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" int mapIndex = 1;\r\n");
#line default
#line hidden
#line 113 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 113 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" foreach(var key in ");
#line default
#line hidden
#line 113 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 113 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 113 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 113 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".Keys)\r\n");
#line default
#line hidden
#line 114 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 114 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" {\r\n");
#line default
#line hidden
#line 115 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 115 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" ");
#line default
#line hidden
#line 115 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.Shape.ValueShape.IsStructure ? member.Shape.ValueShape.Name : member.Shape.ValueShape.GetPrimitiveType()));
#line default
#line hidden
#line 115 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" value;\r\n");
#line default
#line hidden
#line 116 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 116 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" bool hasValue = ");
#line default
#line hidden
#line 116 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 116 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 116 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 116 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".TryGetValue(key, out value);\r\n");
#line default
#line hidden
#line 117 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 117 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 117 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(mapKeyContext));
#line default
#line hidden
#line 117 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", ");
#line default
#line hidden
#line 117 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.Shape.KeyShape.PrimitiveMarshaller(MarshallLocation.Body)));
#line default
#line hidden
#line 117 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("(key));\r\n");
#line default
#line hidden
#line 118 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 118 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" if (hasValue)\r\n");
#line default
#line hidden
#line 119 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 119 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" {\r\n");
#line default
#line hidden
#line 120 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
if(member.Shape.ValueShape.IsStructure)
{
ProcessMembers(level + 3, mapValueContext, "value", member.Shape.ValueShape.Members);
}
else
{
if(string.IsNullOrEmpty(member.CustomMarshallerTransformation))
{
#line default
#line hidden
#line 130 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 130 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 130 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(mapValueContext));
#line default
#line hidden
#line 130 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", ");
#line default
#line hidden
#line 130 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.Shape.ValueShape.PrimitiveMarshaller(MarshallLocation.Body)));
#line default
#line hidden
#line 130 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("(value));\r\n");
#line default
#line hidden
#line 131 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
else
{
#line default
#line hidden
#line 135 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 135 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 135 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(mapValueContext));
#line default
#line hidden
#line 135 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", ");
#line default
#line hidden
#line 135 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.CustomMarshallerTransformation + "(value)"));
#line default
#line hidden
#line 135 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 136 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
}
#line default
#line hidden
#line 140 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 140 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" }\r\n");
#line default
#line hidden
#line 141 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 141 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" mapIndex++;\r\n");
#line default
#line hidden
#line 142 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 142 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" }\r\n");
#line default
#line hidden
#line 143 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
else if(member.IsStructure)
{
string context = ComposeContext(parameterContext, marshallName);
ProcessMembers(level + 1, context, variableName + "." + member.PropertyName, member.Shape.Members);
}
else
{
string context = ComposeContext(parameterContext, marshallName);
string memberProperty = variableName + "." + member.PropertyName + (member.UseNullable ? ".Value" : string.Empty);
if(string.IsNullOrEmpty(member.CustomMarshallerTransformation))
{
#line default
#line hidden
#line 157 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 157 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 157 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(context));
#line default
#line hidden
#line 157 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", ");
#line default
#line hidden
#line 157 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PrimitiveMarshaller));
#line default
#line hidden
#line 157 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 157 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(memberProperty));
#line default
#line hidden
#line 157 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 158 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
else
{
#line default
#line hidden
#line 162 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 162 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 162 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(context));
#line default
#line hidden
#line 162 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", ");
#line default
#line hidden
#line 162 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.CustomMarshallerTransformation));
#line default
#line hidden
#line 162 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 162 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(memberProperty));
#line default
#line hidden
#line 162 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 163 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
if(member.IsIdempotent)
{
#line default
#line hidden
#line 168 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 168 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" \t\t\t }\r\n");
#line default
#line hidden
#line 169 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 169 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" \t\t\t else if(!(");
#line default
#line hidden
#line 169 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 169 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 169 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 169 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write("()))\r\n");
#line default
#line hidden
#line 170 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 170 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" \t\t\t {\r\n");
#line default
#line hidden
#line 171 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 171 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" request.Parameters.Add(");
#line default
#line hidden
#line 171 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(context));
#line default
#line hidden
#line 171 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(", StringUtils.FromString(Guid.NewGuid().ToString()));\r\n");
#line default
#line hidden
#line 172 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
}
#line default
#line hidden
#line 176 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 176 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
this.Write(" }\r\n");
#line default
#line hidden
#line 177 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryRequestMarshaller.tt"
}
}
string ComposeContext(string context, string marshallName)
{
return ComposeContext(context, marshallName, null, null);
}
string ComposeContext(string context, string marshallName, string variableName)
{
return ComposeContext(context, marshallName, variableName, null);
}
string ComposeContext(string context, string marshallName, string variableName, string suffixMember)
{
string nc = context;
if (!string.IsNullOrEmpty(marshallName))
nc = AppendText(nc, marshallName);
if (!string.IsNullOrEmpty(variableName))
nc = AppendVariable(nc, variableName);
if (!string.IsNullOrEmpty(suffixMember))
nc = AppendText(nc, suffixMember);
return nc;
}
private static char quoteChar = '\"';
private static string quote = quoteChar.ToString();
string AppendVariable(string context, string variable)
{
variable = variable.Trim(quoteChar);
return Append(context, variable);
}
string AppendText(string context, string text)
{
if (!text.StartsWith(quote))
text = quote + text;
if (!text.EndsWith(quote))
text = text + quote;
return Append(context, text);
}
string Append(string context, string text)
{
string nc = context;
if (!string.IsNullOrEmpty(nc) && !nc.EndsWith("."))
nc += " + \".\" + ";
nc += text;
return nc;
}
#line default
#line hidden
}
#line default
#line hidden
}
| 1,220 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class AWSQueryResponseUnmarshaller : BaseResponseUnmarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("namespace ");
#line 11 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Response U" +
"nmarshaller for ");
#line 14 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" operation\r\n /// </summary> \r\n public class ");
#line 16 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@"ResponseUnmarshaller : XmlResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name=""context""></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
");
#line 25 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("Response response = new ");
#line 25 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write(@"Response();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.IsStartElement)
{
if(context.TestExpression(""");
#line 33 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@"Result"", 2))
{
UnmarshallResult(context, response);
continue;
}
if (context.TestExpression(""ResponseMetadata"", 2))
{
response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
}
}
}
return response;
}
");
#line 49 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
if (this.Structure == null || this.Structure.Members.Count == 0)
{
#line default
#line hidden
this.Write("\t\t[System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Usage\", \"CA1801:Rev" +
"iewUnusedParameters\", MessageId=\"response\")]\r\n");
#line 54 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" private static void UnmarshallResult(XmlUnmarshallerContext context, ");
#line 57 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@"Response response)
{
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
");
#line 71 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
if(this.Structure != null)
{
if(this.IsWrapped)
{
#line default
#line hidden
this.Write(" if ( context.TestExpression(\"");
#line 77 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Structure.MarshallName));
#line default
#line hidden
this.Write("\", targetDepth))\r\n {\r\n response.");
#line 79 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(MemberAccessorFor(this.Structure.Name)));
#line default
#line hidden
this.Write(" = ");
#line 79 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Structure.Name));
#line default
#line hidden
this.Write("Unmarshaller.Instance.Unmarshall(context);\r\n continue;\r\n " +
" }\r\n");
#line 82 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
}
else
{
foreach (var member in this.Structure.Members)
{
var testExpression = GeneratorHelpers.DetermineAWSQueryTestExpression(member);
#line default
#line hidden
this.Write(" if (context.TestExpression(\"");
#line 90 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(testExpression));
#line default
#line hidden
this.Write("\", targetDepth))\r\n {\r\n var unmarshaller" +
" = ");
#line 92 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n");
#line 93 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
if (member.IsMap || member.IsList)
{
#line default
#line hidden
this.Write(" var item = unmarshaller.Unmarshall(context);\r\n " +
" response.");
#line 98 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(MemberAccessorFor(member.PropertyName)));
#line default
#line hidden
this.Write(".Add(item);\r\n");
#line 99 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(" response.");
#line 104 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(MemberAccessorFor(member.PropertyName)));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n");
#line 105 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" continue;\r\n }\r\n");
#line 110 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
}
}
}
#line default
#line hidden
this.Write(@" }
}
return;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name=""context""></param>
/// <param name=""innerException""></param>
/// <param name=""statusCode""></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null))
{
");
#line 140 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
foreach (var exception in this.Operation.Exceptions)
{
#line default
#line hidden
this.Write(" if (errorResponse.Code != null && errorResponse.Code.Equals(\"");
#line 144 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Code));
#line default
#line hidden
this.Write("\"))\r\n {\r\n return ");
#line 146 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Name));
#line default
#line hidden
this.Write("Unmarshaller.Instance.Unmarshall(contextCopy, errorResponse);\r\n }\r" +
"\n");
#line 148 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" }\r\n return new ");
#line 152 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.BaseException));
#line default
#line hidden
this.Write("(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, e" +
"rrorResponse.RequestId, statusCode);\r\n }\r\n");
#line 154 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
this.AddResponseSingletonMethod();
#line default
#line hidden
this.Write(" }\r\n}\r\n");
return this.GenerationEnvironment.ToString();
}
#line 159 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryResponseUnmarshaller.tt"
// if the result fields have been wrapped in a subordinate structure, wire the accessor
// to use it when addressing a member
string MemberAccessorFor(string memberName)
{
if (string.IsNullOrEmpty(WrappedResultMember))
return memberName;
return string.Concat(WrappedResultMember, ".", memberName);
}
#line default
#line hidden
}
#line default
#line hidden
}
| 377 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class AWSQueryStructureUnmarshaller : BaseResponseUnmarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("namespace ");
#line 11 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Response U" +
"nmarshaller for ");
#line 14 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" Object\r\n /// </summary> \r\n public class ");
#line 16 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("Unmarshaller : IUnmarshaller<");
#line 16 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(", XmlUnmarshallerContext>, IUnmarshaller<");
#line 16 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(", JsonUnmarshallerContext>\r\n {\r\n /// <summary>\r\n /// Unmarshalle" +
"r the response from the service to the response class.\r\n /// </summary> " +
"\r\n /// <param name=\"context\"></param>\r\n /// <returns></returns>\r\n " +
" public ");
#line 23 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" Unmarshall(XmlUnmarshallerContext context)\r\n {\r\n ");
#line 25 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" unmarshalledObject = new ");
#line 25 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@"();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
");
#line 36 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
if(this.Structure != null)
{
foreach (var member in this.Structure.Members)
{
var testExpression = GeneratorHelpers.DetermineAWSQueryTestExpression(member);
#line default
#line hidden
this.Write(" if (context.TestExpression(\"");
#line 43 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(testExpression));
#line default
#line hidden
this.Write("\", targetDepth))\r\n {\r\n var unmarshaller" +
" = ");
#line 45 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n");
#line 46 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
if (member.IsMap || member.IsList)
{
#line default
#line hidden
this.Write(" var item = unmarshaller.Unmarshall(context);\r\n " +
" unmarshalledObject.");
#line 51 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(".Add(item);\r\n");
#line 52 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(" unmarshalledObject.");
#line 57 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n");
#line 58 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" continue;\r\n }\r\n");
#line 63 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
}
}
#line default
#line hidden
this.Write(@" }
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return unmarshalledObject;
}
}
return unmarshalledObject;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name=""context""></param>
/// <returns></returns>
public ");
#line 82 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" Unmarshall(JsonUnmarshallerContext context)\r\n {\r\n return null;" +
"\r\n }\r\n\r\n\r\n");
#line 88 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryStructureUnmarshaller.tt"
this.AddStructureSingletonMethod();
#line default
#line hidden
this.Write(" }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 235 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class BaseMarshaller : Generators.BaseGenerator
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
this.Write("\r\n");
return this.GenerationEnvironment.ToString();
}
#line 9 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
// Adds the neccesary namespaces for the marshaller
protected void AddCommonUsingStatements()
{
#line default
#line hidden
#line 13 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("using System;\r\nusing System.Collections.Generic;\r\nusing System.Globalization;\r\nus" +
"ing System.IO;\r\nusing System.Text;\r\nusing System.Xml.Serialization;\r\n\r\nusing ");
#line default
#line hidden
#line 21 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
#line 21 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".Model;\r\nusing Amazon.Runtime;\r\nusing Amazon.Runtime.Internal;\r\nusing Amazon.Runt" +
"ime.Internal.Transform;\r\nusing Amazon.Runtime.Internal.Util;\r\n");
#line default
#line hidden
#line 26 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
#line default
#line hidden
#line 30 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
// Only applicable for rest-json and rest-xml
// Generates code to add members to the header of the request
// If it's a custom marshaller then it calls the custom marshaller first
protected void ProcessHeaderMembers(string variableName, IEnumerable<Member> members)
{
foreach(var member in members)
{
#line default
#line hidden
#line 38 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\r\n if (");
#line default
#line hidden
#line 39 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 39 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 39 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 39 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("()) \r\n {\r\n");
#line default
#line hidden
#line 41 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
if (member.CustomMarshallerTransformation != null)
{
#line default
#line hidden
#line 44 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\t\trequest.Headers[\"");
#line default
#line hidden
#line 45 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 45 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\"] = ");
#line default
#line hidden
#line 45 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.CustomMarshallerTransformation));
#line default
#line hidden
#line 45 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 45 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 45 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 45 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 45 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 46 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else if (member.IsJsonValue)
{
#line default
#line hidden
#line 50 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\t\trequest.Headers[\"");
#line default
#line hidden
#line 51 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 51 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(");
#line default
#line hidden
#line 51 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 51 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 51 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 51 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 52 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else
{
if (member.IsList)
{
if (member.ModelShape.ModelListShape.IsString || member.ModelShape.ModelListShape.IsEnum)
{
#line default
#line hidden
#line 60 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" request.Headers[\"");
#line default
#line hidden
#line 61 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 61 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\"] = StringUtils.FromList(");
#line default
#line hidden
#line 61 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 61 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 61 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 61 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 62 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else
{
throw new InvalidDataException("[{member.ModelName}]: Marshalling lists as header values is only support for lists of strings or list of enums.");
}
}
else if (member.IsMap)
{
#line default
#line hidden
#line 71 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" //Map of headers with prefix \"");
#line default
#line hidden
#line 72 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 72 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\".\r\n foreach (var kvp");
#line default
#line hidden
#line 73 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 73 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" in ");
#line default
#line hidden
#line 73 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 73 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 73 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 73 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(")\r\n {\r\n");
#line default
#line hidden
#line 75 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
// Dictionary<string, string>
if (member.ModelShape.ValueShape.IsString)
{
#line default
#line hidden
#line 79 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" request.Headers[$\"");
#line default
#line hidden
#line 80 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 80 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("{kvp");
#line default
#line hidden
#line 80 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 80 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".Key}\"] = kvp");
#line default
#line hidden
#line 80 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 80 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".Value;\r\n");
#line default
#line hidden
#line 81 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
// Dictionary<string, List<string>>
else if (member.ModelShape.ValueShape?.ListShape?.IsString == true)
{
#line default
#line hidden
#line 86 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" request.Headers[$\"");
#line default
#line hidden
#line 87 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 87 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("{kvp");
#line default
#line hidden
#line 87 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 87 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".Key}\"] = string.Join(\",\", kvp");
#line default
#line hidden
#line 87 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 87 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".Value.ToArray());\r\n");
#line default
#line hidden
#line 88 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else
{
throw new InvalidDataException("[{member.ModelName}]: Invalid header map shapes. Header Maps must have a value of either a string or a list of strings: {member.ModelShape.ValueShape.Name}");
}
#line default
#line hidden
#line 94 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" }\r\n");
#line default
#line hidden
#line 96 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else if(member.Shape.IsString)
{
#line default
#line hidden
#line 100 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\t\trequest.Headers[\"");
#line default
#line hidden
#line 101 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 101 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\"] = ");
#line default
#line hidden
#line 101 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 101 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 101 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 101 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(";\r\n");
#line default
#line hidden
#line 102 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else
{
#line default
#line hidden
#line 106 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\t\trequest.Headers[\"");
#line default
#line hidden
#line 107 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 107 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\"] = ");
#line default
#line hidden
#line 107 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PrimitiveMarshaller));
#line default
#line hidden
#line 107 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 107 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 107 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 107 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 107 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 108 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
}
#line default
#line hidden
#line 111 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" }\r\n");
#line default
#line hidden
#line 113 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
}
// Only applicable for rest-json and rest-xml
// Generates code to add the operation's requestURIMembers to the PathResources request dictionary
protected void ProcessUriMembers(string variableName, Operation operation)
{
foreach(var member in operation.RequestUriMembers)
{
bool isGreedy = false;
var marshallLocationName = operation.GetUriResourcePathTarget(member, out isGreedy);
if (member.model.Customizations.SkipUriPropertyValidations.Contains(member.PropertyName))
{
if(isGreedy)
{
#line default
#line hidden
#line 130 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\trequest.AddPathResource(\"");
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(marshallLocationName));
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\", ");
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("() ? ");
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PrimitiveMarshaller));
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".TrimStart(\'/\')) : string.Empty);\r\n");
#line default
#line hidden
#line 132 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else
{
#line default
#line hidden
#line 136 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\trequest.AddPathResource(\"");
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(marshallLocationName));
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\", ");
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("() ? ");
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PrimitiveMarshaller));
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(") : string.Empty);\r\n");
#line default
#line hidden
#line 138 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
}
else
{
#line default
#line hidden
#line 144 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" if (!");
#line default
#line hidden
#line 145 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 145 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 145 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 145 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("())\r\n throw new ");
#line default
#line hidden
#line 146 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.BaseException));
#line default
#line hidden
#line 146 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("(\"Request object does not have required field ");
#line default
#line hidden
#line 146 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 146 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" set\");\r\n");
#line default
#line hidden
#line 147 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
if(isGreedy)
{
#line default
#line hidden
#line 150 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\trequest.AddPathResource(\"");
#line default
#line hidden
#line 151 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(marshallLocationName));
#line default
#line hidden
#line 151 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\", ");
#line default
#line hidden
#line 151 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PrimitiveMarshaller));
#line default
#line hidden
#line 151 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 151 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 151 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 151 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 151 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".TrimStart(\'/\')));\r\n");
#line default
#line hidden
#line 152 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else
{
#line default
#line hidden
#line 156 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\trequest.AddPathResource(\"");
#line default
#line hidden
#line 157 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(marshallLocationName));
#line default
#line hidden
#line 157 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\", ");
#line default
#line hidden
#line 157 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PrimitiveMarshaller));
#line default
#line hidden
#line 157 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 157 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 157 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 157 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 157 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 158 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
}
}
}
protected void ProcessRequestUri(Operation operation)
{
foreach(var staticQueryParam in operation.StaticQueryParameters)
{
if(staticQueryParam.Value != null)
{
#line default
#line hidden
#line 170 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\trequest.AddSubResource(\"");
#line default
#line hidden
#line 171 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(staticQueryParam.Key));
#line default
#line hidden
#line 171 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\", \"");
#line default
#line hidden
#line 171 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(staticQueryParam.Value));
#line default
#line hidden
#line 171 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\");\r\n");
#line default
#line hidden
#line 172 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else
{
#line default
#line hidden
#line 176 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\trequest.AddSubResource(\"");
#line default
#line hidden
#line 177 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(staticQueryParam.Key));
#line default
#line hidden
#line 177 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\");\r\n");
#line default
#line hidden
#line 178 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
}
}
// Only applicable for rest-json and rest-xml
// Generates code to add any operation query members to the query string for the request
// If the marshaller is customized, it marshalls the value before changing it to a string
protected void ProcessQueryStringMembers(string variableName, Operation operation)
{
if(operation.RequestHasQueryStringMembers)
{
foreach(var member in operation.RequestQueryStringMembers)
{
#line default
#line hidden
#line 192 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\t\r\n\t\t\tif (");
#line default
#line hidden
#line 193 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 193 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 193 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 193 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("())\r\n");
#line default
#line hidden
#line 194 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
if (member.CustomMarshallerTransformation != null)
{
#line default
#line hidden
#line 197 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\t\trequest.Parameters.Add(\"");
#line default
#line hidden
#line 198 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 198 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\", ");
#line default
#line hidden
#line 198 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.CustomMarshallerTransformation));
#line default
#line hidden
#line 198 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 198 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 198 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 198 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 198 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 199 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else if (member.IsMap)
{
if(!member.Shape.ValueShape.IsString)
{
throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture,
"Marshalling map with value type of {0} as query string param is not implemented.",
member.Shape.ValueShape.Type));
}
#line default
#line hidden
#line 209 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" {\r\n foreach(var kvp in ");
#line default
#line hidden
#line 211 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 211 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 211 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 211 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(")\r\n {\r\n request.Parameters.Add(kvp.Key, kvp.Val" +
"ue);\r\n }\r\n }\r\n");
#line default
#line hidden
#line 216 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else if (member.IsList)
{
if(!member.Shape.ListShape.IsString && !member.Shape.ListShape.IsDouble)
{
throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture,
"Marshalling list of {0} as query string param is not implemented.",
member.Shape.ListShape.Type));
}
#line default
#line hidden
#line 226 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" request.ParameterCollection.Add(\"");
#line default
#line hidden
#line 227 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 227 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\", ");
#line default
#line hidden
#line 227 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 227 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 227 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 227 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 228 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else
{
#line default
#line hidden
#line 232 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\t\t\t\trequest.Parameters.Add(\"");
#line default
#line hidden
#line 233 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 233 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\", ");
#line default
#line hidden
#line 233 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PrimitiveMarshaller));
#line default
#line hidden
#line 233 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 233 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 233 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 233 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 233 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 234 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
if(member.IsIdempotent)
{
#line default
#line hidden
#line 238 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" else \r\n request.Parameters.Add(\"");
#line default
#line hidden
#line 240 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 240 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\", System.Guid.NewGuid().ToString());\r\n \r\n");
#line default
#line hidden
#line 242 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
}
}
}
// Only applicable for rest-json and rest-xml
// Generates code to add the operation's hostPrefixMembers to the request's HostPrefix
protected void ProcessEndpointHostPrefixMembers(string variableName, Operation operation)
{
if(operation.RequestHostPrefixMembers.Count() > 0)
{
#line default
#line hidden
#line 254 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\r\n var hostPrefixLabels = new\r\n {\r\n");
#line default
#line hidden
#line 258 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
foreach(var member in operation.RequestHostPrefixMembers)
{
#line default
#line hidden
#line 262 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" ");
#line default
#line hidden
#line 262 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 262 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" = ");
#line default
#line hidden
#line 262 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PrimitiveMarshaller));
#line default
#line hidden
#line 262 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 262 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 262 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 262 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 262 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("),\r\n");
#line default
#line hidden
#line 263 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
#line default
#line hidden
#line 265 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" };\r\n\r\n");
#line default
#line hidden
#line 268 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
foreach(var member in operation.RequestHostPrefixMembers)
{
#line default
#line hidden
#line 271 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" if (!HostPrefixUtils.IsValidLabelValue(hostPrefixLabels.");
#line default
#line hidden
#line 272 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 272 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("))\r\n throw new ");
#line default
#line hidden
#line 273 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.BaseException));
#line default
#line hidden
#line 273 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("(\"");
#line default
#line hidden
#line 273 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 273 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" can only contain alphanumeric characters and dashes and must be between 1 and 63" +
" characters long.\");\t\t\r\n");
#line default
#line hidden
#line 274 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
}
#line default
#line hidden
#line 277 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" \r\n request.HostPrefix = $\"");
#line default
#line hidden
#line 278 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.EndpointHostPrefix.Replace("{", "{hostPrefixLabels.")));
#line default
#line hidden
#line 278 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("\";\r\n");
#line default
#line hidden
#line 279 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
protected void GenerateRequestChecksumHandling(Operation operation, string requestContent)
{
// If the request has a Content-MD5 property and it's set by the user, copy the value to the header.
// Otherwise the checksum handling in Core will calculate and set MD5 later.
if (operation.HttpChecksumRequired)
{
var member = operation.RequestStructure.Members.FirstOrDefault(m => string.Equals(m.LocationName, "Content-MD5"));
if (member != default(Member))
{
#line default
#line hidden
#line 291 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" if (publicRequest.IsSet");
#line default
#line hidden
#line 292 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 292 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write("())\r\n request.Headers[Amazon.Util.HeaderKeys.ContentMD5Header]" +
" = publicRequest.");
#line default
#line hidden
#line 293 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 293 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(";\r\n");
#line default
#line hidden
#line 294 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
}
if (operation.RequiresChecksumDuringMarshalling)
{
if (!string.IsNullOrEmpty(operation.ChecksumConfiguration?.RequestAlgorithmMember))
{
#line default
#line hidden
#line 302 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" ChecksumUtils.SetRequestChecksum(request, request.");
#line default
#line hidden
#line 303 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.ChecksumConfiguration.RequestAlgorithmMember));
#line default
#line hidden
#line 303 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(", fallbackToMD5: ");
#line default
#line hidden
#line 303 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.HttpChecksumRequired.ToString().ToLower()));
#line default
#line hidden
#line 303 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 304 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
else if (operation.HttpChecksumRequired) // no flexible checksum, just MD5
{
#line default
#line hidden
#line 308 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
this.Write(" ChecksumUtils.SetRequestChecksumMD5(request);\r\n");
#line default
#line hidden
#line 310 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseMarshaller.tt"
}
}
}
#line default
#line hidden
}
#line default
#line hidden
}
| 1,888 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseRequestMarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class BaseRequestMarshaller : BaseMarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
this.Write("\r\n");
return this.GenerationEnvironment.ToString();
}
#line 7 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseRequestMarshaller.tt"
// The operation the marshaller will be used on
public Operation Operation { get; set; }
Shape _structure;
public Shape Structure
{
get
{
if(this.Operation != null)
{
if(this.Operation.IsResponseWrapped)
return this.Operation.ResponseStructure.Members[0].Shape;
else
return this.Operation.ResponseStructure;
}
return this._structure;
}
set { this._structure = value; }
}
protected void AddRequestSingletonMethod()
{
#line default
#line hidden
#line 30 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseRequestMarshaller.tt"
this.Write(" private static ");
#line default
#line hidden
#line 31 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
#line 31 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseRequestMarshaller.tt"
this.Write("RequestMarshaller _instance = new ");
#line default
#line hidden
#line 31 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
#line 31 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseRequestMarshaller.tt"
this.Write("RequestMarshaller(); \r\n\r\n\t\tinternal static ");
#line default
#line hidden
#line 33 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
#line 33 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseRequestMarshaller.tt"
this.Write("RequestMarshaller GetInstance()\r\n\t\t{\r\n\t\t\treturn _instance;\r\n\t\t}\r\n\r\n /// <s" +
"ummary>\r\n /// Gets the singleton.\r\n /// </summary> \r\n\t\tpublic sta" +
"tic ");
#line default
#line hidden
#line 41 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
#line 41 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseRequestMarshaller.tt"
this.Write("RequestMarshaller Instance\r\n\t\t{\r\n\t\t\tget\r\n\t\t\t{\r\n\t\t\t\treturn _instance;\r\n\t\t\t}\r\n\t\t}\r\n" +
"\r\n");
#line default
#line hidden
#line 49 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseRequestMarshaller.tt"
}
#line default
#line hidden
}
#line default
#line hidden
}
| 142 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 16.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "16.0.0.0")]
public partial class BaseResponseUnmarshaller : Generators.BaseGenerator
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
this.Write("\r\n");
return this.GenerationEnvironment.ToString();
}
#line 8 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
protected void GenerateAWSQueryCompatibleBlock()
{
#line default
#line hidden
#line 11 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(@" var errorCode = errorResponse.Code;
var errorType = errorResponse.Type;
var queryHeaderKey = Amazon.Util.HeaderKeys.XAmzQueryError;
if (context.ResponseData.IsHeaderPresent(queryHeaderKey))
{
var queryError = context.ResponseData.GetHeaderValue(queryHeaderKey);
if (!string.IsNullOrEmpty(queryError) && queryError.Contains("";""))
{
var queryErrorParts = queryError.Split(';');
if (queryErrorParts.Length == 2)
{
errorCode = queryErrorParts[0];
var errorTypeString = queryErrorParts[1];
if (Enum.IsDefined(typeof(ErrorType), errorTypeString))
{
errorType = (ErrorType) Enum.Parse(typeof(ErrorType), errorTypeString);
}
}
}
}
");
#line default
#line hidden
#line 32 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
#line default
#line hidden
#line 36 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
protected void AddCommonUsingStatements()
{
#line default
#line hidden
#line 39 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("using System;\r\nusing System.Collections.Generic;\r\nusing System.Globalization;\r\nus" +
"ing System.IO;\r\nusing System.Net;\r\nusing System.Text;\r\nusing System.Xml.Serializ" +
"ation;\r\n\r\nusing ");
#line default
#line hidden
#line 48 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
#line 48 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(".Model;\r\nusing Amazon.Runtime;\r\nusing Amazon.Runtime.Internal;\r\nusing Amazon.Runt" +
"ime.Internal.Transform;\r\nusing Amazon.Runtime.Internal.Util;\r\n");
#line default
#line hidden
#line 53 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
// Set to true when the service model specifies a shape that should be wrapped in a response. ElastiCache CreateCacheCluster is an example of this.
public bool IsWrapped { get; set; }
// set to the name of the member in the base Result class for operations where response data is moved from the result
// class into a structure member. If not set, the response members are assumed to be in the result base class itself.
public string WrappedResultMember { get; set; }
// The operation to unmarshall a response from
public Operation Operation { get; set; }
Shape _structure;
// Set if we are generating what is effectively a void response from an operation - no result class or other
// members were generated
public bool HasSuppressedResult { get; set; }
public string BaseException { get; set; }
// The shape of the response
public Shape Structure
{
get
{
if(this.Operation != null)
{
if(this.Operation.IsResponseWrapped)
return this.Operation.ResponseStructure.Members[0].Shape;
else
return this.Operation.ResponseStructure;
}
return this._structure;
}
set { this._structure = value; }
}
public string UnmarshallerBaseName
{
get
{
if(this.Operation != null)
return this.Operation.Name;
return this.Structure.Name;
}
}
protected void AddResponseSingletonMethod()
{
#line default
#line hidden
#line 104 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" private static ");
#line default
#line hidden
#line 105 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
#line 105 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("ResponseUnmarshaller _instance = new ");
#line default
#line hidden
#line 105 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
#line 105 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("ResponseUnmarshaller(); \r\n\r\n\t\tinternal static ");
#line default
#line hidden
#line 107 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
#line 107 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("ResponseUnmarshaller GetInstance()\r\n\t\t{\r\n\t\t\treturn _instance;\r\n\t\t}\r\n\r\n ///" +
" <summary>\r\n /// Gets the singleton.\r\n /// </summary> \r\n\t\tpublic " +
"static ");
#line default
#line hidden
#line 115 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
#line 115 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("ResponseUnmarshaller Instance\r\n\t\t{\r\n\t\t\tget\r\n\t\t\t{\r\n\t\t\t\treturn _instance;\r\n\t\t\t}\r\n\t\t" +
"}\r\n\r\n");
#line default
#line hidden
#line 123 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
protected void AddStructureSingletonMethod()
{
#line default
#line hidden
#line 128 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" private static ");
#line default
#line hidden
#line 129 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
#line 129 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("Unmarshaller _instance = new ");
#line default
#line hidden
#line 129 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
#line 129 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("Unmarshaller(); \r\n\r\n /// <summary>\r\n /// Gets the singleton." +
"\r\n /// </summary> \r\n\t\tpublic static ");
#line default
#line hidden
#line 134 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
#line 134 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("Unmarshaller Instance\r\n\t\t{\r\n\t\t\tget\r\n\t\t\t{\r\n\t\t\t\treturn _instance;\r\n\t\t\t}\r\n\t\t}\r\n");
#line default
#line hidden
#line 141 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
// Only applicable for rest-json and rest-xml
// Generates code to parse present header members into the response object
protected void UnmarshallHeaders()
{
if( this.Operation.ResponseHeaderMembers.Count() > 0 )
{
foreach (var member in this.Operation.ResponseHeaderMembers)
{
if (member.Shape.IsMap)
{
#line default
#line hidden
#line 154 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\t\t\t//Map of headers with prefix \"");
#line default
#line hidden
#line 155 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 155 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\".\r\n");
#line default
#line hidden
#line 156 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
// Dictionary<string, string>
if (member.ModelShape.ValueShape.IsString)
{
#line default
#line hidden
#line 160 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" var headersFor");
#line default
#line hidden
#line 161 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 161 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = new Dictionary<string, string>();\r\n\t\t\tforeach (var name");
#line default
#line hidden
#line 162 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 162 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" in context.ResponseData.GetHeaderNames())\r\n\t\t\t{\r\n\t\t\t\tvar keyToUse = name");
#line default
#line hidden
#line 164 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 164 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(";\r\n\t\t\t\tif(\"");
#line default
#line hidden
#line 165 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 165 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\".Length > 0 && keyToUse.StartsWith(\"");
#line default
#line hidden
#line 165 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 165 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\")) {\r\n\t\t\t\t\tkeyToUse = keyToUse.Substring(\"");
#line default
#line hidden
#line 166 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 166 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\".Length);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (context.ResponseData.IsHeaderPresent($\"");
#line default
#line hidden
#line 169 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 169 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("{name");
#line default
#line hidden
#line 169 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 169 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("}\"))\r\n\t\t\t\t{\r\n\t\t\t\t\theadersFor");
#line default
#line hidden
#line 171 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 171 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(".Add(\r\n\t\t\t\t\t\tkeyToUse,\r\n\t\t\t\t\t\tcontext.ResponseData.GetHeaderValue($\"");
#line default
#line hidden
#line 173 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 173 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("{name");
#line default
#line hidden
#line 173 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 173 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("}\")\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(headersFor");
#line default
#line hidden
#line 177 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 177 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(".Count > 0)\r\n\t\t\t\tresponse.");
#line default
#line hidden
#line 178 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 178 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = headersFor");
#line default
#line hidden
#line 178 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 178 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(";\r\n");
#line default
#line hidden
#line 179 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
// Dictionary<string, List<string>>
else if (member.ModelShape.ValueShape?.ListShape?.IsString == true)
{
#line default
#line hidden
#line 184 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\t\t\t var headersFor");
#line default
#line hidden
#line 185 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 185 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = new Dictionary<string, List<string>>();\r\n\t\t\tforeach (var name");
#line default
#line hidden
#line 186 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 186 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" in context.ResponseData.GetHeaderNames())\r\n\t\t\t{\r\n\t\t\t\tvar keyToUse = name");
#line default
#line hidden
#line 188 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 188 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(";\r\n\t\t\t\tif(\"");
#line default
#line hidden
#line 189 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 189 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\".Length > 0 && keyToUse.StartsWith(\"");
#line default
#line hidden
#line 189 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 189 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\")) {\r\n\t\t\t\t\tkeyToUse = keyToUse.Substring(\"");
#line default
#line hidden
#line 190 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 190 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\".Length);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (context.ResponseData.IsHeaderPresent($\"");
#line default
#line hidden
#line 193 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 193 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("{name");
#line default
#line hidden
#line 193 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 193 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("}\"))\r\n\t\t\t\t{\r\n\t\t\t\t\theadersFor");
#line default
#line hidden
#line 195 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 195 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(".Add(\r\n\t\t\t\t\t\tkeyToUse,\r\n\t\t\t\t\t\tcontext.ResponseData.GetHeaderValue($\"{nameResponse" +
"Headers}\").Split(\',\').ToList()\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(headersFor");
#line default
#line hidden
#line 201 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 201 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(".Count > 0)\r\n\t\t\t\tresponse.");
#line default
#line hidden
#line 202 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 202 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = headersFor");
#line default
#line hidden
#line 202 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 202 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(";\r\n");
#line default
#line hidden
#line 203 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
else
{
throw new InvalidDataException("[{member.ModelName}]: Invalid header map shapes. Header Maps must have a value of either a string or a list of strings: {member.ModelShape.ValueShape.Name}");
}
#line default
#line hidden
#line 210 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
continue;
}
#line default
#line hidden
#line 213 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\t\t\tif (context.ResponseData.IsHeaderPresent(\"");
#line default
#line hidden
#line 214 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 214 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\"))\r\n");
#line default
#line hidden
#line 215 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
if (member.Shape.IsString)
{
if (member.IsJsonValue)
{
#line default
#line hidden
#line 220 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\t\t\t{\r\n\t\t\t\tvar headerBytes = Convert.FromBase64String(context.ResponseData.GetHead" +
"erValue(\"");
#line default
#line hidden
#line 222 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 222 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\"));\r\n\t\t\t\tresponse.");
#line default
#line hidden
#line 223 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 223 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = Encoding.UTF8.GetString(headerBytes, 0, headerBytes.Length);\r\n\t\t\t}\r\n");
#line default
#line hidden
#line 225 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
else
{
#line default
#line hidden
#line 229 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\t\t\t\tresponse.");
#line default
#line hidden
#line 230 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 230 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = context.ResponseData.GetHeaderValue(\"");
#line default
#line hidden
#line 230 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 230 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\");\r\n");
#line default
#line hidden
#line 231 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
}
else if (member.Shape.IsMap)
{
#line default
#line hidden
#line 236 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\t\t\t//Map of headers with prefix \"");
#line default
#line hidden
#line 237 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 237 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\".\r\n\r\n");
#line default
#line hidden
#line 239 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
// Dictionary<string, string>
if (member.ModelShape.ValueShape.IsString)
{
#line default
#line hidden
#line 243 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" var headersFor");
#line default
#line hidden
#line 244 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 244 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = new Dictionary<string, string>();\r\n\t\t\tforeach (var name");
#line default
#line hidden
#line 245 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 245 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" in context.ResponseData.GetHeaderNames())\r\n\t\t\t{\r\n\t\t\t\tvar keyToUse = name");
#line default
#line hidden
#line 247 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 247 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(";\r\n\t\t\t\tif(\"");
#line default
#line hidden
#line 248 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 248 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\".Length > 0 && keyToUse.StartsWith(\"");
#line default
#line hidden
#line 248 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 248 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\")) {\r\n\t\t\t\t\tkeyToUse = keyToUse.Substring(\"");
#line default
#line hidden
#line 249 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 249 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\".Length);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (context.ResponseData.IsHeaderPresent($\"");
#line default
#line hidden
#line 252 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 252 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("{name");
#line default
#line hidden
#line 252 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 252 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("}\"))\r\n\t\t\t\t{\r\n\t\t\t\t\theadersFor");
#line default
#line hidden
#line 254 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 254 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(".Add(\r\n\t\t\t\t\t\tkeyToUse,\r\n\t\t\t\t\t\tcontext.ResponseData.GetHeaderValue($\"");
#line default
#line hidden
#line 256 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 256 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("{name");
#line default
#line hidden
#line 256 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 256 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("}\")\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(headersFor");
#line default
#line hidden
#line 260 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 260 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(".Count > 0)\r\n\t\t\t\tresponse.");
#line default
#line hidden
#line 261 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 261 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = headersFor");
#line default
#line hidden
#line 261 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 261 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(";\r\n");
#line default
#line hidden
#line 262 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
// Dictionary<string, List<string>>
else if (member.ModelShape.ValueShape?.ListShape?.IsString == true)
{
#line default
#line hidden
#line 267 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\t\t\t var headersFor");
#line default
#line hidden
#line 268 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 268 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = new Dictionary<string, List<string>>();\r\n\t\t\tforeach (var name");
#line default
#line hidden
#line 269 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 269 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" in context.ResponseData.GetHeaderNames())\r\n\t\t\t{\r\n\t\t\t\tvar keyToUse = name");
#line default
#line hidden
#line 271 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 271 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(";\r\n\t\t\t\tif(\"");
#line default
#line hidden
#line 272 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 272 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\".Length > 0 && keyToUse.StartsWith(\"");
#line default
#line hidden
#line 272 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 272 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\")) {\r\n\t\t\t\t\tkeyToUse = keyToUse.Substring(\"");
#line default
#line hidden
#line 273 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 273 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\".Length);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (context.ResponseData.IsHeaderPresent($\"");
#line default
#line hidden
#line 276 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 276 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("{name");
#line default
#line hidden
#line 276 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 276 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("}\"))\r\n\t\t\t\t{\r\n\t\t\t\t\theadersFor");
#line default
#line hidden
#line 278 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 278 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(".Add(\r\n\t\t\t\t\t\tkeyToUse,\r\n\t\t\t\t\t\tcontext.ResponseData.GetHeaderValue($\"{nameResponse" +
"Headers}\").Split(\',\').ToList()\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(headersFor");
#line default
#line hidden
#line 284 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 284 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(".Count > 0)\r\n\t\t\t\tresponse.");
#line default
#line hidden
#line 285 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 285 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = headersFor");
#line default
#line hidden
#line 285 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 285 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(";\r\n");
#line default
#line hidden
#line 286 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
else
{
throw new InvalidDataException("[{member.ModelName}]: Invalid header map shapes. Header Maps must have a value of either a string or a list of strings: {member.ModelShape.ValueShape.Name}");
}
#line default
#line hidden
#line 294 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
else if (member.Shape.IsInt)
{
#line default
#line hidden
#line 298 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\t\t\t\tresponse.");
#line default
#line hidden
#line 299 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 299 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = int.Parse(context.ResponseData.GetHeaderValue(\"");
#line default
#line hidden
#line 299 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 299 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\"), CultureInfo.InvariantCulture);\r\n");
#line default
#line hidden
#line 300 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
else if (member.Shape.IsLong)
{
#line default
#line hidden
#line 304 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\t\t\t\tresponse.");
#line default
#line hidden
#line 305 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 305 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = long.Parse(context.ResponseData.GetHeaderValue(\"");
#line default
#line hidden
#line 305 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 305 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\"), CultureInfo.InvariantCulture);\r\n");
#line default
#line hidden
#line 306 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
else if (member.Shape.IsDateTime)
{
if( member.TimestampFormat == TimestampFormat.ISO8601 ||
member.TimestampFormat == TimestampFormat.RFC822)
{
#line default
#line hidden
#line 313 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\t\t\t\tresponse.");
#line default
#line hidden
#line 314 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 314 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = DateTime.Parse(context.ResponseData.GetHeaderValue(\"");
#line default
#line hidden
#line 314 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 314 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\"), CultureInfo.InvariantCulture);\r\n");
#line default
#line hidden
#line 315 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
else if(member.TimestampFormat == TimestampFormat.UnixTimestamp)
{
#line default
#line hidden
#line 319 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\t\t\t\tresponse.");
#line default
#line hidden
#line 320 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 320 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = Amazon.Util.AWSSDKUtils.ConvertFromUnixEpochSeconds(int.Parse(context.Response" +
"Data.GetHeaderValue(\"");
#line default
#line hidden
#line 320 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallLocationName));
#line default
#line hidden
#line 320 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\"), CultureInfo.InvariantCulture));\r\n");
#line default
#line hidden
#line 321 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
else
{
throw new Exception(string.Format("Unable to determine the TimestampFormat for member {0}, type {1}.", member.Shape.Name, member.Shape.Type));
}
}
else
{
throw new Exception("Member " + member.Shape.Name + " cannot be handled because its type, " + member.Shape.Type + ", is not handled. Please update BaseResponseUnmarshaller.tt.");
}
}
}
}
// Generates code to set the status code of the response, example: 404, 200, etc
protected void ProcessStatusCode()
{
if( this.Operation.ResponseStatusCodeMember != null)
{
#line default
#line hidden
#line 341 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write("\t\t\tresponse.");
#line default
#line hidden
#line 342 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.ResponseStatusCodeMember.PropertyName));
#line default
#line hidden
#line 342 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
this.Write(" = (int)context.ResponseData.StatusCode;\r\n");
#line default
#line hidden
#line 343 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\BaseResponseUnmarshaller.tt"
}
}
#line default
#line hidden
}
#line default
#line hidden
}
| 1,559 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class EndpointDiscoveryMarshaller : BaseMarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
AddSource();
#line default
#line hidden
return this.GenerationEnvironment.ToString();
}
#line 12 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
// The operation to unmarshall a response from
public Operation Operation { get; set; }
protected void AddSingletonMethod()
{
#line default
#line hidden
#line 18 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(" private static ");
#line default
#line hidden
#line 19 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
#line 19 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write("EndpointDiscoveryMarshaller _instance = new ");
#line default
#line hidden
#line 19 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
#line 19 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write("EndpointDiscoveryMarshaller();\r\n\r\n /// <summary>\r\n /// Gets the sin" +
"gleton.\r\n /// </summary> \r\n\t\tpublic static ");
#line default
#line hidden
#line 24 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
#line 24 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write("EndpointDiscoveryMarshaller Instance\r\n\t\t{\r\n\t\t\tget\r\n\t\t\t{\r\n\t\t\t\treturn _instance;\r\n\t" +
"\t\t}\r\n\t\t}\r\n");
#line default
#line hidden
#line 31 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
}
protected void ProcessRequestEndpointDiscoveryIds(string variableName, IEnumerable<Member> members)
{
foreach(var member in members)
{
#line default
#line hidden
#line 38 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write("\t\t\tif(");
#line default
#line hidden
#line 39 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 39 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 39 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 39 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write("())\r\n\t\t\t\tendpointDiscoveryData.Identifiers.Add(\"");
#line default
#line hidden
#line 40 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 40 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write("\", ");
#line default
#line hidden
#line 40 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PrimitiveMarshaller));
#line default
#line hidden
#line 40 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 40 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 40 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 40 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 40 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 41 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
}
}
protected void AddSource()
{
#line default
#line hidden
#line 47 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write("namespace ");
#line default
#line hidden
#line 48 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
#line 48 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Endpoint d" +
"iscovery parameters for ");
#line default
#line hidden
#line 51 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
#line 51 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(" operation\r\n /// </summary> \r\n public class ");
#line default
#line hidden
#line 53 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
#line 53 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write("EndpointDiscoveryMarshaller : IMarshaller<EndpointDiscoveryDataBase, ");
#line default
#line hidden
#line 53 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
#line 53 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(@"Request> , IMarshaller<EndpointDiscoveryDataBase,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the endpoint discovery object.
/// </summary>
/// <param name=""input""></param>
/// <returns></returns>
public EndpointDiscoveryDataBase Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((");
#line default
#line hidden
#line 62 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
#line 62 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(@"Request)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name=""publicRequest""></param>
/// <returns></returns>
public EndpointDiscoveryDataBase Marshall(");
#line default
#line hidden
#line 70 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
#line 70 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write("Request publicRequest)\r\n\t\t{\r\n\t\t\tvar endpointDiscoveryData = new EndpointDiscovery" +
"Data(");
#line default
#line hidden
#line 72 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.IsEndpointDiscoveryRequired.ToString().ToLowerInvariant()));
#line default
#line hidden
#line 72 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(");\r\n\r\n");
#line default
#line hidden
#line 74 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
if(this.Operation.RequestHasEndpointDiscoveryIdMembers)
{
ProcessRequestEndpointDiscoveryIds("publicRequest", this.Operation.RequestEndpointDiscoveryIdMembers);
}
#line default
#line hidden
#line 79 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write("\t\t\treturn endpointDiscoveryData;\r\n\t\t}\r\n \r\n");
#line default
#line hidden
#line 83 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.AddSingletonMethod();
#line default
#line hidden
#line 85 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
this.Write(" \r\n }\r\n}\r\n");
#line default
#line hidden
#line 88 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\EndpointDiscoveryMarshaller.tt"
}
#line default
#line hidden
}
#line default
#line hidden
}
| 393 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 16.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "16.0.0.0")]
public partial class JsonRPCExceptionUnmarshaller : BaseResponseUnmarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("using ThirdParty.Json.LitJson;\r\n\r\nnamespace ");
#line 13 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Response U" +
"nmarshaller for ");
#line 16 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" Object\r\n /// </summary> \r\n public class ");
#line 18 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("Unmarshaller : IErrorResponseUnmarshaller<");
#line 18 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(", JsonUnmarshallerContext>\r\n {\r\n /// <summary>\r\n /// Unmarshalle" +
"r the response from the service to the response class.\r\n /// </summary> " +
"\r\n /// <param name=\"context\"></param>\r\n /// <returns></returns>\r\n " +
" public ");
#line 25 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@" Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name=""context""></param>
/// <param name=""errorResponse""></param>
/// <returns></returns>
public ");
#line 36 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorRespons" +
"e errorResponse)\r\n {\r\n context.Read();\r\n\r\n");
#line 40 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
if (this.Config.ServiceModel.IsAwsQueryCompatible)
{
GenerateAWSQueryCompatibleBlock();
#line default
#line hidden
this.Write(" ");
#line 45 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" unmarshalledObject = new ");
#line 45 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("(errorResponse.Message, errorResponse.InnerException,\r\n errorType," +
" errorCode, errorResponse.RequestId, errorResponse.StatusCode);\r\n");
#line 47 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(" ");
#line 52 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" unmarshalledObject = new ");
#line 52 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("(errorResponse.Message, errorResponse.InnerException,\r\n errorRespo" +
"nse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode)" +
";\r\n");
#line 54 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" \r\n int targetDepth = context.CurrentDepth;\r\n while " +
"(context.ReadAtDepth(targetDepth))\r\n {\r\n");
#line 61 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
if(this.Structure != null)
{
foreach (var member in this.Structure.Members)
{
#line default
#line hidden
this.Write(" if (context.TestExpression(\"");
#line 67 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
this.Write("\", targetDepth))\r\n {\r\n var unmarshaller = ");
#line 69 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n unmarshalledObject.");
#line 70 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n continue;\r\n " +
" }\r\n");
#line 73 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
}
}
#line default
#line hidden
this.Write(" }\r\n \r\n return unmarshalledObject;\r\n }\r\n\r\n");
#line 82 "C:\Users\ezhilani\source\repos\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCExceptionUnmarshaller.tt"
this.AddStructureSingletonMethod();
#line default
#line hidden
this.Write(" }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 223 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class JsonRPCRequestMarshaller : JsonRPCStructureMarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("using ThirdParty.Json.LitJson;\r\n\r\nnamespace ");
#line 13 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n\t/// <summary>\r\n\t/// ");
#line 16 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write(" Request Marshaller\r\n\t/// </summary> \r\n\tpublic class ");
#line 18 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("RequestMarshaller : IMarshaller<IRequest, ");
#line 18 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write(@"Request> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name=""input""></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((");
#line 27 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("Request)input);\r\n }\r\n\r\n /// <summary>\r\n /// Marshaller the r" +
"equest object to the HTTP request.\r\n /// </summary> \r\n /// <param" +
" name=\"publicRequest\"></param>\r\n /// <returns></returns>\r\n\t\tpublic IReque" +
"st Marshall(");
#line 35 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("Request publicRequest)\r\n\t\t{\r\n\t\t\tIRequest request = new DefaultRequest(publicReque" +
"st, \"");
#line 37 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write("\");\r\n");
#line 38 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
if (!string.IsNullOrEmpty(this.Config.ServiceModel.TargetPrefix))
{
#line default
#line hidden
this.Write("\t\t\tstring target = \"");
#line 41 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ServiceModel.TargetPrefix));
#line default
#line hidden
this.Write(".");
#line 41 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("\";\r\n\t\t\trequest.Headers[\"X-Amz-Target\"] = target;\r\n");
#line 43 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
if (this.Operation.HttpMethod != "GET" && this.Operation.HttpMethod != "DELETE")
{
if (this.Config.ServiceModel.Customizations.OverrideContentType != null)
{
#line default
#line hidden
this.Write("\t\t\trequest.Headers[\"Content-Type\"] = \"");
#line 51 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ServiceModel.Customizations.OverrideContentType));
#line default
#line hidden
this.Write("\";\r\n");
#line 52 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
else if (this.Config.ServiceModel.Type != ServiceType.Rest_Json)
{
#line default
#line hidden
this.Write("\t\t\trequest.Headers[\"Content-Type\"] = \"application/x-amz-json-");
#line 57 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ServiceModel.JsonVersion));
#line default
#line hidden
this.Write("\";\r\n");
#line 58 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
else
{
#line default
#line hidden
this.Write("\t\t\trequest.Headers[\"Content-Type\"] = \"application/json\";\r\n");
#line 64 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
}
#line default
#line hidden
this.Write(" request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = \"");
#line 68 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ServiceModel.APIVersion));
#line default
#line hidden
this.Write("\";\r\n request.HttpMethod = \"");
#line 69 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.HttpMethod));
#line default
#line hidden
this.Write("\";\r\n\r\n");
#line 71 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
var requestStructure = this.Operation.RequestStructure;
// Generates code to add members of the request to the request being created by the marshaller
ProcessRequestUri(this.Operation);
if (this.Config.ServiceModel.Type == ServiceType.Rest_Json)
{
ProcessUriMembers("publicRequest", this.Operation);
ProcessQueryStringMembers("publicRequest", this.Operation);
}
#line default
#line hidden
this.Write("\t\t\trequest.ResourcePath = \"");
#line 83 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.RequestUri));
#line default
#line hidden
this.Write("\";\r\n");
#line 84 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
var payload = this.Operation.RequestPayloadMember;
var shouldMarshallPayload = (payload != null && !payload.IsMemoryStream && !payload.Shape.IsString);
// Process any members which are marshalled as part of the request body
if (this.Operation.RequestHasBodyMembers || shouldMarshallPayload)
{
#line default
#line hidden
this.Write("\t\t\tusing (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCultu" +
"re))\r\n\t\t\t{\r\n\t\t\t\tJsonWriter writer = new JsonWriter(stringWriter);\r\n");
#line 95 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
if (shouldMarshallPayload)
{
#line default
#line hidden
this.Write("\t\t\t\tvar context = new JsonMarshallerContext(request, writer);\r\n");
#line 100 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
ProcessStructure(0, "publicRequest." + payload.PropertyName, payload.Shape);
}
else
{
#line default
#line hidden
this.Write("\t\t\t\twriter.WriteObjectStart();\r\n\t\t\t\tvar context = new JsonMarshallerContext(reque" +
"st, writer);\r\n");
#line 108 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
ProcessMembers(1, "publicRequest", this.Operation.RequestBodyMembers);
#line default
#line hidden
this.Write("\t\t\t\twriter.WriteObjectEnd();\r\n");
#line 112 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
#line default
#line hidden
this.Write("\t\t\t\tstring snippet = stringWriter.ToString();\r\n\t\t\t\trequest.Content = System.Text." +
"Encoding.UTF8.GetBytes(snippet);\r\n");
#line 117 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
GenerateRequestChecksumHandling(this.Operation, "snippet");
#line default
#line hidden
this.Write("\t\t\t}\r\n\r\n");
#line 122 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
else if (payload?.Shape.IsString == true)
{
#line default
#line hidden
this.Write("\t\t\trequest.Content = System.Text.Encoding.UTF8.GetBytes(publicRequest.");
#line 127 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(");\r\n");
#line 128 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
else if (payload?.IsMemoryStream == true)
{
#line default
#line hidden
this.Write("\t\t\trequest.ContentStream = publicRequest.");
#line 133 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" ?? new MemoryStream();\r\n");
#line 134 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
var requiresLength = payload.RequiresLength;
if (!requiresLength && payload.IsStreaming && this.Operation.AuthType == OperationAuthType.V4UnsignedBody)
{
#line default
#line hidden
this.Write(@" if (request.ContentStream.CanSeek)
{
request.Headers[Amazon.Util.HeaderKeys.ContentLengthHeader] =
request.ContentStream.Length.ToString(CultureInfo.InvariantCulture);
}
else
{
request.Headers[Amazon.Util.HeaderKeys.TransferEncodingHeader] = ""chunked"";
}
");
#line 148 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
else
{
if (payload.IsStreaming && requiresLength)
{
#line default
#line hidden
this.Write("\t\t\tif (!request.ContentStream.CanSeek)\r\n\t\t\t{\r\n\t\t\t\tthrow new System.InvalidOperati" +
"onException(\"Cannot determine stream length for the payload when content-length " +
"is required.\");\r\n\t\t\t}\r\n");
#line 159 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
#line default
#line hidden
this.Write("\t\t\trequest.Headers[Amazon.Util.HeaderKeys.ContentLengthHeader] =\r\n\t\t\t\trequest.Con" +
"tentStream.Length.ToString(CultureInfo.InvariantCulture);\r\n");
#line 164 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
#line default
#line hidden
this.Write("\t\t\trequest.Headers[Amazon.Util.HeaderKeys.ContentTypeHeader] = \"binary/octet-stre" +
"am\"; \r\n\t\t\tif (request.ContentStream != null && request.ContentStream.Length == 0" +
")\r\n\t\t\t{\r\n\t\t\t\trequest.Headers.Remove(Amazon.Util.HeaderKeys.ContentTypeHeader);\r\n" +
"\t\t\t}\r\n");
#line 172 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
else if (payload?.Shape.IsPrimitiveType == true)
{
// At this point, all valid configurations have been handled. Valid use of payload is defined:
// https://awslabs.github.io/smithy/1.0/spec/core/http-traits.html#httppayload-trait
throw new Exception(
$"{payload.PropertyName} can not be a Payload as Type {payload.Shape.Type} is not a valid target for the httpPayload trait. " +
"The httpPayload trait can be applied to structure members that target a string, blob, structure, union, document, set, map, or list.");
}
else if (this.Config.ServiceModel.Type == ServiceType.Json)
{
#line default
#line hidden
this.Write("\t\t\tvar content = \"{}\";\r\n request.Content = System.Text.Encoding.UTF8.G" +
"etBytes(content);\r\n");
#line 187 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
GenerateRequestChecksumHandling(this.Operation, "content");
#line default
#line hidden
#line 190 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
if (this.Config.ServiceModel.Type == ServiceType.Rest_Json)
{
ProcessHeaderMembers("publicRequest", this.Operation.RequestHeaderMembers);
}
// If there aren't any members that are marshalled as part of the body or streamed
if (this.Operation.UseQueryString)
{
#line default
#line hidden
this.Write("\t\t\trequest.UseQueryString = true;\r\n");
#line 203 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
}
// We skip endpoint host prefix handling for S3 and S3 Control as it's implemented by endpoint rules.
if (!string.IsNullOrEmpty(this.Operation.EndpointHostPrefix) && this.Config.ServiceId != "S3" && this.Config.ServiceId != "S3 Control")
{
ProcessEndpointHostPrefixMembers("publicRequest", this.Operation);
}
#line default
#line hidden
this.Write("\r\n\t\t\treturn request;\r\n\t\t}\r\n");
#line 214 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCRequestMarshaller.tt"
this.AddRequestSingletonMethod();
#line default
#line hidden
this.Write("\t}\r\n}\r\n");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 461 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 16.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "16.0.0.0")]
public partial class JsonRPCResponseUnmarshaller : BaseResponseUnmarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("using ThirdParty.Json.LitJson;\r\n\r\nnamespace ");
#line 13 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Response U" +
"nmarshaller for ");
#line 16 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" operation\r\n /// </summary> \r\n public class ");
#line 18 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@"ResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name=""context""></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
");
#line 27 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("Response response = new ");
#line 27 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("Response();\r\n\r\n");
#line 29 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
var payload = this.Operation.ResponsePayloadMember;
var unmarshallPayload = payload != null && payload.IsStructure;
var payloadIsStream = payload != null && !unmarshallPayload;
bool isEventStreamOutput = this.Operation.IsEventStreamOutput;
if (this.Operation.ResponseHasBodyMembers || payload != null)
{
if (this.Operation.AllowEmptyResult)
{
throw new NotImplementedException("AllowEmptyResult is not implemented for JSON unmarshallers");
}
if (isEventStreamOutput)
{
#line default
#line hidden
this.Write(" response.");
#line 43 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" = new ");
#line 43 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.Shape.Name));
#line default
#line hidden
this.Write("(context.Stream);\r\n");
#line 44 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
else if (payloadIsStream)
{
if (payload.IsStreaming)
{
#line default
#line hidden
this.Write(" response.");
#line 51 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" = context.Stream;\r\n");
#line 52 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
else if (payload.ModelShape.IsString)
{
#line default
#line hidden
this.Write(" using (var sr = new StreamReader(context.Stream))\r\n {\r\n " +
" response.");
#line 59 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" = sr.ReadToEnd();\r\n }\r\n");
#line 61 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
else if (payload.ModelShape.IsMemoryStream)
{
#line default
#line hidden
this.Write(" var ms = new MemoryStream();\r\n Amazon.Util.AWSSDKUtils.Cop" +
"yStream(context.Stream, ms);\r\n ms.Seek(0, SeekOrigin.Begin);\r\n " +
" response.");
#line 69 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" = ms;\r\n");
#line 70 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
else
{
// At this point, all valid configurations have been handled. Valid use of payload is defined:
// https://awslabs.github.io/smithy/1.0/spec/core/http-traits.html#httppayload-trait
throw new Exception(
$"{payload.PropertyName} can not be a Payload as Type {payload.Shape.Type} is not a valid target for the httpPayload trait. " +
"The httpPayload trait can be applied to structure members that target a string, blob, structure, union, document, set, map, or list.");
}
}
else if (unmarshallPayload)
{
#line default
#line hidden
this.Write(" var unmarshaller = ");
#line 84 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n response.");
#line 85 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n");
#line 86 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
else if (this.IsWrapped)
{
#line default
#line hidden
this.Write("\t\t\tresponse.");
#line 91 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.WrappedResultMember));
#line default
#line hidden
this.Write(" = ");
#line 91 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Structure.Name));
#line default
#line hidden
this.Write("Unmarshaller.Instance.Unmarshall(context);\r\n");
#line 92 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(" context.Read();\r\n int targetDepth = context.CurrentDepth;\r" +
"\n while (context.ReadAtDepth(targetDepth))\r\n {\r\n");
#line 101 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
foreach (var member in this.Operation.ResponseBodyMembers)
{
#line default
#line hidden
this.Write(" if (context.TestExpression(\"");
#line 106 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
this.Write("\", targetDepth))\r\n {\r\n var unmarshaller = ");
#line 108 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n response.");
#line 109 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n continue;\r\n " +
" }\r\n");
#line 112 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" }\r\n");
#line 116 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
}
UnmarshallHeaders();
ProcessStatusCode();
#line default
#line hidden
this.Write(@"
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name=""context""></param>
/// <param name=""innerException""></param>
/// <param name=""statusCode""></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
");
#line 142 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
if (this.Config.ServiceModel.IsAwsQueryCompatible)
{
#line default
#line hidden
#line 146 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
// Create a copy of context with headers in the response
#line default
#line hidden
this.Write("\r\n using (var contextCopy = new JsonUnmarshallerContext(streamCopy, tr" +
"ue, context.ResponseData))\r\n");
#line 149 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(" using (var contextCopy = new JsonUnmarshallerContext(streamCopy, fals" +
"e, null))\r\n");
#line 155 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" {\r\n");
#line 159 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
foreach (var exception in this.Operation.Exceptions)
{
#line default
#line hidden
this.Write(" if (errorResponse.Code != null && errorResponse.Code.Equals(\"");
#line 163 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Code));
#line default
#line hidden
this.Write("\"))\r\n {\r\n return ");
#line 165 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Name));
#line default
#line hidden
this.Write("Unmarshaller.Instance.Unmarshall(contextCopy, errorResponse);\r\n }\r" +
"\n");
#line 167 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" }\r\n");
#line 171 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
if (this.Config.ServiceModel.IsAwsQueryCompatible)
{
GenerateAWSQueryCompatibleBlock();
#line default
#line hidden
this.Write(" return new ");
#line 176 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.BaseException));
#line default
#line hidden
this.Write("(errorResponse.Message, errorResponse.InnerException, errorType, errorCode, error" +
"Response.RequestId, errorResponse.StatusCode);\r\n");
#line 177 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(" return new ");
#line 182 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.BaseException));
#line default
#line hidden
this.Write("(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorRe" +
"sponse.Code, errorResponse.RequestId, errorResponse.StatusCode);\r\n");
#line 183 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" }\r\n\r\n");
#line 188 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
if (payload != null && payload.IsStreaming)
{
#line default
#line hidden
this.Write(@" /// <summary>
/// Overriden to return true indicating the response contains streaming data.
/// </summary>
public override bool HasStreamingProperty
{
get
{
return true;
}
}
");
#line 203 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
this.AddResponseSingletonMethod();
#line default
#line hidden
#line 207 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
if(isEventStreamOutput)
{
#line default
#line hidden
this.Write(@" protected override bool ShouldReadEntireResponse(IWebResponseData response, bool readEntireResponse)
{
return false;
}
/// <summary>
/// Specifies that the response should be streamed
/// </summary>
public override bool HasStreamingProperty => true;
");
#line 219 "C:\Dev\Repos\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 508 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class JsonRPCStructureMarshaller : BaseRequestMarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("using ThirdParty.Json.LitJson;\r\n\r\nnamespace ");
#line 13 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n\t/// <summary>\r\n\t/// ");
#line 16 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Structure.Name));
#line default
#line hidden
this.Write(" Marshaller\r\n\t/// </summary>\r\n\tpublic class ");
#line 18 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Structure.Name));
#line default
#line hidden
this.Write("Marshaller : IRequestMarshaller<");
#line 18 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Structure.Name));
#line default
#line hidden
this.Write(@", JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name=""requestObject""></param>
/// <param name=""context""></param>
/// <returns></returns>
public void Marshall(");
#line 26 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Structure.Name));
#line default
#line hidden
this.Write(" requestObject, JsonMarshallerContext context)\r\n\t\t{\r\n");
#line 28 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
ProcessMembers(0, "requestObject", this.Structure.Members);
#line default
#line hidden
this.Write("\t\t}\r\n\r\n /// <summary>\r\n /// Singleton Marshaller.\r\n /// </su" +
"mmary>\r\n\t\tpublic readonly static ");
#line 36 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Structure.Name));
#line default
#line hidden
this.Write("Marshaller Instance = new ");
#line 36 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Structure.Name));
#line default
#line hidden
this.Write("Marshaller();\r\n\r\n\t}\r\n}\r\n\r\n");
return this.GenerationEnvironment.ToString();
}
#line 41 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
protected void ProcessMembers(int level, string variableName, IEnumerable<Member> members)
{
foreach(var member in members)
{
#line default
#line hidden
#line 47 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 47 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" if(");
#line default
#line hidden
#line 47 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 47 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 47 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 47 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("())\r\n");
#line default
#line hidden
#line 48 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 48 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" {\r\n");
#line default
#line hidden
#line 49 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 49 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.WritePropertyName(\"");
#line default
#line hidden
#line 49 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
#line 49 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("\");\r\n");
#line default
#line hidden
#line 50 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
string memberProperty = variableName + "." + member.PropertyName + (member.UseNullable ? ".Value" : string.Empty);
if(member.IsStructure || member.IsList || member.IsMap)
{
this.ProcessStructure(level, variableName + "." + member.PropertyName, member.Shape);
}
else if(!string.IsNullOrEmpty(member.CustomMarshallerTransformation))
{
#line default
#line hidden
#line 59 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 59 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.Write(");
#line default
#line hidden
#line 59 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.CustomMarshallerTransformation));
#line default
#line hidden
#line 59 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 59 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(memberProperty));
#line default
#line hidden
#line 59 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 60 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
else if(member.IsMemoryStream)
{
#line default
#line hidden
#line 65 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 65 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.Write(StringUtils.FromMemoryStream(");
#line default
#line hidden
#line 65 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName + "." + member.PropertyName));
#line default
#line hidden
#line 65 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 66 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
else
{
// Only use timestamp format based marshalling if format is not Unix epoch, which is the default for json/rest-json
if(member.IsDateTime && member.TimestampFormat != TimestampFormat.UnixTimestamp)
{
#line default
#line hidden
#line 74 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 74 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.Write(");
#line default
#line hidden
#line 74 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PrimitiveMarshaller));
#line default
#line hidden
#line 74 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 74 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName + "." + member.PropertyName));
#line default
#line hidden
#line 74 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 75 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
else
{
#line default
#line hidden
#line 80 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 80 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.Write(");
#line default
#line hidden
#line 80 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(memberProperty));
#line default
#line hidden
#line 80 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 81 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
}
#line default
#line hidden
#line 85 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 85 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" }\r\n\r\n");
#line default
#line hidden
#line 87 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
if(member.IsIdempotent)
{
#line default
#line hidden
#line 91 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 91 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" \t\t else if(!(");
#line default
#line hidden
#line 91 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 91 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 91 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 91 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("()))\r\n");
#line default
#line hidden
#line 92 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 92 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" \t\t {\r\n");
#line default
#line hidden
#line 93 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 93 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.WritePropertyName(\"");
#line default
#line hidden
#line 93 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
#line 93 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("\");\r\n");
#line default
#line hidden
#line 94 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 94 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.Write(Guid.NewGuid().ToString());\r\n");
#line default
#line hidden
#line 95 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 95 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" \t\t }\r\n");
#line default
#line hidden
#line 96 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
}
}
protected void ProcessRequestPayloadMember(int level, string variableName, Shape structure)
{
#line default
#line hidden
#line 103 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("\r\n");
#line default
#line hidden
#line 105 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 105 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" var marshaller = ");
#line default
#line hidden
#line 105 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(structure.Name));
#line default
#line hidden
#line 105 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("Marshaller.Instance;\r\n");
#line default
#line hidden
#line 106 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 106 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" marshaller.Marshall(");
#line default
#line hidden
#line 106 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 106 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(", context);\r\n");
#line default
#line hidden
#line 107 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
protected void ProcessStructure(int level, string variableName, Shape structure)
{
string flatVariableName = variableName.Replace(".", "");
if(structure.IsList)
{
#line default
#line hidden
#line 117 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 117 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.WriteArrayStart();\r\n");
#line default
#line hidden
#line 118 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 118 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" foreach(var ");
#line default
#line hidden
#line 118 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(flatVariableName));
#line default
#line hidden
#line 118 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("ListValue in ");
#line default
#line hidden
#line 118 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 118 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(")\r\n");
#line default
#line hidden
#line 119 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 119 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" {\r\n");
#line default
#line hidden
#line 120 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
ProcessStructure(level + 1, flatVariableName + "ListValue", structure.ListShape);
#line default
#line hidden
#line 123 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 123 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" }\r\n");
#line default
#line hidden
#line 124 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 124 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.WriteArrayEnd();\r\n");
#line default
#line hidden
#line 125 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
else if(structure.IsMap)
{
#line default
#line hidden
#line 130 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 130 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.WriteObjectStart();\r\n");
#line default
#line hidden
#line 131 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 131 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" foreach (var ");
#line default
#line hidden
#line 131 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(flatVariableName));
#line default
#line hidden
#line 131 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("Kvp in ");
#line default
#line hidden
#line 131 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 131 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(")\r\n");
#line default
#line hidden
#line 132 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 132 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" {\r\n");
#line default
#line hidden
#line 133 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 133 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.WritePropertyName(");
#line default
#line hidden
#line 133 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(flatVariableName));
#line default
#line hidden
#line 133 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("Kvp.Key);\r\n");
#line default
#line hidden
#line 134 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 134 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" var ");
#line default
#line hidden
#line 134 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(flatVariableName));
#line default
#line hidden
#line 134 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("Value = ");
#line default
#line hidden
#line 134 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(flatVariableName));
#line default
#line hidden
#line 134 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("Kvp.Value;\r\n\r\n");
#line default
#line hidden
#line 136 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
ProcessStructure(level + 1, flatVariableName + "Value", structure.ValueShape);
#line default
#line hidden
#line 139 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 139 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" }\r\n");
#line default
#line hidden
#line 140 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 140 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.WriteObjectEnd();\r\n");
#line default
#line hidden
#line 141 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
else if(structure.IsDocument)
{
#line default
#line hidden
#line 146 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 146 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" Amazon.Runtime.Documents.Internal.Transform.DocumentMarshaller.In" +
"stance.Write(context.Writer, ");
#line default
#line hidden
#line 146 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 146 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 147 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
else if(structure.IsStructure)
{
#line default
#line hidden
#line 153 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 153 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.WriteObjectStart();\r\n\r\n");
#line default
#line hidden
#line 155 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 155 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" var marshaller = ");
#line default
#line hidden
#line 155 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(structure.Name));
#line default
#line hidden
#line 155 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("Marshaller.Instance;\r\n");
#line default
#line hidden
#line 156 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 156 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" marshaller.Marshall(");
#line default
#line hidden
#line 156 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 156 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(", context);\r\n\r\n");
#line default
#line hidden
#line 158 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 158 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.WriteObjectEnd();\r\n");
#line default
#line hidden
#line 159 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
else if(structure.IsMemoryStream)
{
#line default
#line hidden
#line 164 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 164 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.Write(StringUtils.FromMemoryStream(");
#line default
#line hidden
#line 164 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 164 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 165 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
else
{
// Only use timestamp format based marshalling if format is not Unix epoch, which is the default for json/rest-json
if(structure.IsDateTime && structure.GetTimestampFormat(MarshallLocation.Body) != TimestampFormat.UnixTimestamp)
{
#line default
#line hidden
#line 173 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 173 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("\t\t\t\t context.Writer.Write(");
#line default
#line hidden
#line 173 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(structure.PrimitiveMarshaller(MarshallLocation.Body)));
#line default
#line hidden
#line 173 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 173 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 173 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write("));\r\n");
#line default
#line hidden
#line 174 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
else
{
#line default
#line hidden
#line 180 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(new string(' ', level * 4)));
#line default
#line hidden
#line 180 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(" context.Writer.Write(");
#line default
#line hidden
#line 180 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 180 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
this.Write(");\r\n");
#line default
#line hidden
#line 181 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureMarshaller.tt"
}
}
}
#line default
#line hidden
}
#line default
#line hidden
}
| 1,202 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class JsonRPCStructureUnmarshaller : BaseResponseUnmarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("using ThirdParty.Json.LitJson;\r\n\r\nnamespace ");
#line 13 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Response U" +
"nmarshaller for ");
#line 16 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" Object\r\n /// </summary> \r\n public class ");
#line 18 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("Unmarshaller : IUnmarshaller<");
#line 18 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(", XmlUnmarshallerContext>, IUnmarshaller<");
#line 18 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(", JsonUnmarshallerContext>\r\n {\r\n /// <summary>\r\n /// Unmarshalle" +
"r the response from the service to the response class.\r\n /// </summary> " +
"\r\n /// <param name=\"context\"></param>\r\n /// <returns></returns>\r\n " +
" ");
#line 25 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" IUnmarshaller<");
#line 25 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@", XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name=""context""></param>
/// <returns></returns>
public ");
#line 35 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" Unmarshall(JsonUnmarshallerContext context)\r\n {\r\n context.Read" +
"();\r\n if (context.CurrentTokenType == JsonToken.Null) \r\n " +
" return null;\r\n\r\n ");
#line 41 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" unmarshalledObject = new ");
#line 41 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("();\r\n \r\n int targetDepth = context.CurrentDepth;\r\n w" +
"hile (context.ReadAtDepth(targetDepth))\r\n {\r\n");
#line 46 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
if(this.Structure != null)
{
foreach (var member in this.Structure.Members)
{
#line default
#line hidden
this.Write(" if (context.TestExpression(\"");
#line 52 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
this.Write("\", targetDepth))\r\n {\r\n var unmarshaller = ");
#line 54 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n unmarshalledObject.");
#line 55 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n continue;\r\n " +
" }\r\n");
#line 58 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
}
}
#line default
#line hidden
this.Write(" }\r\n \r\n return unmarshalledObject;\r\n }\r\n\r\n\r" +
"\n");
#line 68 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCStructureUnmarshaller.tt"
this.AddStructureSingletonMethod();
#line default
#line hidden
this.Write(" }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 190 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class RestXmlExceptionUnmarshaller : BaseResponseUnmarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("\r\nnamespace ");
#line 12 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Response U" +
"nmarshaller for ");
#line 15 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" operation\r\n /// </summary> \r\n public class ");
#line 17 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("Unmarshaller : IErrorResponseUnmarshaller<");
#line 17 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(", XmlUnmarshallerContext>\r\n {\r\n /// <summary>\r\n /// Unmarshaller" +
" the response from the service to the response class.\r\n /// </summary> \r" +
"\n /// <param name=\"context\"></param>\r\n /// <returns></returns>\r\n " +
" public ");
#line 24 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@" Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name=""context""></param>
/// <param name=""errorResponse""></param>
/// <returns></returns>
public ");
#line 35 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" Unmarshall(XmlUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse" +
" errorResponse)\r\n {\r\n ");
#line 37 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" response = new ");
#line 37 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@"(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
while (context.Read())
{
if (context.IsStartElement || context.IsAttribute)
{
");
#line 44 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
foreach (var member in this.Structure.Members)
{
if(member.Shape.IsList)
{
var listMarshallName = member.Shape.ListMarshallName ?? "member";
#line default
#line hidden
this.Write(" if (context.TestExpression(\"");
#line 51 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
this.Write("/");
#line 51 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listMarshallName));
#line default
#line hidden
this.Write("\"))\r\n {\r\n var unmarshaller = ");
#line 53 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n response.");
#line 54 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(".Add(unmarshaller.Unmarshall(context));\r\n }\r\n");
#line 56 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(" if (context.TestExpression(\"");
#line 61 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
this.Write("\"))\r\n {\r\n var unmarshaller = ");
#line 63 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n response.");
#line 64 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n }\r\n");
#line 66 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
}
}
#line default
#line hidden
this.Write(" }\r\n }\r\n return response;\r\n }\r\n\r\n");
#line 75 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlExceptionUnmarshaller.tt"
this.AddStructureSingletonMethod();
#line default
#line hidden
this.Write(" }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 220 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class RestXmlRequestMarshaller : BaseRequestMarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("using System.Xml;\r\n\r\nnamespace ");
#line 13 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n\t/// <summary>\r\n\t/// ");
#line 16 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write(" Request Marshaller\r\n\t/// </summary> \r\n\tpublic class ");
#line 18 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("RequestMarshaller : IMarshaller<IRequest, ");
#line 18 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write(@"Request> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name=""input""></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((");
#line 27 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("Request)input);\r\n }\r\n\r\n /// <summary>\r\n /// Marshaller the r" +
"equest object to the HTTP request.\r\n /// </summary> \r\n /// <param" +
" name=\"publicRequest\"></param>\r\n /// <returns></returns>\r\n\t\tpublic IReque" +
"st Marshall(");
#line 35 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("Request publicRequest)\r\n\t\t{\r\n\t\t\tvar request = new DefaultRequest(publicRequest, \"" +
"");
#line 37 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write("\");\r\n");
#line 38 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
// Assign HttpMethod if present or default to POST
if(!string.IsNullOrWhiteSpace(this.Operation.HttpMethod)){
#line default
#line hidden
this.Write("\t\t\trequest.HttpMethod = \"");
#line 42 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.HttpMethod));
#line default
#line hidden
this.Write("\";\r\n");
#line 43 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
}
var requestStructure = this.Operation.RequestStructure;
var payload = this.Operation.RequestPayloadMember;
var shouldMarshallPayload = (payload != null && payload.IsStructure);
// This block adds members of the request object to the actual request
ProcessRequestUri(this.Operation);
ProcessHeaderMembers("publicRequest", this.Operation.RequestHeaderMembers);
ProcessUriMembers("publicRequest", this.Operation);
ProcessQueryStringMembers("publicRequest", this.Operation);
#line default
#line hidden
this.Write("\t\t\trequest.ResourcePath = \"");
#line 55 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.RequestUri));
#line default
#line hidden
this.Write("\";\r\n\r\n");
#line 57 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
// Process any members which are marshalled as part of the request body
if(this.Operation.RequestHasBodyMembers || shouldMarshallPayload)
{
ProcessRequestBodyMembers("publicRequest", this.Operation);
}
#line default
#line hidden
this.Write("\r\n");
#line 65 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
// If there aren't any members that are marshalled as part of the body or streamed
if(this.Operation.UseQueryString)
{
#line default
#line hidden
this.Write("\t\t\trequest.UseQueryString = true;\r\n");
#line 71 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
}
// We skip endpoint host prefix handling for S3 and S3 Control as it's implemented by endpoint rules.
if(!string.IsNullOrEmpty(this.Operation.EndpointHostPrefix) && this.Config.ServiceId != "S3" && this.Config.ServiceId != "S3 Control")
{
ProcessEndpointHostPrefixMembers("publicRequest", this.Operation);
}
#line default
#line hidden
this.Write("\t\t\treturn request;\r\n\t\t}\r\n");
#line 81 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.AddRequestSingletonMethod();
#line default
#line hidden
this.Write("\t}\t\r\n}\r\n\r\n");
return this.GenerationEnvironment.ToString();
}
#line 87 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
void ProcessRequestBodyMembers(string variableName, Operation operation)
{
#line default
#line hidden
#line 91 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(@" var stringWriter = new XMLEncodedStringWriter(CultureInfo.InvariantCulture);
using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings() { Encoding = System.Text.Encoding.UTF8, OmitXmlDeclaration = true, NewLineHandling = NewLineHandling.Entitize }))
{
");
#line default
#line hidden
#line 95 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
if(operation.RequestPayloadMember==null)
{
#line default
#line hidden
#line 98 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\txmlWriter.WriteStartElement(\"");
#line default
#line hidden
#line 99 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.Input.LocationName));
#line default
#line hidden
#line 99 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", \"");
#line default
#line hidden
#line 99 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.XmlNamespace));
#line default
#line hidden
#line 99 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\");\t\r\n");
#line default
#line hidden
#line 100 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
}
else
{
#line default
#line hidden
#line 104 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\tif (");
#line default
#line hidden
#line 105 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName + ".IsSet" + operation.RequestPayloadMember.PropertyName));
#line default
#line hidden
#line 105 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("())\r\n\t\t\t\t{\r\n\t\t\t\t\txmlWriter.WriteStartElement(\"");
#line default
#line hidden
#line 107 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.RequestPayloadMember.MarshallName));
#line default
#line hidden
#line 107 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", \"");
#line default
#line hidden
#line 107 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.XmlNamespace));
#line default
#line hidden
#line 107 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\");\r\n");
#line default
#line hidden
#line 108 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
PushIndent(" ");
}
var childmembers = operation.RequestPayloadMember == null ? operation.RequestBodyMembers : operation.RequestPayloadMember.Shape.Members;
variableName = operation.RequestPayloadMember == null ? variableName : variableName + "." + operation.RequestPayloadMember.PropertyName;
foreach(var member in childmembers)
{
if(member.IsStructure)
{
ProcessStructure(variableName, member, operation.XmlNamespace);
}
else if(member.IsList)
{
ProcessList(variableName, member, operation.XmlNamespace);
}
else if(member.IsMap)
{
ProcessMap(variableName, member, operation.XmlNamespace);
}
else
{
#line default
#line hidden
#line 129 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\tif(");
#line default
#line hidden
#line 130 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 130 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 130 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 130 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("())\r\n\t\t\t\t\txmlWriter.WriteElementString(\"");
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", \"");
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.XmlNamespace));
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", ");
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PrimitiveMarshaller));
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture((member.UseNullable ? ".Value" : string.Empty)));
#line default
#line hidden
#line 131 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("));\t\t\t\t\t\r\n");
#line default
#line hidden
#line 132 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
if(member.IsIdempotent)
{
#line default
#line hidden
#line 135 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\telse\t\t\t\t\r\n\t\t\t\t\txmlWriter.WriteElementString(\"");
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", \"");
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(operation.XmlNamespace));
#line default
#line hidden
#line 137 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", Guid.NewGuid().ToString());\t\t\t\t\r\n");
#line default
#line hidden
#line 138 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
}
#line default
#line hidden
#line 141 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(""));
#line default
#line hidden
#line 141 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\r\n");
#line default
#line hidden
#line 142 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
}
}
#line default
#line hidden
#line 146 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\r\n\t\t\t\txmlWriter.WriteEndElement();\r\n");
#line default
#line hidden
#line 149 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
if(operation.RequestPayloadMember!=null)
{
#line default
#line hidden
#line 152 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t}\r\n");
#line default
#line hidden
#line 154 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
PopIndent();
}
#line default
#line hidden
#line 157 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t}\r\n\t\t\ttry \r\n\t\t\t{\r\n\t\t\t\tstring content = stringWriter.ToString();\r\n\t\t\t\trequest.C" +
"ontent = System.Text.Encoding.UTF8.GetBytes(content);\r\n\t\t\t\trequest.Headers[\"Cont" +
"ent-Type\"] = \"application/xml\";\r\n");
#line default
#line hidden
#line 164 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
GenerateRequestChecksumHandling(operation, "content");
#line default
#line hidden
#line 166 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = \"");
#line default
#line hidden
#line 167 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.ServiceModel.APIVersion));
#line default
#line hidden
#line 167 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\"; \r\n\t\t\t} \r\n\t\t\tcatch (EncoderFallbackException e) \r\n\t\t\t{\r\n\t\t\t\tthrow ne" +
"w AmazonServiceException(\"Unable to marshall request to XML\", e);\r\n\t\t\t}\r\n");
#line default
#line hidden
#line 173 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
}
void ProcessMembers(string variableName, IEnumerable<Member> members, string xmlNamespace)
{
foreach(var member in members)
{
if(member.IsStructure)
{
ProcessStructure(variableName, member, xmlNamespace);
}
else if(member.IsList)
{
ProcessList(variableName, member, xmlNamespace);
}
else if(member.IsMap)
{
ProcessMap(variableName, member, xmlNamespace);
}
else
{
#line default
#line hidden
#line 194 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\tif(");
#line default
#line hidden
#line 195 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 195 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(".IsSet");
#line default
#line hidden
#line 195 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 195 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("())\r\n\t\t\t\t\txmlWriter.WriteElementString(\"");
#line default
#line hidden
#line 196 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
#line 196 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", \"");
#line default
#line hidden
#line 196 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(xmlNamespace));
#line default
#line hidden
#line 196 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", ");
#line default
#line hidden
#line 196 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PrimitiveMarshaller));
#line default
#line hidden
#line 196 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 196 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 196 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 196 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 196 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture((member.UseNullable ? ".Value" : string.Empty)));
#line default
#line hidden
#line 196 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("));\t\t\t\t \r\n\r\n");
#line default
#line hidden
#line 198 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
}
}
}
void ProcessStructure(string variableName, Member member, string xmlNamespace)
{
var shape = member.Shape.IsList ? member.Shape.ListShape : member.Shape ;
variableName = member.Shape.IsList ? variableName : variableName + "." + member.PropertyName;
// Use shape's ListMarshallName if the structure is a list.
var marshallName = member.Shape.IsList ? member.Shape.ListMarshallName ?? "member" : member.MarshallName;
#line default
#line hidden
#line 210 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\t\r\n\t\t\t\tif (");
#line default
#line hidden
#line 211 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 211 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(" != null) \r\n\t\t\t\t{\r\n\t\t\t\t\txmlWriter.WriteStartElement(\"");
#line default
#line hidden
#line 213 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(marshallName));
#line default
#line hidden
#line 213 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", \"");
#line default
#line hidden
#line 213 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(xmlNamespace));
#line default
#line hidden
#line 213 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\");\t\t\t\r\n");
#line default
#line hidden
#line 214 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
PushIndent(" ");
ProcessMembers(variableName, shape.Members, xmlNamespace);
PopIndent();
#line default
#line hidden
#line 218 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\t\txmlWriter.WriteEndElement();\r\n\t\t\t\t}\r\n");
#line default
#line hidden
#line 221 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
}
void ProcessList(string variableName, Member member, string xmlNamespace)
{
var listVariable = (variableName + member.PropertyName).Replace(".",string.Empty);
var listItemVariable = (variableName + member.PropertyName).Replace(".",string.Empty) + "Value";
#line default
#line hidden
#line 228 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\tvar ");
#line default
#line hidden
#line 229 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listVariable));
#line default
#line hidden
#line 229 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(" = ");
#line default
#line hidden
#line 229 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 229 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 229 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 229 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(";\r\n\t\t\t\tif (");
#line default
#line hidden
#line 230 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listVariable));
#line default
#line hidden
#line 230 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(" != null && ");
#line default
#line hidden
#line 230 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listVariable));
#line default
#line hidden
#line 230 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(".Count > 0) \r\n\t\t\t\t{\t\t\t\t\t\t\r\n\t\t\t\t\txmlWriter.WriteStartElement(\"");
#line default
#line hidden
#line 232 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
#line 232 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", \"");
#line default
#line hidden
#line 232 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(xmlNamespace));
#line default
#line hidden
#line 232 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\");\r\n\t\t\t\t\tforeach (var ");
#line default
#line hidden
#line 233 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listItemVariable));
#line default
#line hidden
#line 233 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(" in ");
#line default
#line hidden
#line 233 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listVariable));
#line default
#line hidden
#line 233 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(") \r\n\t\t\t\t\t{\r\n");
#line default
#line hidden
#line 235 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
PushIndent(" ");
if(member.Shape.ListShape.IsStructure)
{
ProcessStructure(listItemVariable, member, xmlNamespace);
}
else
{
var listMarshallName = member.Shape.ListMarshallName ?? "member";
if(member.Shape.ListShape.IsDateTime)
{
// Use shape's ListMarshallName as it's a list structure.
#line default
#line hidden
#line 247 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\t\txmlWriter.WriteStartElement(\"");
#line default
#line hidden
#line 248 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listMarshallName));
#line default
#line hidden
#line 248 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", \"");
#line default
#line hidden
#line 248 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(xmlNamespace));
#line default
#line hidden
#line 248 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\");\r\n xmlWriter.WriteValue(");
#line default
#line hidden
#line 249 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.Shape.ListShape.PrimitiveMarshaller(MarshallLocation.Body)));
#line default
#line hidden
#line 249 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("(");
#line default
#line hidden
#line 249 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listItemVariable));
#line default
#line hidden
#line 249 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("));\r\n xmlWriter.WriteEndElement();\r\n");
#line default
#line hidden
#line 251 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
}
else
{
// Use shape's ListMarshallName as it's a list structure.
#line default
#line hidden
#line 257 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\t\txmlWriter.WriteStartElement(\"");
#line default
#line hidden
#line 258 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listMarshallName));
#line default
#line hidden
#line 258 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", \"");
#line default
#line hidden
#line 258 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(xmlNamespace));
#line default
#line hidden
#line 258 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\");\r\n xmlWriter.WriteValue(");
#line default
#line hidden
#line 259 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listItemVariable));
#line default
#line hidden
#line 259 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(");\r\n xmlWriter.WriteEndElement();\r\n");
#line default
#line hidden
#line 261 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
}
}
PopIndent();
#line default
#line hidden
#line 265 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\t\t}\t\t\t\r\n\t\t\t\t\txmlWriter.WriteEndElement();\t\t\t\r\n\t\t\t\t}\r\n");
#line default
#line hidden
#line 269 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
}
void ProcessMap(string variableName, Member member, string xmlNamespace)
{
#line default
#line hidden
#line 274 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\t\txmlWriter.WriteStartElement(\"");
#line default
#line hidden
#line 275 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
#line 275 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", \"");
#line default
#line hidden
#line 275 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(xmlNamespace));
#line default
#line hidden
#line 275 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\");\r\n\t\t\t\t\tforeach (var kvp in ");
#line default
#line hidden
#line 276 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(variableName));
#line default
#line hidden
#line 276 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(".");
#line default
#line hidden
#line 276 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
#line 276 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(") \r\n\t\t\t\t\t{\r\n");
#line default
#line hidden
#line 278 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
PushIndent(" ");
#line default
#line hidden
#line 280 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\t\txmlWriter.WriteStartElement(\"entry\", \"");
#line default
#line hidden
#line 281 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(xmlNamespace));
#line default
#line hidden
#line 281 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\");\r\n\t\t\t\t\txmlWriter.WriteElementString(\"key\", \"");
#line default
#line hidden
#line 282 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(xmlNamespace));
#line default
#line hidden
#line 282 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", kvp.Key);\r\n\t\t\t\t\txmlWriter.WriteElementString(\"value\", \"");
#line default
#line hidden
#line 283 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(xmlNamespace));
#line default
#line hidden
#line 283 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\", kvp.Value);\r\n\t\t\t\t\txmlWriter.WriteEndElement();\r\n");
#line default
#line hidden
#line 285 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
PopIndent();
#line default
#line hidden
#line 287 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
this.Write("\t\t\t\t\t}\t\t\t\r\n\t\t\t\t\txmlWriter.WriteEndElement();\t\t\t\t\r\n");
#line default
#line hidden
#line 290 "C:\Projects\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlRequestMarshaller.tt"
}
#line default
#line hidden
}
#line default
#line hidden
}
| 1,291 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class RestXmlResponseUnmarshaller : BaseResponseUnmarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("\r\nnamespace ");
#line 12 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Response U" +
"nmarshaller for ");
#line 15 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" operation\r\n /// </summary> \r\n public class ");
#line 17 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@"ResponseUnmarshaller : XmlResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name=""context""></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
");
#line 26 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("Response response = new ");
#line 26 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("Response();\r\n");
#line 27 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
var payload= this.Operation.ResponsePayloadMember;
var shouldMarshallPayload = (payload != null && payload.IsStructure);
var payloadIsStream = (payload != null && !shouldMarshallPayload);
if (this.Operation.ResponseHasBodyMembers || shouldMarshallPayload)
{
if (this.Operation.AllowEmptyResult)
{
#line default
#line hidden
this.Write(" if (context.ResponseData.IsSuccessStatusCode && context.ResponseData." +
"ContentLength == 0)\r\n return response;\r\n");
#line 38 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
foreach (var marshallName in this.Structure.FindMarshallNamesWithoutMembers())
{
#line default
#line hidden
this.Write("\t\t\tcontext.AllowEmptyElementLookup.Add(\"");
#line 44 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(marshallName));
#line default
#line hidden
this.Write("\");\r\n");
#line 45 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" UnmarshallResult(context,response);\r\n");
#line 49 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
else if (payloadIsStream)
{
if (payload.IsStreaming)
{
#line default
#line hidden
this.Write(" response.");
#line 56 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" = context.Stream;\r\n");
#line 57 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
else if (payload.ModelShape.IsString)
{
#line default
#line hidden
this.Write(" using (var sr = new StreamReader(context.Stream))\r\n {\r\n " +
" response.");
#line 64 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" = sr.ReadToEnd();\r\n }\r\n");
#line 66 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
else if (payload.ModelShape.IsMemoryStream)
{
#line default
#line hidden
this.Write("\r\n var ms = new MemoryStream();\r\n Amazon.Util.AWSSDKUtils.C" +
"opyStream(context.Stream, ms);\r\n ms.Seek(0, SeekOrigin.Begin);\r\n " +
" response.");
#line 75 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" = ms;\r\n\r\n");
#line 77 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
else
{
// At this point, all valid configurations have been handled. Valid use of payload is defined:
// https://awslabs.github.io/smithy/1.0/spec/core/http-traits.html#httppayload-trait
throw new Exception(
$"{payload.PropertyName} can not be a Payload as Type {payload.Shape.Type} is not a valid target for the httpPayload trait. " +
"The httpPayload trait can be applied to structure members that target a string, blob, structure, union, document, set, map, or list.");
}
}
UnmarshallHeaders();
ProcessStatusCode();
#line default
#line hidden
this.Write(" \r\n return response;\r\n\t\t}\t\t\r\n");
#line 93 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
if ( this.Operation.ResponseHasBodyMembers || shouldMarshallPayload)
{
#line default
#line hidden
this.Write("\r\n");
#line 98 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
if (this.Operation.ResponseBodyMembers.Count == 0 && !shouldMarshallPayload)
{
#line default
#line hidden
this.Write("\t\t[System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Usage\", \"CA1801:Rev" +
"iewUnusedParameters\", MessageId=\"response\")]\r\n");
#line 103 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write("\t\tprivate static void UnmarshallResult(XmlUnmarshallerContext context, ");
#line 106 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("Response response)\r\n {\r\n int originalDepth = context.CurrentDep" +
"th;\r\n int targetDepth = originalDepth + 1;\r\n");
#line 110 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
if (payload == null)
{
#line default
#line hidden
this.Write("\t\t\tif (context.IsStartOfDocument) \r\n\t\t\t\t targetDepth += 1;\r\n");
#line 116 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write("\r\n while (context.Read())\r\n {\r\n\t\t\t\tif (context.IsStartEleme" +
"nt || context.IsAttribute)\r\n {\r\n");
#line 124 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
foreach (var member in this.Operation.ResponseBodyMembers)
{
if (member.Shape.IsList)
{
var listMarshallName = member.Shape.ListMarshallName ?? "member";
if (member.Shape.IsFlattened)
{
#line default
#line hidden
this.Write("\t\t\t\t\tif (context.TestExpression(\"");
#line 134 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listMarshallName));
#line default
#line hidden
this.Write("\", targetDepth))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tvar unmarshaller = ");
#line 136 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n\t\t\t\t\t\tresponse.");
#line 137 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(".Add(unmarshaller.Unmarshall(context));\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n");
#line 140 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write("\t\t\t\t if (context.TestExpression(\"");
#line 147 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
this.Write("/");
#line 147 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listMarshallName));
#line default
#line hidden
this.Write("\", targetDepth))\r\n\t\t\t\t {\r\n\t\t\t\t\t var unmarshaller = ");
#line 149 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n\t\t\t\t\t response.");
#line 150 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(".Add(unmarshaller.Unmarshall(context));\r\n\t\t\t\t\t continue;\r\n\t\t\t\t }\r\n");
#line 153 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
}
else
{
#line default
#line hidden
this.Write("\t\t\t\t\tif (context.TestExpression(\"");
#line 159 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
this.Write("\", targetDepth))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tvar unmarshaller = ");
#line 161 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n\t\t\t\t\t\tresponse.");
#line 162 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n");
#line 165 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
}
if (shouldMarshallPayload)
{
#line default
#line hidden
this.Write("\t\t\t\t\tif (context.TestExpression(\"");
#line 172 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.MarshallName));
#line default
#line hidden
this.Write("\", targetDepth))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tvar unmarshaller = ");
#line 174 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n\t\t\t\t\t\tresponse.");
#line 175 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n");
#line 178 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write("\t\t\t\t}\r\n\t\t\t\telse if (context.IsEndElement && context.CurrentDepth < originalDepth)" +
"\r\n {\r\n return;\r\n }\r\n " +
" }\r\n \r\n return;\r\n }\r\n");
#line 190 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(@"
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name=""context""></param>
/// <param name=""innerException""></param>
/// <param name=""statusCode""></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null))
{
");
#line 212 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
foreach (var exception in this.Operation.Exceptions)
{
#line default
#line hidden
this.Write(" if (errorResponse.Code != null && errorResponse.Code.Equals(\"");
#line 216 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Code));
#line default
#line hidden
this.Write("\"))\r\n {\r\n return ");
#line 218 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Name));
#line default
#line hidden
this.Write("Unmarshaller.Instance.Unmarshall(contextCopy, errorResponse);\r\n }\r" +
"\n");
#line 220 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" }\r\n return new ");
#line 224 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.BaseException));
#line default
#line hidden
this.Write("(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, e" +
"rrorResponse.RequestId, statusCode);\r\n }\r\n\r\n");
#line 227 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlResponseUnmarshaller.tt"
this.AddResponseSingletonMethod();
#line default
#line hidden
this.Write(" }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 511 |
aws-sdk-net | aws | C# | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class RestXmlStructureUnmarshaller : BaseResponseUnmarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("\r\nnamespace ");
#line 12 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Response U" +
"nmarshaller for ");
#line 15 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" Object\r\n /// </summary> \r\n public class ");
#line 17 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("Unmarshaller : IUnmarshaller<");
#line 17 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(", XmlUnmarshallerContext>\r\n {\r\n /// <summary>\r\n /// Unmarshaller" +
" the response from the service to the response class.\r\n /// </summary> \r" +
"\n /// <param name=\"context\"></param>\r\n /// <returns></returns>\r\n " +
" public ");
#line 24 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" Unmarshall(XmlUnmarshallerContext context)\r\n {\r\n ");
#line 26 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" unmarshalledObject = new ");
#line 26 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@"();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.Read())
{
if (context.IsStartElement || context.IsAttribute)
{
");
#line 37 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
if(this.Structure != null)
{
// For every member, generate code to add the unmarshalled member to the response object
foreach (var member in this.Structure.Members)
{
if(member.Shape.IsList)
{
var listMarshallName = member.Shape.ListMarshallName ?? "member";
#line default
#line hidden
this.Write("\t\t\t\t\tif (context.TestExpression(\"");
#line 47 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
this.Write("/");
#line 47 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(listMarshallName));
#line default
#line hidden
this.Write("\", targetDepth))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tvar unmarshaller = ");
#line 49 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n\t\t\t\t\t\tunmarshalledObject.");
#line 50 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(".Add(unmarshaller.Unmarshall(context));\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n");
#line 53 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write("\t\t\t\t\tif (context.TestExpression(\"");
#line 58 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
this.Write("\", targetDepth))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tvar unmarshaller = ");
#line 60 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n\t\t\t\t\t\tunmarshalledObject.");
#line 61 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n");
#line 64 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
}
}
}
#line default
#line hidden
this.Write(@" }
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return unmarshalledObject;
}
}
return unmarshalledObject;
}
");
#line 78 "C:\projects\aws\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\RestXmlStructureUnmarshaller.tt"
this.AddStructureSingletonMethod();
#line default
#line hidden
this.Write(" }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 218 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.