/// <summary> /// GetAttachmentInfo. /// </summary> /// <remarks> /// Get AttachmentInfo structure describing the attachment views. /// </remarks> /// <param name='attachmentId'> /// attachment id. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code. /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response. /// </exception> /// <exception cref="ValidationException"> /// Thrown when an input value does not match the expected data type, range or pattern. /// </exception> /// <exception cref="System.ArgumentNullException"> Thrown when a required parameter is null. </exception> /// <returns> /// A response object containing the response body and response headers. /// </returns> public async Task <HttpOperationResponse <AttachmentInfo> > GetAttachmentInfoWithHttpMessagesAsync(string attachmentId, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (attachmentId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "attachmentId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(CultureInfo.InvariantCulture); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("attachmentId", attachmentId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetAttachmentInfo", tracingParameters); } // Construct URL var baseUrl = Client.BaseUri.AbsoluteUri; var url = new System.Uri(new System.Uri(baseUrl + (baseUrl.EndsWith("/", System.StringComparison.InvariantCulture) ? string.Empty : "/")), "v3/attachments/{attachmentId}").ToString(); url = url.Replace("{attachmentId}", System.Uri.EscapeDataString(attachmentId)); // Create HTTP transport objects var httpRequest = new HttpRequestMessage(); HttpResponseMessage httpResponse = null; httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new System.Uri(url); // Set Headers 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); } } // Serialize Request string requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string responseContent = null; if ((int)statusCode != 200) { var ex = new ErrorResponseException($"Operation returned an invalid status code '{statusCode}'"); try { responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(responseContent, Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(httpRequest, requestContent); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } httpRequest.Dispose(); if (httpResponse != null) { httpResponse.Dispose(); } throw ex; } // Create Result var result = new HttpOperationResponse <AttachmentInfo>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if ((int)statusCode == 200) { responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <AttachmentInfo>(responseContent, Client.DeserializationSettings); } catch (JsonException ex) { httpRequest.Dispose(); if (httpResponse != null) { httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", responseContent, ex); } } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return(result); }
/// <summary> /// GetAttachment /// </summary> /// <remarks> /// Get the named view as binary content /// </remarks> /// <param name='attachmentId'> /// attachment id /// </param> /// <param name='viewId'> /// View id from attachmentInfo /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <Stream> > GetAttachmentWithHttpMessagesAsync(string attachmentId, string viewId, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (attachmentId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "attachmentId"); } if (viewId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "viewId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("attachmentId", attachmentId); tracingParameters.Add("viewId", viewId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetAttachment", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? string.Empty : "/")), "v3/attachments/{attachmentId}/views/{viewId}").ToString(); _url = _url.Replace("{attachmentId}", System.Uri.EscapeDataString(attachmentId)); _url = _url.Replace("{viewId}", System.Uri.EscapeDataString(viewId)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers 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); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 301 && (int)_statusCode != 302) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <Stream>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Retrieve an Azure Active Directory token for particular AAD resources. /// </summary> /// <param name="userId">The user's ID.</param> /// <param name="connectionName">Name of the auth connection to use for AAD token exchange.</param> /// <param name="resourceUrls">The collection of resource URLs for which to get tokens.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the response includes a collection of TokenResponse /// objects with the resourceUrl and its corresponding TokenResponse.</remarks> public async Task <Dictionary <string, TokenResponse> > GetAadTokensAsync(string userId, string connectionName, string[] resourceUrls, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(userId)) { throw new ArgumentNullException(nameof(userId)); } if (string.IsNullOrEmpty(connectionName)) { throw new ArgumentNullException(nameof(connectionName)); } if (resourceUrls == null) { throw new ArgumentNullException(nameof(resourceUrls)); } if (resourceUrls.Length == 0) { throw new ArgumentException("Collection cannot be empty", nameof(resourceUrls)); } if (resourceUrls.Any(s => string.IsNullOrEmpty(s))) { throw new ArgumentException("Resource URLs must have a value", nameof(resourceUrls)); } bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(CultureInfo.InvariantCulture); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("userId", userId); tracingParameters.Add("connectionName", connectionName); tracingParameters.Add("resourceUrls", resourceUrls); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "SignOutUserAsync", tracingParameters); } // Construct URL var tokenUrl = new Uri(new Uri(_uri + (_uri.EndsWith("/", StringComparison.OrdinalIgnoreCase) ? string.Empty : "/")), "api/usertoken/GetAadTokens?userId={userId}&connectionName={connectionName}").ToString(); tokenUrl = tokenUrl.Replace("{userId}", Uri.EscapeDataString(userId)); tokenUrl = tokenUrl.Replace("{connectionName}", Uri.EscapeDataString(connectionName)); // Create HTTP transport objects var httpRequest = new HttpRequestMessage(); HttpResponseMessage httpResponse = null; httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new Uri(tokenUrl); // Serialize Request string requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(new AadResourceUrls() { ResourceUrls = resourceUrls }, _client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, System.Text.Encoding.UTF8); httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (_client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await _client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } httpResponse = await _client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); try { if (statusCode == HttpStatusCode.OK) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { var tokens = Rest.Serialization.SafeJsonConvert.DeserializeObject <Dictionary <string, TokenResponse> >(responseContent); return(tokens); } catch (JsonException) { // ignore json exception and return null return(null); } } else if (statusCode == HttpStatusCode.NotFound) { return(null); } else { var ex = new ErrorResponseException(string.Format(CultureInfo.InvariantCulture, "Operation returned an invalid status code '{0}'", statusCode)); string responseContent = null; try { responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(responseContent, _client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(httpRequest, requestContent); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } } finally { httpRequest.Dispose(); if (httpResponse != null) { httpResponse.Dispose(); } } }
/// <summary> /// Send a dummy OAuth card when the bot is being used on the Emulator for testing without fetching a real token. /// </summary> /// <param name="client">client.</param> /// <param name="emulateOAuthCards">Indicates whether the Emulator should emulate the OAuth card.</param> /// <returns>A task that represents the work queued to execute.</returns> public static async Task SendEmulateOAuthCardsAsync(OAuthClient client, bool emulateOAuthCards) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("emulateOAuthCards", emulateOAuthCards); ServiceClientTracing.Enter(invocationId, client, "GetToken", tracingParameters); } // Construct URL var baseUrl = client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? string.Empty : "/")), "api/usertoken/emulateOAuthCards?emulate={emulate}").ToString(); url = url.Replace("{emulate}", emulateOAuthCards.ToString()); // Create HTTP transport objects var httpRequest = new HttpRequestMessage(); HttpResponseMessage httpResponse = null; httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new System.Uri(url); var cancellationToken = CancellationToken.None; // Serialize Request string requestContent = null; // Set Credentials if (client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string responseContent = null; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NotFound) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); try { responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(responseContent, client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(httpRequest, requestContent); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } httpRequest.Dispose(); if (httpResponse != null) { httpResponse.Dispose(); } throw ex; } // Create Result var result = new HttpOperationResponse <int>(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } }