@using System.Globalization @using System.Linq; @using System @using AutoRest.Core.Model @using AutoRest.Core.Utilities @using AutoRest.CSharp @using AutoRest.CSharp.Model @using AutoRest.Extensions @inherits AutoRest.Core.Template @foreach (ParameterCs parameter in Model.Parameters.Where(p => !p.IsConstant)) { if (parameter.IsRequired && parameter.IsNullable()) { @:if (@(parameter.Name) == null) @:{ @:throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "@(parameter.Name)"); @:} @: } if(parameter.CanBeValidated && (Model.HttpMethod != HttpMethod.Patch || parameter.Location != ParameterLocation.Body)) { @:@(parameter.ModelType.ValidateType(Model, parameter.Name, parameter.Constraints)) } } @foreach (ParameterCs parameter in Model.Parameters.Where(p => p.IsConstant && !p.IsClientProperty)) { @:@(parameter.ModelTypeName) @(parameter.Name) = @(parameter.DefaultValue); } @Model.BuildInputMappings() // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary tracingParameters = new System.Collections.Generic.Dictionary(); @foreach (var parameter in Model.LogicalParameters.Where(p => !p.IsClientProperty)) { @:tracingParameters.Add("@(parameter.Name)", @(parameter.Name)); } tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "@(Model.Name)", tracingParameters); } // Construct URL @if (Model.IsAbsoluteUrl) { @:string _url = "@(Model.Url)"; } else { if (Model.IsCustomBaseUri) { @:var _baseUrl = @(Model.ClientReference).BaseUri; @:var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "@(Model.Url.TrimStart('/'))"; } else { @:var _baseUrl = @(Model.ClientReference).BaseUri.AbsoluteUri; @:var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "@(Model.Url.TrimStart('/'))").ToString(); } } @(Model.BuildUrl("_url")) // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("@(Model.HttpMethod.ToString().ToUpper())"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers @(Model.SetDefaultHeaders) @foreach (var parameter in Model.LogicalParameters.OfType().Where(p => p.Location == ParameterLocation.Header && !p.IsHeaderCollection && !p.IsContentTypeHeader)) { if (!parameter.IsNullable()) { @:if (_httpRequest.Headers.Contains("@(parameter.SerializedName)")) @:{ @: _httpRequest.Headers.Remove("@(parameter.SerializedName)"); @:} @:_httpRequest.Headers.TryAddWithoutValidation("@(parameter.SerializedName)", @parameter.ModelType.ToString(Model.ClientReference, parameter.Name)); } else { @:if (@(parameter.Name) != null) @:{ @: if (_httpRequest.Headers.Contains("@(parameter.SerializedName)")) @: { @: _httpRequest.Headers.Remove("@(parameter.SerializedName)"); @: } @: _httpRequest.Headers.TryAddWithoutValidation("@(parameter.SerializedName)", @parameter.ModelType.ToString(Model.ClientReference, parameter.Name)); @:} } } @EmptyLine @foreach (var parameter in Model.LogicalParameters.OfType().Where(p => p.Location == ParameterLocation.Header && p.IsHeaderCollection)) { @:if (@(parameter.Name) != null) @:{ @: foreach (var _header in @(parameter.Name)) @: { @: var key = "@(parameter.HeaderCollectionPrefix)" + _header.Key; @: if (_httpRequest.Headers.Contains(key)) @: { @: _httpRequest.Headers.Remove(key); @: } @: _httpRequest.Headers.TryAddWithoutValidation(key, _header.Value); @: } @:} } @EmptyLine if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } @EmptyLine // Serialize Request string _requestContent = null; @if (Model.RequestBody != null) { if (Model.RequestBody.ModelType.IsPrimaryType(KnownPrimaryType.Stream)) { if (Model.RequestBody.IsRequired) { @:if(@(Model.RequestBody.Name) == null) @:{ @: throw new System.ArgumentNullException("@(Model.RequestBody.Name)"); @:} } if (@(Model.RequestBody.Name) != null && @(Model.RequestBody.Name) != System.IO.Stream.Null) { _httpRequest.Content = new System.Net.Http.StreamContent(@(Model.RequestBody.Name)); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse(@(((Func)(p => p != null ? (p.Name.Value + ((p.ModelType as EnumType)?.ModelAsString == false ? ".ToSerializedValue()" : "")) : $"\"{Model.RequestContentType}\"" ))(Model.LocalParameters.FirstOrDefault(p => p.IsContentTypeHeader)))); } } else { if (Model.RequestContentType.StartsWith("application/xml")) { if (!Model.RequestBody.IsNullable()) { if (Model.RequestBody.ModelType is SequenceType && (Model.RequestBody.ModelType as SequenceType).ElementType is CompositeType) { // for primitive sequences for now @:_requestContent = new System.Xml.Linq.XElement("@Model.RequestBody.ModelType.XmlName", System.Linq.Enumerable.Select(@(Model.RequestBody.Name), x => x.XmlSerialize(new System.Xml.Linq.XElement("@((Model.RequestBody.ModelType as SequenceType).ElementXmlName)")))).ToString(); } else if (Model.RequestBody.ModelType is SequenceType) { // for primitive sequences for now @:_requestContent = new System.Xml.Linq.XElement("@Model.RequestBody.ModelType.XmlName", System.Linq.Enumerable.Select(@(Model.RequestBody.Name), x => new System.Xml.Linq.XElement("@((Model.RequestBody.ModelType as SequenceType).ElementXmlName)", x))).ToString(); } else { @:_requestContent = @(Model.RequestBody.Name).XmlSerialize( new System.Xml.Linq.XElement("@Model.RequestBody.ModelType.XmlName") ).ToString(); @:_requestContent = $"\n{_requestContent}"; } @:_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); @:_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("@(Model.RequestContentType)"); } else { @:if(@(Model.RequestBody.Name) != null) @:{ if (Model.RequestBody.ModelType is SequenceType && (Model.RequestBody.ModelType as SequenceType).ElementType is CompositeType) { // for primitive sequences for now @:_requestContent = new System.Xml.Linq.XElement("@Model.RequestBody.ModelType.XmlName", System.Linq.Enumerable.Select(@(Model.RequestBody.Name), x => x.XmlSerialize(new System.Xml.Linq.XElement("@((Model.RequestBody.ModelType as SequenceType).ElementXmlName)")))).ToString(); } else if (Model.RequestBody.ModelType is SequenceType) { // for primitive sequences for now @:_requestContent = new System.Xml.Linq.XElement("@Model.RequestBody.ModelType.XmlName", System.Linq.Enumerable.Select(@(Model.RequestBody.Name), x => new System.Xml.Linq.XElement("@((Model.RequestBody.ModelType as SequenceType).ElementXmlName)", x))).ToString(); } else { @:_requestContent = @(Model.RequestBody.Name).XmlSerialize( new System.Xml.Linq.XElement("@Model.RequestBody.ModelType.XmlName") ).ToString(); @:_requestContent = $"\n{_requestContent}"; } @:_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); @:_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("@(Model.RequestContentType)"); @:} } } else { if (!Model.RequestBody.IsNullable()) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(@(Model.RequestBody.Name), @(Model.GetSerializationSettingsReference(Model.RequestBody.ModelType))); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("@(Model.RequestContentType)"); } else { if(@(Model.RequestBody.Name) != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(@(Model.RequestBody.Name), @(Model.GetSerializationSettingsReference(Model.RequestBody.ModelType))); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("@(Model.RequestContentType)"); } } } } } else if (Model.LogicalParameters.Any(p => p.Location == ParameterLocation.FormData)) { if (!Model.RequestContentType.StartsWith("application/x-www-form-urlencoded")) { @:System.Net.Http.MultipartFormDataContent _multiPartContent = new System.Net.Http.MultipartFormDataContent(); foreach (ParameterCs parameter in Model.LogicalParameters.Where(p => p.Location == ParameterLocation.FormData)) { @:if (@(parameter.Name) != null) @:{ @{ string localParam = "_"+ @parameter.Name.Value.Replace("this.", ""); } if (parameter.ModelType.IsPrimaryType(KnownPrimaryType.Stream)) { System.Net.Http.StreamContent _@parameter.Name = new System.Net.Http.StreamContent(@parameter.Name); @(localParam).Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); System.Net.Http.Headers.ContentDispositionHeaderValue _contentDispositionHeaderValue = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data"); _contentDispositionHeaderValue.Name = "@(parameter.SerializedName)"; // get filename from stream if it's a file otherwise, just use 'unknown' var _fileStream = @parameter.Name as System.IO.FileStream; var _fileName = (_fileStream != null ? _fileStream.Name : null) ?? "unknown"; if(System.Linq.Enumerable.Any(_fileName, c => c > 127) ) { // non ASCII chars detected, need UTF encoding: _contentDispositionHeaderValue.FileNameStar = _fileName; } else { // ASCII only _contentDispositionHeaderValue.FileName = _fileName; } @(localParam).Headers.ContentDisposition = _contentDispositionHeaderValue; } else { @:System.Net.Http.StringContent @(localParam) = new System.Net.Http.StringContent(@(parameter.ModelType.ToString(Model.ClientReference, parameter.Name)), System.Text.Encoding.UTF8); } @:_multiPartContent.Add(@(localParam), "@(parameter.SerializedName)"); @:} } @:_httpRequest.Content = _multiPartContent; } else { @:var values = new System.Collections.Generic.List>(); foreach (ParameterCs parameter in Model.LogicalParameters.Where(p => p.Location == ParameterLocation.FormData)) { @:if(@(parameter.Name) != null) @:{ @:values.Add(new System.Collections.Generic.KeyValuePair("@(parameter.SerializedName)", @parameter.Name)); @:} } @:var _formContent = new System.Net.Http.FormUrlEncodedContent(values); @:_httpRequest.Content = _formContent; } } @if (Settings.AddCredentials) { // Set Credentials if (@(Model.ClientReference).Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await @(Model.ClientReference).Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); @if (Model.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream) || Model.HttpMethod == HttpMethod.Head) { @:_httpResponse = await @(Model.ClientReference).HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); } else { @:_httpResponse = await @(Model.ClientReference).HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if (@(Model.FailureStatusCodePredicate)) { var ex = new @(Model.OperationExceptionTypeString)(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); @if (Model.DefaultResponse.Body != null) { @:try @:{ if (Model.DefaultResponse.Body.IsPrimaryType(KnownPrimaryType.Stream)) { @:@(Model.DefaultResponse.Body.AsNullableType()) _errorBody = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); } else { @:_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); @:@(Model.DefaultResponse.Body.AsNullableType()) _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<@(Model.DefaultResponse.Body.AsNullableType())>(_responseContent, @(Model.GetDeserializationSettingsReference(Model.DefaultResponse.Body))); } @:if (_errorBody != null) @:{ @:@(Model.InitializeExceptionWithMessage) @:ex.Body = _errorBody; @:} @:} @:catch (Newtonsoft.Json.JsonException) @:{ @: // Ignore the exception @:} } else { //If not defined by default model, read content as string @:if (_httpResponse.Content != null) { @:_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); @:} @:else { @:_responseContent = string.Empty; @:} } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); @(Model.InitializeException) if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new @(Model.OperationResponseReturnTypeString)(); _result.Request = _httpRequest; _result.Response = _httpResponse; @(Model.InitializeResponseBody) @foreach (var responsePair in Model.Responses.Where(r => r.Value.Body != null)) { // Deserialize Response if ((int)_statusCode == @MethodCs.GetStatusCodeReference(responsePair.Key)) { @if (responsePair.Value.Body.IsPrimaryType(KnownPrimaryType.Stream)) { @:_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); } else { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { @if (Model.CodeModel.ShouldGenerateXmlSerialization) { @responsePair.Value.Body.AsNullableType(Model.IsXNullableReturnType) _tmp_ = null; if (_httpResponse.Content.Headers.ContentType.MediaType == "application/xml" && @(XmlSerialization.XmlDeserializationClass).Root(@(XmlSerialization.GenerateDeserializer(Model.CodeModel, responsePair.Value.Body)))(System.Xml.Linq.XElement.Parse(_responseContent), out _tmp_)) { _result.Body = _tmp_; } else { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<@(responsePair.Value.Body.AsNullableType(Model.IsXNullableReturnType))>(_responseContent, @(Model.GetDeserializationSettingsReference(responsePair.Value.Body))); } } else { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<@(responsePair.Value.Body.AsNullableType(Model.IsXNullableReturnType))>(_responseContent, @(Model.GetDeserializationSettingsReference(responsePair.Value.Body))); } } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } } } @if (Model.ReturnType.Body != null && Model.DefaultResponse.Body != null && !Model.Responses.Any()) { if (Model.DefaultResponse.Body.IsPrimaryType(KnownPrimaryType.Stream)) { @:_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); } else { @:string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); @:try @:{ if (Model.CodeModel.ShouldGenerateXmlSerialization) { @: @Model.DefaultResponse.Body.AsNullableType() _tmp_ = null; @: if (_httpResponse.Content.Headers.ContentType.MediaType == "application/xml" && @: @(XmlSerialization.XmlDeserializationClass).Root(@(XmlSerialization.GenerateDeserializer(Model.CodeModel, Model.DefaultResponse.Body)))(System.Xml.Linq.XElement.Parse(_defaultResponseContent), out _tmp_)) @:{ @: _result.Body = _tmp_; @:} else @:{ @: _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<@(Model.DefaultResponse.Body.AsNullableType())>(_defaultResponseContent, @(Model.GetDeserializationSettingsReference(Model.DefaultResponse.Body))); @:} } else { @:_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<@(Model.DefaultResponse.Body.AsNullableType())>(_defaultResponseContent, @(Model.GetDeserializationSettingsReference(Model.DefaultResponse.Body))); } @:} @:catch (Newtonsoft.Json.JsonException ex) @:{ @: _httpRequest.Dispose(); @: if (_httpResponse != null) @: { @: _httpResponse.Dispose(); @: } @: throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex); @:} } } @if (Model.ReturnType.Headers != null) { @:try @:{ @:_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<@(Model.ReturnType.Headers.Name)>(Newtonsoft.Json.JsonSerializer.Create(@(Model.GetDeserializationSettingsReference(Model.DefaultResponse.Body)))); foreach (var property in (Model.ReturnType.Headers as CompositeType).Properties.OfType().Where(p => p.IsHeaderCollection)) { @:_result.Headers.@(property.Name) = new @(property.ModelTypeName.Replace("IDictionary", "Dictionary"))(); @:foreach (var header in _httpResponse.Headers) @:{ @: if (header.Key.StartsWith("@(property.HeaderCollectionPrefix)")) @: { @: _result.Headers.@(property.Name)[header.Key.Replace("@(property.HeaderCollectionPrefix)", "")] = header.Value.FirstOrDefault() as @((property.ModelType as DictionaryType).ValueType.Name); @: } @:} } @:} @:catch (Newtonsoft.Json.JsonException ex) @:{ @: _httpRequest.Dispose(); @: if (_httpResponse != null) @: { @: _httpResponse.Dispose(); @: } @: throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); @:} } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result;