Пример #1
0
        private async Task <Tuple <T, Dictionary <string, TE> > > GetRequestWithExpansions <T, TE>(string baseAddress, string endpoint)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseAddress);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                if (LoginType == LoginType.Anonymous)
                {
                    endpoint = string.Format("{0}{2}APIKey={1}", endpoint, smugmugTokenManager.ConsumerKey, endpoint.Contains('?') ? "&" : "?");
                }
                else if (LoginType == LoginType.OAuth)
                {
                    smugmugConsumer = new DesktopConsumer(smugmugServiceDescription, smugmugTokenManager);
                    HttpDeliveryMethods resourceHttpMethod = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest;

                    var resourceEndpoint = new MessageReceivingEndpoint(baseAddress + endpoint, resourceHttpMethod);
                    var httpRequest      = smugmugConsumer.PrepareAuthorizedRequest(resourceEndpoint, smugmugTokenManager.AccessToken);
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", httpRequest.Headers["Authorization"].Substring(6));
                }
                else
                {
                    throw new NotSupportedException(string.Format("LoginType {0} is unsupported", LoginType));
                }

                HttpResponseMessage httpResponse = client.GetAsync(endpoint).Result;
                System.Diagnostics.Trace.WriteLine(string.Format("GET {0}", httpResponse.RequestMessage.RequestUri));
                httpResponse.EnsureSuccessStatusCode();
                GetResponseWithExpansionStub <T, TE> contentResponse = await httpResponse.Content.ReadAsAsync <GetResponseWithExpansionStub <T, TE> >();

                System.Diagnostics.Trace.WriteLine(string.Format("---{0}:{1}", contentResponse.Code, contentResponse.Message));

                return(new Tuple <T, Dictionary <string, TE> >(contentResponse.Response, contentResponse.Expansions));
            }
        }
