コード例 #1
0
        /// <summary>Creates a message representation as follows:
        /// HTTP method\n +
        /// Content-MD5\n +
        /// Response content type (accept header)\n +
        /// Canonicalized URI\n
        /// ISO-8601 UTC timestamp including milliseconds (e.g. 2013-09-23T09:24:43.5395441Z)\n
        /// Public-Key
        /// </summary>
        public string CreateMessageRepresentation(WebApiRequestContext context, string contentMd5Hash, string timestamp, bool queryStringDecode = false)
        {
            if (context == null || !context.IsValid)
            {
                return(null);
            }

            var url = context.Url;

            if (queryStringDecode)
            {
                var uri = new Uri(url);

                if (uri.Query != null && uri.Query.Length > 0)
                {
                    url = string.Concat(uri.GetLeftPart(UriPartial.Path), HttpUtility.UrlDecode(uri.Query));
                }
            }

            var result = string.Join(_delimiterRepresentation,
                                     context.HttpMethod.ToLower(),
                                     contentMd5Hash ?? "",
                                     context.HttpAcceptType.ToLower(),
                                     url.ToLower(),
                                     timestamp,
                                     context.PublicKey.ToLower()
                                     );

            return(result);
        }
コード例 #2
0
		/// <summary>Creates a message representation as follows:
		/// HTTP method\n +
		/// Content-MD5\n + 
		/// Response content type (accept header)\n + 
		/// Canonicalized URI\n
		/// ISO-8601 UTC timestamp including milliseconds (e.g. 2013-09-23T09:24:43.5395441Z)\n
		/// Public-Key
		/// </summary>
		public string CreateMessageRepresentation(WebApiRequestContext context, string contentMd5Hash, string timestamp)
		{
			if (context == null || !context.IsValid)
				return null;

			string result = string.Join(_delimiterRepresentation,
				context.HttpMethod.ToLower(),
				contentMd5Hash ?? "",
				context.HttpAcceptType.ToLower(),
				context.Url.ToLower(),
				timestamp,
				context.PublicKey.ToLower()
			);
			return result;
		}
コード例 #3
0
        /// <summary>Creates a message representation as follows:
        /// HTTP method\n +
        /// Content-MD5\n +
        /// Response content type (accept header)\n +
        /// Canonicalized URI\n
        /// ISO-8601 UTC timestamp including milliseconds (e.g. 2013-09-23T09:24:43.5395441Z)\n
        /// Public-Key
        /// </summary>
        public string CreateMessageRepresentation(WebApiRequestContext context, string contentMd5Hash, string timestamp)
        {
            if (context == null || !context.IsValid)
            {
                return(null);
            }

            string result = string.Join(_delimiterRepresentation,
                                        context.HttpMethod.ToLower(),
                                        contentMd5Hash ?? "",
                                        context.HttpAcceptType.ToLower(),
                                        context.Url.ToLower(),
                                        timestamp,
                                        context.PublicKey.ToLower()
                                        );

            return(result);
        }
