Exemplo n.º 1
0
        // Perform a relayr API operation. Takes the operation, URI arguments, and a dictionary
        // of key -> value pairs (which will be converted to a JSON string) for operation content
        public async Task<HttpResponseMessage> PerformHttpOperation(ApiCall operation, string[] arguments, Dictionary<string, string> content) {
            
            // Get the URI extension and opration type from the attributes of the operation
            Type type = operation.GetType();
            FieldInfo field = type.GetRuntimeField(operation.ToString());
            string uriExtension = ((UriAttribute) field.GetCustomAttribute(typeof(UriAttribute), false)).Value;
            string operationType = ((OperationType) field.GetCustomAttribute(typeof(OperationType), false)).Value;

            // Add the arguments to the URI, if required
            uriExtension = processArguments(uriExtension, arguments);

            // Create the content json, if required
            StringContent contentJson = null;
            if (content != null)
            {
                contentJson = new StringContent(createContentJson(content));
                contentJson.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            }

            // Set up the http request
            HttpRequestMessage httpRequest = new HttpRequestMessage();
            httpRequest.Method = new HttpMethod(operationType);
            httpRequest.RequestUri = new Uri(uriExtension, UriKind.Relative);
            httpRequest.Content = contentJson;

            // Send the http request, return the response message
            try 
            { 
                return await _httpClient.SendAsync(httpRequest);
            }
            catch(ProtocolViolationException e)
            {
                throw new InvalidOperationException("Cannot send content with operation of type " + operationType, e);
            }
        }