Пример #2
0
        private void ParameterizedReceiveTest(HttpDeliveryMethods scheme)
        {
            var fields = new Dictionary <string, string> {
                { "age", "15" },
                { "Name", "Andrew" },
                { "Location", "http://hostb/pathB" },
                { "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) },
                { "realm", "someValue" },
            };
            IProtocolMessage requestMessage = this.channel.ReadFromRequest(CreateHttpRequestInfo(scheme, fields));

            Assert.IsNotNull(requestMessage);
            Assert.IsInstanceOf <TestMessage>(requestMessage);
            TestMessage testMessage = (TestMessage)requestMessage;

            Assert.AreEqual(15, testMessage.Age);
            Assert.AreEqual("Andrew", testMessage.Name);
            Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri);
            if (scheme == HttpDeliveryMethods.AuthorizationHeaderRequest)
            {
                // The realm value should be ignored in the authorization header
                Assert.IsFalse(((IMessage)testMessage).ExtraData.ContainsKey("realm"));
            }
            else
            {
                Assert.AreEqual("someValue", ((IMessage)testMessage).ExtraData["realm"]);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
 /// </summary>
 /// <param name="locationUri">The URL of this endpoint.</param>
 /// <param name="method">The HTTP method(s) allowed.</param>
 public MessageReceivingEndpoint(string locationUri, HttpDeliveryMethods method)
     : this(new Uri(locationUri), method)
 {
     Contract.Requires <ArgumentNullException>(locationUri != null);
     Contract.Requires <ArgumentOutOfRangeException>(method != HttpDeliveryMethods.None);
     Contract.Requires <ArgumentOutOfRangeException>((method & HttpDeliveryMethods.HttpVerbMask) != 0, MessagingStrings.GetOrPostFlagsRequired);
 }
        /// <summary>
        /// Prepares a message for sending based on the rules of this channel binding element.
        /// </summary>
        /// <param name="message">The message to prepare for sending.</param>
        /// <returns>
        /// True if the <paramref name="message"/> applied to this binding element
        /// and the operation was successful.  False otherwise.
        /// </returns>
        public bool PrepareMessageForSending(IProtocolMessage message)
        {
            var oauthMessage = message as ITamperResistantOAuthMessage;

            if (oauthMessage != null)
            {
                HttpDeliveryMethods transmissionMethod = oauthMessage.HttpMethods;
                if ((transmissionMethod & HttpDeliveryMethods.PostRequest) != 0)
                {
                    oauthMessage.HttpMethod = "POST";
                }
                else if ((transmissionMethod & HttpDeliveryMethods.GetRequest) != 0)
                {
                    oauthMessage.HttpMethod = "GET";
                }
                else
                {
                    return(false);
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #5
0
        /// <summary>
        /// Prepares an HTTP request that carries a given message.
        /// </summary>
        /// <param name="request">The message to send.</param>
        /// <returns>
        /// The <see cref="HttpRequest"/> prepared to send the request.
        /// </returns>
        protected override HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request)
        {
            ErrorUtilities.VerifyArgumentNotNull(request, "request");
            ErrorUtilities.VerifyArgumentNamed(request.Recipient != null, "request", MessagingStrings.DirectedMessageMissingRecipient);

            IDirectedProtocolMessage oauthRequest = request as IDirectedProtocolMessage;

            ErrorUtilities.VerifyArgument(oauthRequest != null, MessagingStrings.UnexpectedType, typeof(IDirectedProtocolMessage), request.GetType());

            HttpWebRequest httpRequest;

            HttpDeliveryMethods transmissionMethod = oauthRequest.HttpMethods;

            if ((transmissionMethod & HttpDeliveryMethods.AuthorizationHeaderRequest) != 0)
            {
                httpRequest = this.InitializeRequestAsAuthHeader(request);
            }
            else if ((transmissionMethod & HttpDeliveryMethods.PostRequest) != 0)
            {
                httpRequest = this.InitializeRequestAsPost(request);
            }
            else if ((transmissionMethod & HttpDeliveryMethods.GetRequest) != 0)
            {
                httpRequest = InitializeRequestAsGet(request);
            }
            else
            {
                throw new NotSupportedException();
            }
            return(httpRequest);
        }
Пример #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
 /// </summary>
 /// <param name="locationUri">The URL of this endpoint.</param>
 /// <param name="method">The HTTP method(s) allowed.</param>
 public MessageReceivingEndpoint(string locationUri, HttpDeliveryMethods method)
     : this(new Uri(locationUri), method)
 {
     Requires.NotNull(locationUri, "locationUri");
     Requires.Range(method != HttpDeliveryMethods.None, "method");
     Requires.Range((method & HttpDeliveryMethods.HttpVerbMask) != 0, "method", MessagingStrings.GetOrPostFlagsRequired);
 }
        private static HttpRequestInfo CreateHttpRequestInfo(HttpDeliveryMethods scheme, IDictionary <string, string> fields)
        {
            var requestUri           = new UriBuilder(MessagingTestBase.DefaultUrlForHttpRequestInfo);
            var headers              = new NameValueCollection();
            NameValueCollection form = null;
            string method;

            switch (scheme)
            {
            case HttpDeliveryMethods.PostRequest:
                method = "POST";
                form   = fields.ToNameValueCollection();
                headers.Add(HttpRequestHeaders.ContentType, Channel.HttpFormUrlEncoded);
                break;

            case HttpDeliveryMethods.GetRequest:
                method           = "GET";
                requestUri.Query = MessagingUtilities.CreateQueryString(fields);
                break;

            case HttpDeliveryMethods.AuthorizationHeaderRequest:
                method = "GET";
                headers.Add(HttpRequestHeaders.Authorization, CreateAuthorizationHeader(fields));
                break;

            default:
                throw new ArgumentOutOfRangeException("scheme", scheme, "Unexpected value");
            }

            return(new HttpRequestInfo(method, requestUri.Uri, form: form, headers: headers));
        }
Пример #8
0
 /// <summary>
 /// Gets the HTTP verb to use for a given <see cref="HttpDeliveryMethods"/> enum value.
 /// </summary>
 /// <param name="httpMethod">The HTTP method.</param>
 /// <returns>An HTTP verb, such as GET, POST, PUT, or DELETE.</returns>
 internal static string GetHttpVerb(HttpDeliveryMethods httpMethod)
 {
     if ((httpMethod & HttpDeliveryMethods.HttpVerbMask) == HttpDeliveryMethods.GetRequest)
     {
         return("GET");
     }
     else if ((httpMethod & HttpDeliveryMethods.HttpVerbMask) == HttpDeliveryMethods.PostRequest)
     {
         return("POST");
     }
     else if ((httpMethod & HttpDeliveryMethods.HttpVerbMask) == HttpDeliveryMethods.PutRequest)
     {
         return("PUT");
     }
     else if ((httpMethod & HttpDeliveryMethods.HttpVerbMask) == HttpDeliveryMethods.DeleteRequest)
     {
         return("DELETE");
     }
     else if ((httpMethod & HttpDeliveryMethods.HttpVerbMask) == HttpDeliveryMethods.HeadRequest)
     {
         return("HEAD");
     }
     else if ((httpMethod & HttpDeliveryMethods.AuthorizationHeaderRequest) != 0)
     {
         return("GET");                // if AuthorizationHeaderRequest is specified without an explicit HTTP verb, assume GET.
     }
     else
     {
         throw ErrorUtilities.ThrowArgumentNamed("httpMethod", MessagingStrings.UnsupportedHttpVerb, httpMethod);
     }
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
		/// </summary>
		/// <param name="location">The URL of this endpoint.</param>
		/// <param name="method">The HTTP method(s) allowed.</param>
		public MessageReceivingEndpoint(Uri location, HttpDeliveryMethods method) {
			Contract.Requires<ArgumentNullException>(location != null);
			Contract.Requires<ArgumentOutOfRangeException>(method != HttpDeliveryMethods.None);
			Contract.Requires<ArgumentOutOfRangeException>((method & HttpDeliveryMethods.HttpVerbMask) != 0, MessagingStrings.GetOrPostFlagsRequired);

			this.Location = location;
			this.AllowedMethods = method;
		}
Пример #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SignedMessageBase"/> class.
        /// </summary>
        /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param>
        /// <param name="recipient">The URI that a directed message will be delivered to.</param>
        internal SignedMessageBase(MessageTransport transport, MessageReceivingEndpoint recipient)
            : base(MessageProtections.All, transport, recipient)
        {
            ITamperResistantOAuthMessage self    = (ITamperResistantOAuthMessage)this;
            HttpDeliveryMethods          methods = ((IDirectedProtocolMessage)this).HttpMethods;

            self.HttpMethod = (methods & HttpDeliveryMethods.PostRequest) != 0 ? "POST" : "GET";
        }
Пример #11
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
		/// </summary>
		/// <param name="location">The URL of this endpoint.</param>
		/// <param name="method">The HTTP method(s) allowed.</param>
		public MessageReceivingEndpoint(Uri location, HttpDeliveryMethods method) {
			Requires.NotNull(location, "location");
			Requires.InRange(method != HttpDeliveryMethods.None, "method");
			Requires.InRange((method & HttpDeliveryMethods.HttpVerbMask) != 0, "method", MessagingStrings.GetOrPostFlagsRequired);

			this.Location = location;
			this.AllowedMethods = method;
		}
Пример #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SignedMessageBase"/> class.
        /// </summary>
        /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param>
        /// <param name="recipient">The URI that a directed message will be delivered to.</param>
        /// <param name="version">The OAuth version.</param>
        internal SignedMessageBase(MessageTransport transport, MessageReceivingEndpoint recipient, Version version)
            : base(MessageProtections.All, transport, recipient, version)
        {
            ITamperResistantOAuthMessage self    = (ITamperResistantOAuthMessage)this;
            HttpDeliveryMethods          methods = ((IDirectedProtocolMessage)this).HttpMethods;

            self.HttpMethod = MessagingUtilities.GetHttpVerb(methods);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
        /// </summary>
        /// <param name="location">The URL of this endpoint.</param>
        /// <param name="method">The HTTP method(s) allowed.</param>
        public MessageReceivingEndpoint(Uri location, HttpDeliveryMethods method)
        {
            ErrorUtilities.VerifyArgumentNotNull(location, "location");
            ErrorUtilities.VerifyArgumentInRange(method != HttpDeliveryMethods.None, "method");
            ErrorUtilities.VerifyArgumentInRange((method & (HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.GetRequest)) != 0, "method", MessagingStrings.GetOrPostFlagsRequired);

            this.Location = location;
            this.AllowedMethods = method;
        }
Пример #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
        /// </summary>
        /// <param name="location">The URL of this endpoint.</param>
        /// <param name="method">The HTTP method(s) allowed.</param>
        public MessageReceivingEndpoint(Uri location, HttpDeliveryMethods method)
        {
            Requires.NotNull(location, "location");
            Requires.Range(method != HttpDeliveryMethods.None, "method");
            Requires.Range((method & HttpDeliveryMethods.HttpVerbMask) != 0, "method", MessagingStrings.GetOrPostFlagsRequired);

            this.Location       = location;
            this.AllowedMethods = method;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
        /// </summary>
        /// <param name="location">The URL of this endpoint.</param>
        /// <param name="method">The HTTP method(s) allowed.</param>
        public MessageReceivingEndpoint(Uri location, HttpDeliveryMethods method)
        {
            ErrorUtilities.VerifyArgumentNotNull(location, "location");
            ErrorUtilities.VerifyArgumentInRange(method != HttpDeliveryMethods.None, "method");
            ErrorUtilities.VerifyArgumentInRange((method & (HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.GetRequest)) != 0, "method", MessagingStrings.GetOrPostFlagsRequired);

            this.Location       = location;
            this.AllowedMethods = method;
        }
Пример #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
        /// </summary>
        /// <param name="location">The URL of this endpoint.</param>
        /// <param name="method">The HTTP method(s) allowed.</param>
        public MessageReceivingEndpoint(Uri location, HttpDeliveryMethods method)
        {
            Contract.Requires <ArgumentNullException>(location != null);
            Contract.Requires <ArgumentOutOfRangeException>(method != HttpDeliveryMethods.None);
            Contract.Requires <ArgumentOutOfRangeException>((method & HttpDeliveryMethods.HttpVerbMask) != 0, MessagingStrings.GetOrPostFlagsRequired);

            this.Location       = location;
            this.AllowedMethods = method;
        }
Пример #17
0
        private void beginButton_Click(object sender, RoutedEventArgs e)
        {
            try {
                var service = new ServiceProviderDescription {
                    RequestTokenEndpoint      = new MessageReceivingEndpoint(this.requestTokenUrlBox.Text, this.requestTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest),
                    UserAuthorizationEndpoint = new MessageReceivingEndpoint(this.authorizeUrlBox.Text, HttpDeliveryMethods.GetRequest),
                    AccessTokenEndpoint       = new MessageReceivingEndpoint(this.accessTokenUrlBox.Text, this.accessTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest),
                    TamperProtectionElements  = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
                    ProtocolVersion           = this.oauthVersion.SelectedIndex == 0 ? ProtocolVersion.V10 : ProtocolVersion.V10a,
                };
                var tokenManager = new InMemoryTokenManager();
                tokenManager.ConsumerKey    = this.consumerKeyBox.Text;
                tokenManager.ConsumerSecret = this.consumerSecretBox.Text;

                var    consumer = new DesktopConsumer(service, tokenManager);
                string accessToken;
                if (service.ProtocolVersion == ProtocolVersion.V10)
                {
                    string requestToken;
                    Uri    authorizeUrl = consumer.RequestUserAuthorization(null, null, out requestToken);
                    Process.Start(authorizeUrl.AbsoluteUri);
                    MessageBox.Show(this, "Click OK when you've authorized the app.");
                    var authorizationResponse = consumer.ProcessUserAuthorization(requestToken, null);
                    accessToken = authorizationResponse.AccessToken;
                }
                else
                {
                    var authorizePopup = new Authorize(
                        consumer,
                        (DesktopConsumer c, out string requestToken) => c.RequestUserAuthorization(null, null, out requestToken));
                    authorizePopup.Owner = this;
                    bool?result = authorizePopup.ShowDialog();
                    if (result.HasValue && result.Value)
                    {
                        accessToken = authorizePopup.AccessToken;
                    }
                    else
                    {
                        return;
                    }
                }
                HttpDeliveryMethods resourceHttpMethod = this.resourceHttpMethodList.SelectedIndex < 2 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest;
                if (this.resourceHttpMethodList.SelectedIndex == 1)
                {
                    resourceHttpMethod |= HttpDeliveryMethods.AuthorizationHeaderRequest;
                }
                var resourceEndpoint = new MessageReceivingEndpoint(this.resourceUrlBox.Text, resourceHttpMethod);
                using (IncomingWebResponse resourceResponse = consumer.PrepareAuthorizedRequestAndSend(resourceEndpoint, accessToken)) {
                    this.resultsBox.Text = resourceResponse.GetResponseReader().ReadToEnd();
                }
            } catch (DotNetOpenAuth.Messaging.ProtocolException ex) {
                MessageBox.Show(this, ex.Message);
            }
        }
Пример #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class.
 /// </summary>
 /// <param name="message">The message being passed in through a mock transport.  May be null.</param>
 /// <param name="httpMethod">The HTTP method that the incoming request came in on, whether or not <paramref name="message"/> is null.</param>
 internal HttpRequestInfo(IDirectedProtocolMessage message, HttpDeliveryMethods httpMethod)
 {
     this.Message = message;
     if ((httpMethod & HttpDeliveryMethods.GetRequest) != 0)
     {
         this.HttpMethod = "GET";
     }
     else if ((httpMethod & HttpDeliveryMethods.PostRequest) != 0)
     {
         this.HttpMethod = "POST";
     }
 }
Пример #19
0
        private static string GetHttpVerb(HttpDeliveryMethods httpMethod)
        {
            if ((httpMethod & HttpDeliveryMethods.GetRequest) != 0)
            {
                return("GET");
            }

            if ((httpMethod & HttpDeliveryMethods.PostRequest) != 0)
            {
                return("POST");
            }

            throw new ArgumentOutOfRangeException();
        }
Пример #20
0
        private void ParameterizedRequestTest(HttpDeliveryMethods scheme)
        {
            TestDirectedMessage request = new TestDirectedMessage(MessageTransport.Direct)
            {
                Age         = 15,
                Name        = "Andrew",
                Location    = new Uri("http://hostb/pathB"),
                Recipient   = new Uri("http://localtest"),
                Timestamp   = DateTime.UtcNow,
                HttpMethods = scheme,
            };

            CachedDirectWebResponse rawResponse = null;

            this.webRequestHandler.Callback = (req) => {
                Assert.IsNotNull(req);
                HttpRequestInfo reqInfo = ConvertToRequestInfo(req, this.webRequestHandler.RequestEntityStream);
                Assert.AreEqual(MessagingUtilities.GetHttpVerb(scheme), reqInfo.HttpMethod);
                var incomingMessage = this.channel.ReadFromRequest(reqInfo) as TestMessage;
                Assert.IsNotNull(incomingMessage);
                Assert.AreEqual(request.Age, incomingMessage.Age);
                Assert.AreEqual(request.Name, incomingMessage.Name);
                Assert.AreEqual(request.Location, incomingMessage.Location);
                Assert.AreEqual(request.Timestamp, incomingMessage.Timestamp);

                var responseFields = new Dictionary <string, string> {
                    { "age", request.Age.ToString() },
                    { "Name", request.Name },
                    { "Location", request.Location.AbsoluteUri },
                    { "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) },
                };
                rawResponse = new CachedDirectWebResponse();
                rawResponse.SetResponse(MessagingUtilities.CreateQueryString(responseFields));
                return(rawResponse);
            };

            IProtocolMessage response = this.channel.Request(request);

            Assert.IsNotNull(response);
            Assert.IsInstanceOf <TestMessage>(response);
            TestMessage responseMessage = (TestMessage)response;

            Assert.AreEqual(request.Age, responseMessage.Age);
            Assert.AreEqual(request.Name, responseMessage.Name);
            Assert.AreEqual(request.Location, responseMessage.Location);
        }
Пример #21
0
        private void ParameterizedReceiveTest(HttpDeliveryMethods scheme)
        {
            var fields = new Dictionary <string, string> {
                { "age", "15" },
                { "Name", "Andrew" },
                { "Location", "http://hostb/pathB" },
                { "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) },
            };
            IProtocolMessage requestMessage = this.channel.ReadFromRequest(CreateHttpRequestInfo(scheme, fields));

            Assert.IsNotNull(requestMessage);
            Assert.IsInstanceOf <TestMessage>(requestMessage);
            TestMessage testMessage = (TestMessage)requestMessage;

            Assert.AreEqual(15, testMessage.Age);
            Assert.AreEqual("Andrew", testMessage.Name);
            Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri);
        }
Пример #22
0
        private async Task ParameterizedRequestTestAsync(HttpDeliveryMethods scheme)
        {
            var request = new TestDirectedMessage(MessageTransport.Direct)
            {
                Age         = 15,
                Name        = "Andrew",
                Location    = new Uri("http://hostb/pathB"),
                Recipient   = new Uri("http://localtest"),
                Timestamp   = DateTime.UtcNow,
                HttpMethods = scheme,
            };

            Handle(request.Recipient).By(
                async(req, ct) => {
                Assert.IsNotNull(req);
                Assert.AreEqual(MessagingUtilities.GetHttpVerb(scheme), req.Method);
                var incomingMessage = (await this.channel.ReadFromRequestAsync(req, CancellationToken.None)) as TestMessage;
                Assert.IsNotNull(incomingMessage);
                Assert.AreEqual(request.Age, incomingMessage.Age);
                Assert.AreEqual(request.Name, incomingMessage.Name);
                Assert.AreEqual(request.Location, incomingMessage.Location);
                Assert.AreEqual(request.Timestamp, incomingMessage.Timestamp);

                var responseFields = new Dictionary <string, string> {
                    { "age", request.Age.ToString() },
                    { "Name", request.Name },
                    { "Location", request.Location.AbsoluteUri },
                    { "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) },
                };
                var rawResponse     = new HttpResponseMessage();
                rawResponse.Content = new StringContent(MessagingUtilities.CreateQueryString(responseFields));
                return(rawResponse);
            });

            IProtocolMessage response = await this.channel.RequestAsync(request, CancellationToken.None);

            Assert.IsNotNull(response);
            Assert.IsInstanceOf <TestMessage>(response);
            TestMessage responseMessage = (TestMessage)response;

            Assert.AreEqual(request.Age, responseMessage.Age);
            Assert.AreEqual(request.Name, responseMessage.Name);
            Assert.AreEqual(request.Location, responseMessage.Location);
        }
Пример #23
0
        private static HttpRequestInfo CreateHttpRequestInfo(HttpDeliveryMethods scheme, IDictionary <string, string> fields)
        {
            string              query      = MessagingUtilities.CreateQueryString(fields);
            UriBuilder          requestUri = new UriBuilder("http://localhost/path");
            WebHeaderCollection headers    = new WebHeaderCollection();
            MemoryStream        ms         = new MemoryStream();
            string              method;

            switch (scheme)
            {
            case HttpDeliveryMethods.PostRequest:
                method = "POST";
                headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
                StreamWriter sw = new StreamWriter(ms);
                sw.Write(query);
                sw.Flush();
                ms.Position = 0;
                break;

            case HttpDeliveryMethods.GetRequest:
                method           = "GET";
                requestUri.Query = query;
                break;

            case HttpDeliveryMethods.AuthorizationHeaderRequest:
                method = "GET";
                headers.Add(HttpRequestHeader.Authorization, CreateAuthorizationHeader(fields));
                break;

            default:
                throw new ArgumentOutOfRangeException("scheme", scheme, "Unexpected value");
            }
            HttpRequestInfo request = new HttpRequestInfo {
                HttpMethod         = method,
                UrlBeforeRewriting = requestUri.Uri,
                RawUrl             = requestUri.Path + requestUri.Query + requestUri.Fragment,
                Headers            = headers,
                InputStream        = ms,
            };

            return(request);
        }
Пример #24
0
        /// <summary>
        /// Prepares a message for sending based on the rules of this channel binding element.
        /// </summary>
        /// <param name="message">The message to prepare for sending.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// True if the <paramref name="message"/> applied to this binding element
        /// and the operation was successful.  False otherwise.
        /// </returns>
        public Task <MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken)
        {
            var oauthMessage = message as ITamperResistantOAuthMessage;

            if (oauthMessage != null)
            {
                HttpDeliveryMethods transmissionMethod = oauthMessage.HttpMethods;
                try {
                    oauthMessage.HttpMethod = MessagingUtilities.GetHttpVerb(transmissionMethod);
                    return(MessageProtectionTasks.None);
                } catch (ArgumentException ex) {
                    Logger.OAuth.ErrorException("Unrecognized HttpDeliveryMethods value.", ex);
                    return(MessageProtectionTasks.Null);
                }
            }
            else
            {
                return(MessageProtectionTasks.Null);
            }
        }
Пример #25
0
        /// <summary>
        /// Prepares an HTTP request that carries a given message.
        /// </summary>
        /// <param name="request">The message to send.</param>
        /// <returns>
        /// The <see cref="HttpRequest"/> prepared to send the request.
        /// </returns>
        protected override HttpRequestMessage CreateHttpRequest(IDirectedProtocolMessage request)
        {
            HttpRequestMessage httpRequest;

            HttpDeliveryMethods transmissionMethod = request.HttpMethods;

            if ((transmissionMethod & HttpDeliveryMethods.AuthorizationHeaderRequest) != 0)
            {
                httpRequest = this.InitializeRequestAsAuthHeader(request);
            }
            else if ((transmissionMethod & HttpDeliveryMethods.PostRequest) != 0)
            {
                var requestMessageWithBinaryData = request as IMessageWithBinaryData;
                ErrorUtilities.VerifyProtocol(requestMessageWithBinaryData == null || !requestMessageWithBinaryData.SendAsMultipart, OAuthStrings.MultipartPostMustBeUsedWithAuthHeader);
                httpRequest = this.InitializeRequestAsPost(request);
            }
            else if ((transmissionMethod & HttpDeliveryMethods.GetRequest) != 0)
            {
                httpRequest = InitializeRequestAsGet(request);
            }
            else if ((transmissionMethod & HttpDeliveryMethods.HeadRequest) != 0)
            {
                httpRequest = InitializeRequestAsHead(request);
            }
            else if ((transmissionMethod & HttpDeliveryMethods.PutRequest) != 0)
            {
                httpRequest = this.InitializeRequestAsPut(request);
            }
            else if ((transmissionMethod & HttpDeliveryMethods.DeleteRequest) != 0)
            {
                httpRequest = InitializeRequestAsDelete(request);
            }
            else
            {
                throw new NotSupportedException();
            }

            return(httpRequest);
        }
Пример #26
0
        private async Task <ImageUpload> UploadImage(string albumUri, string fileName, byte[] image, CancellationToken cancellationToken)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(SMUGMUG_API_v2_UploadEndpoint);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("X-Smug-AlbumUri", albumUri);
                client.DefaultRequestHeaders.Add("X-Smug-FileName", fileName);
                client.DefaultRequestHeaders.Add("X-Smug-ResponseType", "JSON");
                client.DefaultRequestHeaders.Add("X-Smug-Version", "v2");

                if (LoginType == LoginType.OAuth)
                {
                    smugmugConsumer = new DesktopConsumer(smugmugServiceDescription, smugmugTokenManager);
                    HttpDeliveryMethods resourceHttpMethod = HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest;

                    var resourceEndpoint = new MessageReceivingEndpoint(SMUGMUG_API_v2_UploadEndpoint, resourceHttpMethod);
                    var httpRequest      = smugmugConsumer.PrepareAuthorizedRequest(resourceEndpoint, smugmugTokenManager.AccessToken);

                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", httpRequest.Headers["Authorization"].Substring(6));
                }
                else
                {
                    throw new NotSupportedException(string.Format("LoginType {0} is unsupported", LoginType));
                }

                var content = new StreamContent(new MemoryStream(image));

                HttpResponseMessage httpResponse = client.PostAsync(SMUGMUG_API_v2_UploadEndpoint, content, cancellationToken).Result;
                System.Diagnostics.Trace.WriteLine(string.Format("POST {0}", httpResponse.RequestMessage.RequestUri));
                httpResponse.EnsureSuccessStatusCode();
                ImagePostResponse contentResponse = await httpResponse.Content.ReadAsAsync <ImagePostResponse>();

                System.Diagnostics.Trace.WriteLine(string.Format("---{0} {1}: {2}", contentResponse.Stat, contentResponse.Method, contentResponse.Image));

                return(contentResponse.Image);
            }
        }
Пример #27
0
        internal static string ConstructSignatureBaseString(ITamperResistantOAuthMessage message, MessageDictionary messageDictionary)
        {
            Requires.NotNull(message, "message");
            Requires.NotNull(message.HttpMethod, "message.HttpMethod");
            Requires.NotNull(messageDictionary, "messageDictionary");
            ErrorUtilities.VerifyInternal(messageDictionary.Message == message, "Message references are not equal.");

            List <string> signatureBaseStringElements = new List <string>(3);

            signatureBaseStringElements.Add(message.HttpMethod.ToString().ToUpperInvariant());

            // For multipart POST messages, only include the message parts that are NOT
            // in the POST entity (those parts that may appear in an OAuth authorization header).
            var encodedDictionary = new Dictionary <string, string>();
            IEnumerable <KeyValuePair <string, string> > partsToInclude = Enumerable.Empty <KeyValuePair <string, string> >();
            var binaryMessage = message as IMessageWithBinaryData;

            if (binaryMessage != null && binaryMessage.SendAsMultipart)
            {
                HttpDeliveryMethods authHeaderInUseFlags = HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest;
                ErrorUtilities.VerifyProtocol((binaryMessage.HttpMethods & authHeaderInUseFlags) == authHeaderInUseFlags, OAuthStrings.MultipartPostMustBeUsedWithAuthHeader);

                // Include the declared keys in the signature as those will be signable.
                // Cache in local variable to avoid recalculating DeclaredKeys in the delegate.
                ICollection <string> declaredKeys = messageDictionary.DeclaredKeys;
                partsToInclude = messageDictionary.Where(pair => declaredKeys.Contains(pair.Key));
            }
            else
            {
                partsToInclude = messageDictionary;
            }

            // If this message was deserialized, include only those explicitly included message parts (excludes defaulted values)
            // in the signature.
            var originalPayloadMessage = (IMessageOriginalPayload)message;

            if (originalPayloadMessage.OriginalPayload != null)
            {
                partsToInclude = partsToInclude.Where(pair => originalPayloadMessage.OriginalPayload.ContainsKey(pair.Key));
            }

            foreach (var pair in OAuthChannel.GetUriEscapedParameters(partsToInclude))
            {
                encodedDictionary[pair.Key] = pair.Value;
            }

            // An incoming message will already have included the query and form parameters
            // in the message dictionary, but an outgoing message COULD have SOME parameters
            // in the query that are not in the message dictionary because they were included
            // in the receiving endpoint (the original URL).
            // In an outgoing message, the POST entity can only contain parameters if they were
            // in the message dictionary, so no need to pull out any parameters from there.
            if (message.Recipient.Query != null)
            {
                NameValueCollection nvc = HttpUtility.ParseQueryString(message.Recipient.Query);
                foreach (string key in nvc)
                {
                    string escapedKey   = MessagingUtilities.EscapeUriDataStringRfc3986(key);
                    string escapedValue = MessagingUtilities.EscapeUriDataStringRfc3986(nvc[key]);
                    string existingValue;
                    if (!encodedDictionary.TryGetValue(escapedKey, out existingValue))
                    {
                        encodedDictionary.Add(escapedKey, escapedValue);
                    }
                    else
                    {
                        ErrorUtilities.VerifyInternal(escapedValue == existingValue, "Somehow we have conflicting values for the '{0}' parameter.", escapedKey);
                    }
                }
            }
            encodedDictionary.Remove("oauth_signature");

            UriBuilder endpoint = new UriBuilder(message.Recipient);

            endpoint.Query    = null;
            endpoint.Fragment = null;
            signatureBaseStringElements.Add(endpoint.Uri.AbsoluteUri);

            var sortedKeyValueList = new List <KeyValuePair <string, string> >(encodedDictionary);

            sortedKeyValueList.Sort(SignatureBaseStringParameterComparer);
            StringBuilder paramBuilder = new StringBuilder();

            foreach (var pair in sortedKeyValueList)
            {
                if (paramBuilder.Length > 0)
                {
                    paramBuilder.Append("&");
                }

                paramBuilder.Append(pair.Key);
                paramBuilder.Append('=');
                paramBuilder.Append(pair.Value);
            }

            signatureBaseStringElements.Add(paramBuilder.ToString());

            StringBuilder signatureBaseString = new StringBuilder();

            foreach (string element in signatureBaseStringElements)
            {
                if (signatureBaseString.Length > 0)
                {
                    signatureBaseString.Append("&");
                }

                signatureBaseString.Append(MessagingUtilities.EscapeUriDataStringRfc3986(element));
            }

            Logger.Bindings.DebugFormat("Constructed signature base string: {0}", signatureBaseString);
            return(signatureBaseString.ToString());
        }
Пример #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CoordinatingHttpRequestInfo"/> class.
 /// </summary>
 /// <param name="message">The message being passed in through a mock transport.  May be null.</param>
 /// <param name="httpMethod">The HTTP method that the incoming request came in on, whether or not <paramref name="message"/> is null.</param>
 internal CoordinatingHttpRequestInfo(IDirectedProtocolMessage message, HttpDeliveryMethods httpMethod)
     : base(GetHttpVerb(httpMethod), message.Recipient)
 {
     this.message = message;
 }
Пример #29
0
		private void ParameterizedReceiveTest(HttpDeliveryMethods scheme) {
			var fields = new Dictionary<string, string> {
				{ "age", "15" },
				{ "Name", "Andrew" },
				{ "Location", "http://hostb/pathB" },
				{ "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) },
				{ "realm", "someValue" },
			};
			IProtocolMessage requestMessage = this.channel.ReadFromRequest(CreateHttpRequestInfo(scheme, fields));
			Assert.IsNotNull(requestMessage);
			Assert.IsInstanceOf<TestMessage>(requestMessage);
			TestMessage testMessage = (TestMessage)requestMessage;
			Assert.AreEqual(15, testMessage.Age);
			Assert.AreEqual("Andrew", testMessage.Name);
			Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri);
			if (scheme == HttpDeliveryMethods.AuthorizationHeaderRequest) {
				// The realm value should be ignored in the authorization header
				Assert.IsFalse(((IMessage)testMessage).ExtraData.ContainsKey("realm"));
			} else {
				Assert.AreEqual("someValue", ((IMessage)testMessage).ExtraData["realm"]);
			}
		}
Пример #30
0
		private static HttpRequestInfo CreateHttpRequestInfo(HttpDeliveryMethods scheme, IDictionary<string, string> fields) {
			var requestUri = new UriBuilder(MessagingTestBase.DefaultUrlForHttpRequestInfo);
			var headers = new NameValueCollection();
			NameValueCollection form = null;
			string method;
			switch (scheme) {
				case HttpDeliveryMethods.PostRequest:
					method = "POST";
					form = fields.ToNameValueCollection();
					headers.Add(HttpRequestHeaders.ContentType, Channel.HttpFormUrlEncoded);
					break;
				case HttpDeliveryMethods.GetRequest:
					method = "GET";
					requestUri.Query = MessagingUtilities.CreateQueryString(fields);
					break;
				case HttpDeliveryMethods.AuthorizationHeaderRequest:
					method = "GET";
					headers.Add(HttpRequestHeaders.Authorization, CreateAuthorizationHeader(fields));
					break;
				default:
					throw new ArgumentOutOfRangeException("scheme", scheme, "Unexpected value");
			}

			return new HttpRequestInfo(method, requestUri.Uri, form: form, headers: headers);
		}
Пример #31
0
		private static HttpRequestInfo CreateHttpRequestInfo(HttpDeliveryMethods scheme, IDictionary<string, string> fields) {
			string query = MessagingUtilities.CreateQueryString(fields);
			UriBuilder requestUri = new UriBuilder("http://localhost/path");
			WebHeaderCollection headers = new WebHeaderCollection();
			MemoryStream ms = new MemoryStream();
			string method;
			switch (scheme) {
				case HttpDeliveryMethods.PostRequest:
					method = "POST";
					headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
					StreamWriter sw = new StreamWriter(ms);
					sw.Write(query);
					sw.Flush();
					ms.Position = 0;
					break;
				case HttpDeliveryMethods.GetRequest:
					method = "GET";
					requestUri.Query = query;
					break;
				case HttpDeliveryMethods.AuthorizationHeaderRequest:
					method = "GET";
					headers.Add(HttpRequestHeader.Authorization, CreateAuthorizationHeader(fields));
					break;
				default:
					throw new ArgumentOutOfRangeException("scheme", scheme, "Unexpected value");
			}
			HttpRequestInfo request = new HttpRequestInfo {
				HttpMethod = method,
				UrlBeforeRewriting = requestUri.Uri,
				RawUrl = requestUri.Path + requestUri.Query + requestUri.Fragment,
				Headers = headers,
				InputStream = ms,
			};

			return request;
		}
		private static string GetHttpVerb(HttpDeliveryMethods httpMethod) {
			if ((httpMethod & HttpDeliveryMethods.GetRequest) != 0) {
				return "GET";
			}

			if ((httpMethod & HttpDeliveryMethods.PostRequest) != 0) {
				return "POST";
			}

			throw new ArgumentOutOfRangeException();
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="CoordinatingHttpRequestInfo"/> class.
		/// </summary>
		/// <param name="message">The message being passed in through a mock transport.  May be null.</param>
		/// <param name="httpMethod">The HTTP method that the incoming request came in on, whether or not <paramref name="message"/> is null.</param>
		internal CoordinatingHttpRequestInfo(IDirectedProtocolMessage message, HttpDeliveryMethods httpMethod)
			: base(GetHttpVerb(httpMethod), message.Recipient) {
			this.message = message;
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
 /// </summary>
 /// <param name="locationUri">The URL of this endpoint.</param>
 /// <param name="method">The HTTP method(s) allowed.</param>
 public MessageReceivingEndpoint(string locationUri, HttpDeliveryMethods method)
     : this(new Uri(locationUri), method)
 {
 }
Пример #35
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
		/// </summary>
		/// <param name="locationUri">The URL of this endpoint.</param>
		/// <param name="method">The HTTP method(s) allowed.</param>
		public MessageReceivingEndpoint(string locationUri, HttpDeliveryMethods method)
			: this(new Uri(locationUri), method) {
			Requires.NotNull(locationUri, "locationUri");
			Requires.InRange(method != HttpDeliveryMethods.None, "method");
			Requires.InRange((method & HttpDeliveryMethods.HttpVerbMask) != 0, "method", MessagingStrings.GetOrPostFlagsRequired);
		}
Пример #36
0
		/// <summary>
		/// Initializes a new instance of the <see cref="HttpRequestInfo"/> class.
		/// </summary>
		/// <param name="message">The message being passed in through a mock transport.  May be null.</param>
		/// <param name="httpMethod">The HTTP method that the incoming request came in on, whether or not <paramref name="message"/> is null.</param>
		internal HttpRequestInfo(IDirectedProtocolMessage message, HttpDeliveryMethods httpMethod) {
			this.message = message;
			this.HttpMethod = MessagingUtilities.GetHttpVerb(httpMethod);
		}
Пример #37
0
		private void ParameterizedReceiveTest(HttpDeliveryMethods scheme) {
			var fields = new Dictionary<string, string> {
				{ "age", "15" },
				{ "Name", "Andrew" },
				{ "Location", "http://hostb/pathB" },
				{ "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) },
			};
			IProtocolMessage requestMessage = this.channel.ReadFromRequest(CreateHttpRequestInfo(scheme, fields));
			Assert.IsNotNull(requestMessage);
			Assert.IsInstanceOf<TestMessage>(requestMessage);
			TestMessage testMessage = (TestMessage)requestMessage;
			Assert.AreEqual(15, testMessage.Age);
			Assert.AreEqual("Andrew", testMessage.Name);
			Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri);
		}
Пример #38
0
 public MessageReceivingEndpoint(Uri location, HttpDeliveryMethods method)
 {
     this.Location       = location;
     this.AllowedMethods = method;
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
		/// </summary>
		/// <param name="locationUri">The URL of this endpoint.</param>
		/// <param name="method">The HTTP method(s) allowed.</param>
		public MessageReceivingEndpoint(string locationUri, HttpDeliveryMethods method)
			: this(new Uri(locationUri), method) {
			Contract.Requires<ArgumentNullException>(locationUri != null);
			Contract.Requires<ArgumentOutOfRangeException>(method != HttpDeliveryMethods.None);
			Contract.Requires<ArgumentOutOfRangeException>((method & HttpDeliveryMethods.HttpVerbMask) != 0, MessagingStrings.GetOrPostFlagsRequired);
		}
Пример #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class.
 /// </summary>
 /// <param name="message">The message being passed in through a mock transport.  May be null.</param>
 /// <param name="httpMethod">The HTTP method that the incoming request came in on, whether or not <paramref name="message"/> is null.</param>
 internal HttpRequestInfo(IDirectedProtocolMessage message, HttpDeliveryMethods httpMethod)
 {
     this.message    = message;
     this.HttpMethod = MessagingUtilities.GetHttpVerb(httpMethod);
 }
Пример #41
0
		private async Task ParameterizedRequestTestAsync(HttpDeliveryMethods scheme) {
			var request = new TestDirectedMessage(MessageTransport.Direct) {
				Age = 15,
				Name = "Andrew",
				Location = new Uri("http://hostb/pathB"),
				Recipient = new Uri("http://localtest"),
				Timestamp = DateTime.UtcNow,
				HttpMethods = scheme,
			};

			Handle(request.Recipient).By(
				async (req, ct) => {
					Assert.IsNotNull(req);
					Assert.AreEqual(MessagingUtilities.GetHttpVerb(scheme), req.Method);
					var incomingMessage = (await this.channel.ReadFromRequestAsync(req, CancellationToken.None)) as TestMessage;
					Assert.IsNotNull(incomingMessage);
					Assert.AreEqual(request.Age, incomingMessage.Age);
					Assert.AreEqual(request.Name, incomingMessage.Name);
					Assert.AreEqual(request.Location, incomingMessage.Location);
					Assert.AreEqual(request.Timestamp, incomingMessage.Timestamp);

					var responseFields = new Dictionary<string, string> {
						{ "age", request.Age.ToString() },
						{ "Name", request.Name },
						{ "Location", request.Location.AbsoluteUri },
						{ "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) },
					};
					var rawResponse = new HttpResponseMessage();
					rawResponse.Content = new StringContent(MessagingUtilities.CreateQueryString(responseFields));
					return rawResponse;
				});

			IProtocolMessage response = await this.channel.RequestAsync(request, CancellationToken.None);
			Assert.IsNotNull(response);
			Assert.IsInstanceOf<TestMessage>(response);
			TestMessage responseMessage = (TestMessage)response;
			Assert.AreEqual(request.Age, responseMessage.Age);
			Assert.AreEqual(request.Name, responseMessage.Name);
			Assert.AreEqual(request.Location, responseMessage.Location);
		}
Пример #42
0
		private void ParameterizedRequestTest(HttpDeliveryMethods scheme) {
			TestDirectedMessage request = new TestDirectedMessage(MessageTransport.Direct) {
				Age = 15,
				Name = "Andrew",
				Location = new Uri("http://hostb/pathB"),
				Recipient = new Uri("http://localtest"),
				Timestamp = DateTime.UtcNow,
				HttpMethods = scheme,
			};

			CachedDirectWebResponse rawResponse = null;
			this.webRequestHandler.Callback = (req) => {
				Assert.IsNotNull(req);
				HttpRequestInfo reqInfo = ConvertToRequestInfo(req, this.webRequestHandler.RequestEntityStream);
				Assert.AreEqual(MessagingUtilities.GetHttpVerb(scheme), reqInfo.HttpMethod);
				var incomingMessage = this.channel.ReadFromRequest(reqInfo) as TestMessage;
				Assert.IsNotNull(incomingMessage);
				Assert.AreEqual(request.Age, incomingMessage.Age);
				Assert.AreEqual(request.Name, incomingMessage.Name);
				Assert.AreEqual(request.Location, incomingMessage.Location);
				Assert.AreEqual(request.Timestamp, incomingMessage.Timestamp);

				var responseFields = new Dictionary<string, string> {
					{ "age", request.Age.ToString() },
					{ "Name", request.Name },
					{ "Location", request.Location.AbsoluteUri },
					{ "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) },
				};
				rawResponse = new CachedDirectWebResponse();
				rawResponse.SetResponse(MessagingUtilities.CreateQueryString(responseFields));
				return rawResponse;
			};

			IProtocolMessage response = this.channel.Request(request);
			Assert.IsNotNull(response);
			Assert.IsInstanceOf<TestMessage>(response);
			TestMessage responseMessage = (TestMessage)response;
			Assert.AreEqual(request.Age, responseMessage.Age);
			Assert.AreEqual(request.Name, responseMessage.Name);
			Assert.AreEqual(request.Location, responseMessage.Location);
		}
Пример #43
0
        private async Task <T> PostRequest <T>(string baseAddress, string endpoint, string jsonContent)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseAddress);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                if (LoginType == LoginType.Anonymous)
                {
                    endpoint = string.Format("{0}{2}APIKey={1}", endpoint, smugmugTokenManager.ConsumerKey, endpoint.Contains('?') ? "&" : "?");
                }
                else if (LoginType == LoginType.OAuth)
                {
                    smugmugConsumer = new DesktopConsumer(smugmugServiceDescription, smugmugTokenManager);
                    HttpDeliveryMethods resourceHttpMethod = HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest;

                    var resourceEndpoint = new MessageReceivingEndpoint(baseAddress + endpoint, resourceHttpMethod);
                    var httpRequest      = smugmugConsumer.PrepareAuthorizedRequest(resourceEndpoint, smugmugTokenManager.AccessToken);
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", httpRequest.Headers["Authorization"].Substring(6));
                }
                else
                {
                    throw new NotSupportedException(string.Format("LoginType {0} is unsupported", LoginType));
                }

                HttpResponseMessage httpResponse = client.PostAsync(endpoint, new StringContent(jsonContent)).Result;
                System.Diagnostics.Trace.WriteLine(string.Format("POST {0}: {1}", httpResponse.RequestMessage.RequestUri, jsonContent));

                PostResponseStub <T> contentResponse = null;
                if (httpResponse.IsSuccessStatusCode)
                {
                    contentResponse = await httpResponse.Content.ReadAsAsync <PostResponseStub <T> >();
                }
                else
                {
                    var     failedResponse    = httpResponse.Content.ReadAsStringAsync();
                    JObject response          = JObject.Parse(failedResponse.Result);
                    var     invalidParameters =
                        from p in response["Options"]["Parameters"]["POST"]
                        where p["Problems"] != null
                        select new POSTParameter
                    {
                        ParameterName = (string)p["Name"],
                        Problem       = (string)p["Problems"].First()
                    };

                    if (invalidParameters.Count() > 0)
                    {
                        List <ArgumentException> argumentExceptions = new List <ArgumentException>();
                        foreach (POSTParameter invalidParameter in invalidParameters)
                        {
                            argumentExceptions.Add(new ArgumentException(invalidParameter.Problem, invalidParameter.ParameterName));
                        }
                        throw new AggregateException("HTTP POST Request failed.  See inner exceptions for individual reasons.", argumentExceptions.ToArray());
                    }
                    else
                    {
                        throw new HttpRequestException("HTTP POST Request failed for unknown reasons");
                    }
                }

                System.Diagnostics.Trace.WriteLine(string.Format("---{0} {1}: {2}", contentResponse.Code, contentResponse.Message, contentResponse.Response));

                return(contentResponse.Response);
            }
        }
 private static string GetHttpMethod(HttpDeliveryMethods methods)
 {
     return((methods & HttpDeliveryMethods.PostRequest) != 0 ? "POST" : "GET");
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
 /// </summary>
 /// <param name="locationUri">The URL of this endpoint.</param>
 /// <param name="method">The HTTP method(s) allowed.</param>
 public MessageReceivingEndpoint(string locationUri, HttpDeliveryMethods method)
     : this(new Uri(locationUri), method)
 {
 }