コード例 #4
0
        private void CallTheApi()
        {
            if (!string.IsNullOrWhiteSpace(txtUrl.Text) && !txtUrl.Text.EndsWith("/"))
                txtUrl.Text = txtUrl.Text + "/";

            if (!string.IsNullOrWhiteSpace(cboPath.Text) && !cboPath.Text.StartsWith("/"))
                cboPath.Text = "/" + cboPath.Text;

            var context = new WebApiRequestContext()
            {
                PublicKey = txtPublicKey.Text,
                SecretKey = txtSecretKey.Text,
                Url = txtUrl.Text + (radioOdata.Checked ? "odata/" : "api/") + txtVersion.Text + cboPath.Text,
                HttpMethod = cboMethod.Text,
                HttpAcceptType = (radioJson.Checked ? ApiConsumer.JsonAcceptType : ApiConsumer.XmlAcceptType)
            };

            if (!string.IsNullOrWhiteSpace(cboQuery.Text))
                context.Url = string.Format("{0}?{1}", context.Url, cboQuery.Text);

            if (!context.IsValid)
            {
                "Please enter Public-Key, Secret-Key, URL and method.".Box(MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Debug.WriteLine(context.ToString());
                return;
            }

            var apiConsumer = new ApiConsumer();
            var requestContent = new StringBuilder();
            var response = new WebApiConsumerResponse();
            var sb = new StringBuilder();

            lblRequest.Text = "Request: " + context.HttpMethod + " " + context.Url;
            lblRequest.Refresh();

            var webRequest = apiConsumer.StartRequest(context, cboContent.Text, requestContent);

            txtRequest.Text = requestContent.ToString();

            bool result = apiConsumer.ProcessResponse(webRequest, response);

            lblResponse.Text = "Response: " + response.Status;

            sb.Append(response.Headers);

            if (result && radioJson.Checked && radioOdata.Checked)
            {
                var customers = apiConsumer.TryParseCustomers(response);

                if (customers != null)
                {
                    sb.AppendLine(string.Format("Parsed {0} customer(s):", customers.Count));

                    foreach (var customer in customers)
                        sb.AppendLine(customer.ToString());

                    sb.Append("\r\n");
                }
            }

            sb.Append(response.Content);
            txtResponse.Text = sb.ToString();

            cboPath.InsertRolled(cboPath.Text, 64);
            cboQuery.InsertRolled(cboQuery.Text, 64);
            cboContent.InsertRolled(cboContent.Text, 64);
        }
コード例 #5
0
        public HttpWebRequest StartRequest(WebApiRequestContext context, string content, Dictionary <string, object> multipartData, out StringBuilder requestContent)
        {
            requestContent = new StringBuilder();

            if (context == null || !context.IsValid)
            {
                return(null);
            }

            // client system time must not be too far away from api server time! check response header.
            // ISO-8601 utc timestamp with milliseconds (e.g. 2013-09-23T09:24:43.5395441Z)
            string timestamp = DateTime.UtcNow.ToString("o");

            byte[] data           = null;
            string contentMd5Hash = "";

            var request = (HttpWebRequest)WebRequest.Create(context.Url);

            SetTimeout(request);

            request.UserAgent = Program.ConsumerName;                           // optional
            request.Method    = context.HttpMethod;

            request.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
            request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache, no-store");

            request.Accept = context.HttpAcceptType;
            request.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8");

            request.Headers.Add(WebApiGlobal.HeaderName.PublicKey, context.PublicKey);
            request.Headers.Add(WebApiGlobal.HeaderName.Date, timestamp);

            if (multipartData != null && multipartData.Count > 0)
            {
                var formDataBoundary = string.Format("----------{0:N}", Guid.NewGuid());

                data           = GetMultipartFormData(multipartData, formDataBoundary, requestContent);
                contentMd5Hash = CreateContentMd5Hash(data);

                request.ContentLength = data.Length;
                request.ContentType   = "multipart/form-data; boundary=" + formDataBoundary;
            }
            else if (!string.IsNullOrWhiteSpace(content) && BodySupported(request.Method))
            {
                requestContent.Append(content);
                data           = Encoding.UTF8.GetBytes(content);
                contentMd5Hash = CreateContentMd5Hash(data);

                request.ContentLength = data.Length;
                request.ContentType   = "application/json; charset=utf-8";
            }
            else if (BodySupported(request.Method))
            {
                request.ContentLength = 0;
            }

            if (!string.IsNullOrEmpty(contentMd5Hash))
            {
                // optional... provider returns HmacResult.ContentMd5NotMatching if there's no match
                request.Headers.Add(HttpRequestHeader.ContentMd5, contentMd5Hash);
            }

            string messageRepresentation = CreateMessageRepresentation(context, contentMd5Hash, timestamp, true);
            //Debug.WriteLine(messageRepresentation);
            string signature = CreateSignature(context.SecretKey, messageRepresentation);

            request.Headers.Add(HttpRequestHeader.Authorization, CreateAuthorizationHeader(signature));

            if (data != null)
            {
                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }

            requestContent.Insert(0, request.Headers.ToString());

            return(request);
        }
コード例 #6
0
		public HttpWebRequest StartRequest(WebApiRequestContext context, string content, Dictionary<string, object> multipartData, out StringBuilder requestContent)
		{
			requestContent = new StringBuilder();

			if (context == null || !context.IsValid)
				return null;

			// client system time must not be too far away from api server time! check response header.
			// ISO-8601 utc timestamp with milliseconds (e.g. 2013-09-23T09:24:43.5395441Z)
			string timestamp = DateTime.UtcNow.ToString("o");

			byte[] data = null;
			string contentMd5Hash = "";

			var request = (HttpWebRequest)WebRequest.Create(context.Url);
			SetTimeout(request);

			request.UserAgent = Program.ConsumerName;		// optional
			request.Method = context.HttpMethod;

			request.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
			request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache, no-store");

			request.Accept = context.HttpAcceptType;
			request.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8");

			request.Headers.Add(WebApiGlobal.HeaderName.PublicKey, context.PublicKey);
			request.Headers.Add(WebApiGlobal.HeaderName.Date, timestamp);

			if (multipartData != null && multipartData.Count > 0)
			{
				var formDataBoundary = string.Format("----------{0:N}", Guid.NewGuid());

				data = GetMultipartFormData(multipartData, formDataBoundary, requestContent);
				contentMd5Hash = CreateContentMd5Hash(data);

				request.ContentLength = data.Length;
				request.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
			}
			else if (!string.IsNullOrWhiteSpace(content) && BodySupported(request.Method))
			{
				requestContent.Append(content);
				data = Encoding.UTF8.GetBytes(content);
				contentMd5Hash = CreateContentMd5Hash(data);
				
				request.ContentLength = data.Length;
				request.ContentType = "application/json; charset=utf-8";
			}
			else if (BodySupported(request.Method))
			{
				request.ContentLength = 0;
			}

			if (!string.IsNullOrEmpty(contentMd5Hash))
			{
				// optional... provider returns HmacResult.ContentMd5NotMatching if there's no match
				request.Headers.Add(HttpRequestHeader.ContentMd5, contentMd5Hash);
			}

			string messageRepresentation = CreateMessageRepresentation(context, contentMd5Hash, timestamp);
			//Debug.WriteLine(messageRepresentation);
			string signature = CreateSignature(context.SecretKey, messageRepresentation);

			request.Headers.Add(HttpRequestHeader.Authorization, CreateAuthorizationHeader(signature));

			if (data != null)
			{
				using (var stream = request.GetRequestStream())
				{
					stream.Write(data, 0, data.Length);
				}
			}

			requestContent.Insert(0, request.Headers.ToString());

			return request;
		}
コード例 #7
0
        /// <summary>Creates a message representation as follows:
        /// HTTP method\n +
        /// Content-MD5\n + 
        /// Response content type (accept header)\n + 
        /// Canonicalized URI\n
        /// ISO-8601 UTC timestamp including milliseconds (e.g. 2013-09-23T09:24:43.5395441Z)\n
        /// Public-Key
        /// </summary>
        public string CreateMessageRepresentation(WebApiRequestContext context, string contentMd5Hash, string timestamp, bool queryStringDecode = false)
        {
            if (context == null || !context.IsValid)
                return null;

            var url = context.Url;

            if (queryStringDecode)
            {
                var uri = new Uri(url);

                if (uri.Query != null && uri.Query.Length > 0)
                {
                    url = string.Concat(uri.GetLeftPart(UriPartial.Path), HttpUtility.UrlDecode(uri.Query));
                }
            }

            var result = string.Join(_delimiterRepresentation,
                context.HttpMethod.ToLower(),
                contentMd5Hash ?? "",
                context.HttpAcceptType.ToLower(),
                url.ToLower(),
                timestamp,
                context.PublicKey.ToLower()
            );

            return result;
        }
コード例 #8
0
        private void CallTheApi()
        {
            if (txtUrl.Text.HasValue() && !txtUrl.Text.EndsWith("/"))
                txtUrl.Text = txtUrl.Text + "/";

            if (cboPath.Text.HasValue() && !cboPath.Text.StartsWith("/"))
                cboPath.Text = "/" + cboPath.Text;

            var context = new WebApiRequestContext
            {
                PublicKey = txtPublicKey.Text,
                SecretKey = txtSecretKey.Text,
                Url = txtUrl.Text + (radioOdata.Checked ? "odata/" : "api/") + txtVersion.Text + cboPath.Text,
                HttpMethod = cboMethod.Text,
                HttpAcceptType = (radioJson.Checked ? ApiConsumer.JsonAcceptType : ApiConsumer.XmlAcceptType)
            };

            if (cboQuery.Text.HasValue())
                context.Url = string.Format("{0}?{1}", context.Url, cboQuery.Text);

            if (!context.IsValid)
            {
                "Please enter Public-Key, Secret-Key, URL and method.".Box(MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Debug.WriteLine(context.ToString());
                return;
            }

            var apiConsumer = new ApiConsumer();
            var response = new WebApiConsumerResponse();
            var sb = new StringBuilder();
            StringBuilder requestContent = null;
            Dictionary<string, object> multiPartData = null;

            lblRequest.Text = "Request: " + context.HttpMethod + " " + context.Url;
            lblRequest.Refresh();

            if (radioApi.Checked && txtFile.Text.HasValue())
            {
                var id1 = txtIdentfier1.Text.ToInt();
                var id2 = txtIdentfier2.Text;
                var keyForId1 = "Id";
                var keyForId2 = "";

                multiPartData = new Dictionary<string, object>();

                if (cboPath.Text.StartsWith("/Uploads/ProductImages"))
                {
                    // only one identifier required: product id, sku or gtin
                    keyForId2 = "Sku";
                }
                else if (cboPath.Text.StartsWith("/Uploads/ImportFiles"))
                {
                    // only one identifier required: import profile id or profile name
                    keyForId2 = "Name";

                    // to delete existing import files:
                    //multiPartData.Add("deleteExisting", true);
                }

                if (id1 != 0)
                    multiPartData.Add(keyForId1, id1);

                if (id2.HasValue())
                    multiPartData.Add(keyForId2, id2);

                apiConsumer.AddApiFileParameter(multiPartData, txtFile.Text);
            }

            var webRequest = apiConsumer.StartRequest(context, cboContent.Text, multiPartData, out requestContent);
            txtRequest.Text = requestContent.ToString();

            var result = apiConsumer.ProcessResponse(webRequest, response);

            lblResponse.Text = "Response: " + response.Status;

            sb.Append(response.Headers);

            if (result && radioJson.Checked && radioOdata.Checked)
            {
                var customers = response.TryParseCustomers();

                if (customers != null)
                {
                    sb.AppendLine("Parsed {0} customer(s):".FormatInvariant(customers.Count));

                    customers.ForEach(x => sb.AppendLine(x.ToString()));

                    sb.Append("\r\n");
                }
            }

            sb.Append(response.Content);
            txtResponse.Text = sb.ToString();

            cboPath.InsertRolled(cboPath.Text, 64);
            cboQuery.InsertRolled(cboQuery.Text, 64);
            cboContent.InsertRolled(cboContent.Text, 64);
        }