Exemplo n.º 1
0
        private HttpWebRequest BuildMultipartWebRequest(HttpWebRequest webReq, IORequest request, IOService service, string requestUriString)
        {
            webReq.Method = "POST";
            webReq.KeepAlive = true;
            SystemLogger.Log(SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. Request method fixed to 'POST' (only this is allowed for a form-data), and KeepAlive true");
            
            string boundary = CreateFormDataBoundary();
            webReq.ContentType = contentTypes[service.Type] + boundary;
            SystemLogger.Log(SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. Adding boundary to content-type: " + webReq.ContentType);
            // KO in some servers if Accept header is filled 
            //webReq.Accept = contentTypes[service.Type]; // setting "Accept" header with the same value as "Content Type" header, it is needed to be defined for some services.

            Dictionary<string, string> postData = new Dictionary<string, string>();

            if (request.Content != null)
            {
                SystemLogger.Log(SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. Getting form data from request Content...");

                // example of format accepted "key1=value1&key2=value2&key3=value3&"
                string[] items = request.Content.TrimEnd('&').Split('&');
                foreach (string item in items)
                {
                    string[] keyValue = item.Split('=');
                    postData.Add(keyValue[0], keyValue[1]);
                }
                SystemLogger.Log(SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. POST data form fields count: #" + postData.Count);
            }

            byte[] bContent;
            using (var ms = new MemoryStream())
            {
                WriteMultipartFormData_FromDict(postData, ms, boundary);
                
                if (request.Attachment != null)
                {
				   SystemLogger.Log (SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. Processing attachment files, count: " + request.Attachment.Length);
				   int attchCount = 0;
                   foreach (AttachmentData attachData in request.Attachment)
                    {
						try {
							if (attachData != null && attachData.ReferenceUrl != null) {
								string refUrl = this.GetAttachmentFullPath (attachData.ReferenceUrl);
								FileInfo fileToUpload = new FileInfo (refUrl);
								if (fileToUpload.Exists) {
									SystemLogger.Log (SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. #" + attchCount+ " Attaching file from referenced URL: " + refUrl);
									String fileMimeType = attachData.MimeType;
									String fileFormKey = attachData.FormFieldKey;

									WriteMultipartFormData_FromFile (fileToUpload, ms, boundary, fileMimeType, fileFormKey);
								} else {
									SystemLogger.Log (SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. #" + attchCount+ " File from referenced URL: " + refUrl + ", does not exists in filesystem, please check provided ReferenceUrl!");
								}
							} else {
								SystemLogger.Log (SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. #" + attchCount+ " Attached file does not contain a valid ReferenceUrl field. IGNORED");
							}
						} catch(Exception ex) {
							SystemLogger.Log (SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. #" + attchCount+ " Exception attaching file, exception message: "+ ex.Message);
						}
						attchCount++;
                    }
                }

                var endBytes = Encoding.UTF8.GetBytes("--" + boundary + "--");
                ms.Write(endBytes, 0, endBytes.Length);
                ms.Flush();
                bContent = ms.ToArray();
            }

            SystemLogger.Log(SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. Sending data on the request stream... (POST)");
            SystemLogger.Log(SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. Request data length: " + bContent.Length);
            using (Stream requestStream = webReq.GetRequestStream())
            {
                requestStream.Write(bContent, 0, bContent.Length);
            }

            return webReq;
        }
Exemplo n.º 2
0
        private HttpWebRequest BuildWebRequest(IORequest request, IOService service, string requestUriString, string reqMethod) {

            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(requestUriString);

            webReq.Timeout = DEFAULT_RESPONSE_TIMEOUT; // in millisecods (default is 100 seconds)
            webReq.ReadWriteTimeout = DEFAULT_READWRITE_TIMEOUT; // in milliseconds

            // [MOBPLAT-200] ... Allow Gzip or Deflate decompression methods
            webReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
			
            if (ServiceType.MULTIPART_FORM_DATA.Equals(service.Type))
            {
                SystemLogger.Log(SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. Building specific WebRequest...");
                webReq = BuildMultipartWebRequest(webReq, request, service, requestUriString);
            }
            else
            {  
                webReq.Method = reqMethod; // default is POST
                webReq.ContentType = contentTypes[service.Type];

                // check specific request ContentType defined, and override service type in that case
                if (request.ContentType != null && request.ContentType.Length > 0)
                {
                    webReq.ContentType = request.ContentType;
                }

                SystemLogger.Log(SystemLogger.Module.CORE, "Request content type: " + webReq.ContentType);
                SystemLogger.Log(SystemLogger.Module.CORE, "Request method: " + webReq.Method);

                webReq.Accept = webReq.ContentType; // setting "Accept" header with the same value as "Content Type" header, it is needed to be defined for some services.

                if (!reqMethod.Equals(RequestMethod.GET.ToString()) && request.Content != null)
                {
                    webReq.ContentLength = request.GetContentLength();
                    SystemLogger.Log(SystemLogger.Module.CORE, "Setting request ContentLength (not needed for GET): " + webReq.ContentLength);
                }

                SystemLogger.Log(SystemLogger.Module.CORE, "Request content length: " + webReq.ContentLength);
                webReq.KeepAlive = false;
            
            }

            webReq.AllowAutoRedirect = !request.StopAutoRedirect; // each request could decide if 302 redirection are automatically followed, or not. Default behaviour is to follow redirections and do not send back the 302 status code
            webReq.ProtocolVersion = HttpVersion.Version10;
            if (request.ProtocolVersion == HTTPProtocolVersion.HTTP11) webReq.ProtocolVersion = HttpVersion.Version11;

            // user agent needs to be informed - some servers check this parameter and send 500 errors when not informed.
            webReq.UserAgent = this.IOUserAgent;
            SystemLogger.Log (SystemLogger.Module.CORE, "Request UserAgent : " + webReq.UserAgent);

            /*************
             * HEADERS HANDLING
             *************/

            // add specific headers to the request
			if (request.Headers != null && request.Headers.Length > 0) {
				foreach (IOHeader header in request.Headers) {
					webReq.Headers.Add (header.Name, header.Value);
					SystemLogger.Log (SystemLogger.Module.CORE, "Added request header: " + header.Name + "=" + webReq.Headers.Get (header.Name));
				}
			}

			/*************
			 * COOKIES HANDLING
			 *************/

			// Assign the cookie container on the request to hold cookie objects that are sent on the response.
			// Required even though you no cookies are send.
			webReq.CookieContainer = this.cookieContainer;
			
			// add cookies to the request cookie container
			if (request.Session != null && request.Session.Cookies != null && request.Session.Cookies.Length > 0) {
				foreach (IOCookie cookie in request.Session.Cookies) {
					if (cookie != null && cookie.Name != null) {
						webReq.CookieContainer.Add (webReq.RequestUri, new Cookie (cookie.Name, cookie.Value));
                        SystemLogger.Log(SystemLogger.Module.CORE, "Added cookie [" + cookie.Name + "] to request. [" + cookie.Value + "]");
					}
				}
			}
			SystemLogger.Log (SystemLogger.Module.CORE, "HTTP Request cookies: " + webReq.CookieContainer.GetCookieHeader (webReq.RequestUri));
			
			/*************
			 * SETTING A PROXY (ENTERPRISE ENVIRONMENTS)
			 *************/

			if (service.Endpoint.ProxyUrl != null) {
				WebProxy myProxy = new WebProxy ();
				Uri proxyUri = new Uri (service.Endpoint.ProxyUrl);
				myProxy.Address = proxyUri;
				webReq.Proxy = myProxy;
			}

			return webReq;
		}
Exemplo n.º 3
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="service"></param>
        /// <returns></returns>
        public virtual IOResponse InvokeService(IORequest request, IOService service)
        {
            IOResponse response = new IOResponse ();

            if (service != null) {
                SystemLogger.Log (SystemLogger.Module .CORE, "Request content: " + request.Content);
                byte[] requestData = request.GetRawContent ();

                if (service.Endpoint == null) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "No endpoint configured for this service name: " + service.Name);
                    return response;
                }

                string requestUriString = String.Format ("{0}:{1}{2}", service.Endpoint.Host, service.Endpoint.Port, service.Endpoint.Path);
                if (service.Endpoint.Port == 0) {
                    requestUriString = String.Format ("{0}{1}", service.Endpoint.Host, service.Endpoint.Path);
                }

                if (service.RequestMethod == RequestMethod.GET && request.Content != null) {
                    // add request content to the URI string when GET method.
                    requestUriString += request.Content;
                }

                SystemLogger.Log (SystemLogger.Module .CORE, "Requesting service: " + requestUriString);
                try {

                    ServicePointManager.ServerCertificateValidationCallback += delegate(object sender,X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
                        SystemLogger.Log (SystemLogger.Module .CORE, "*************** On ServerCertificateValidationCallback: accept all certificates");
                        return true;
                    };

                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create (requestUriString);
                    req.Method = service.RequestMethod.ToString (); // default is POST
                    req.ContentType = contentTypes [service.Type];

                    // check specific request ContentType defined, and override service type in that case
                    if (request.ContentType != null && request.ContentType.Length > 0) {
                        req.ContentType = request.ContentType;
                    }
                    SystemLogger.Log (SystemLogger.Module.CORE, "Request content type: " + req.ContentType);
                    SystemLogger.Log (SystemLogger.Module.CORE, "Request method: " + req.Method);

                    req.Accept = req.ContentType; // setting "Accept" header with the same value as "Content Type" header, it is needed to be defined for some services.
                    req.ContentLength = request.GetContentLength ();
                    SystemLogger.Log (SystemLogger.Module.CORE, "Request content length: " + req.ContentLength);
                    req.Timeout = DEFAULT_RESPONSE_TIMEOUT; // in millisecods (default is 10 seconds)
                    req.KeepAlive = false;

                    // user agent needs to be informed - some servers check this parameter and send 500 errors when not informed.
                    req.UserAgent = this.IOUserAgent;
                    SystemLogger.Log (SystemLogger.Module.CORE, "Request UserAgent : " + req.UserAgent);

                    // add specific headers to the request
                    if (request.Headers != null && request.Headers.Length > 0) {
                        foreach (IOHeader header in request.Headers) {
                            req.Headers.Add (header.Name, header.Value);
                            SystemLogger.Log (SystemLogger.Module.CORE, "Added request header: " + header.Name + "=" + req.Headers.Get (header.Name));
                        }
                    }

                    // Assign the cookie container on the request to hold cookie objects that are sent on the response.
                    // Required even though you no cookies are send.
                    req.CookieContainer = this.cookieContainer;

                    // add cookies to the request cookie container
                    if (request.Session != null && request.Session.Cookies != null && request.Session.Cookies.Length > 0) {
                        foreach (IOCookie cookie in request.Session.Cookies) {
                            req.CookieContainer.Add (req.RequestUri, new Cookie (cookie.Name, cookie.Value));
                            SystemLogger.Log (SystemLogger.Module.CORE, "Added cookie [" + cookie.Name + "] to request.");
                        }
                    }

                    SystemLogger.Log (SystemLogger.Module.CORE, "HTTP Request cookies: " + req.CookieContainer.GetCookieHeader (req.RequestUri));

                    if (service.Endpoint.ProxyUrl != null) {
                        WebProxy myProxy = new WebProxy ();
                        Uri proxyUri = new Uri (service.Endpoint.ProxyUrl);
                        myProxy.Address = proxyUri;
                        req.Proxy = myProxy;
                    }

                    if (req.Method == RequestMethod.POST.ToString ()) {
                        // send data only for POST method.
                        SystemLogger.Log (SystemLogger.Module.CORE, "Sending data on the request stream... (POST)");
                        SystemLogger.Log (SystemLogger.Module.CORE, "request data length: " + requestData.Length);
                        using (Stream requestStream = req.GetRequestStream()) {
                            SystemLogger.Log (SystemLogger.Module.CORE, "request stream: " + requestStream);
                            requestStream.Write (requestData, 0, requestData.Length);
                        }
                    }

                    string result = null;
                    byte[] resultBinary = null;

                    string responseMimeTypeOverride = null;

                    using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) {
                        SystemLogger.Log (SystemLogger.Module.CORE, "getting response...");
                        using (Stream stream = resp.GetResponseStream()) {
                            SystemLogger.Log (SystemLogger.Module.CORE, "getting response stream...");
                            if (ServiceType.OCTET_BINARY.Equals (service.Type)) {

                                // TODO workaround to avoid problems when serving binary content (corrupted content)
                                Thread.Sleep (500);

                                int lengthContent = 0;
                                if (resp.GetResponseHeader ("Content-Length") != null && resp.GetResponseHeader ("Content-Length") != "") {
                                    lengthContent = Int32.Parse (resp.GetResponseHeader ("Content-Length"));
                                }
                                if (lengthContent > 0) {
                                    // Read in block
                                    resultBinary = new byte[lengthContent];
                                    stream.Read (resultBinary, 0, lengthContent);
                                } else {
                                    // Read to end of stream
                                    MemoryStream memBuffer = new MemoryStream ();
                                    byte[] readBuffer = new byte[256];
                                    int readLen = 0;
                                    do {
                                        readLen = stream.Read (readBuffer, 0, readBuffer.Length);
                                        memBuffer.Write (readBuffer, 0, readLen);
                                    } while (readLen >0);

                                    resultBinary = memBuffer.ToArray ();
                                    memBuffer.Close ();
                                    memBuffer = null;
                                }
                            } else {
                                SystemLogger.Log (SystemLogger.Module.CORE, "reading response content...");
                                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
                                    result = reader.ReadToEnd ();
                                }
                            }
                        }
                        responseMimeTypeOverride = resp.GetResponseHeader ("Content-Type");

                        // get response cookies (stored on cookiecontainer)
                        if (response.Session == null) {
                            response.Session = new IOSessionContext ();

                        }
                        response.Session.Cookies = new IOCookie[this.cookieContainer.Count];
                        IEnumerator enumerator = this.cookieContainer.GetCookies (req.RequestUri).GetEnumerator ();
                        int i = 0;
                        while (enumerator.MoveNext()) {
                            Cookie cookieFound = (Cookie)enumerator.Current;
                            SystemLogger.Log (SystemLogger.Module.CORE, "Found cookie on response: " + cookieFound.Name + "=" + cookieFound.Value);
                            IOCookie cookie = new IOCookie ();
                            cookie.Name = cookieFound.Name;
                            cookie.Value = cookieFound.Value;
                            response.Session.Cookies [i] = cookie;
                            i++;
                        }
                    }

                    if (ServiceType.OCTET_BINARY.Equals (service.Type)) {
                        if (responseMimeTypeOverride != null && !responseMimeTypeOverride.Equals (contentTypes [service.Type])) {
                            response.ContentType = responseMimeTypeOverride;
                        } else {
                            response.ContentType = contentTypes [service.Type];
                        }
                        response.ContentBinary = resultBinary; // Assign binary content here
                    } else {
                        response.ContentType = contentTypes [service.Type];
                        response.Content = result;
                    }

                } catch (WebException ex) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "WebException requesting service: " + requestUriString + ".", ex);
                    response.ContentType = contentTypes [ServiceType.REST_JSON];
                    response.Content = "WebException Requesting Service: " + requestUriString + ". Message: " + ex.Message;
                } catch (Exception ex) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "Unnandled Exception requesting service: " + requestUriString + ".", ex);
                    response.ContentType = contentTypes [ServiceType.REST_JSON];
                    response.Content = "Unhandled Exception Requesting Service: " + requestUriString + ". Message: " + ex.Message;
                }
            } else {
                SystemLogger.Log (SystemLogger.Module .CORE, "Null service received for invoking.");
            }

            return response;
        }
Exemplo n.º 4
0
		private string FormatRequestUriString(IORequest request, IOService service, string reqMethod) {

			string requestUriString = String.Format ("{0}:{1}{2}", service.Endpoint.Host, service.Endpoint.Port, service.Endpoint.Path);
			if (service.Endpoint.Port == 0) 
			{
				requestUriString = String.Format ("{0}{1}", service.Endpoint.Host, service.Endpoint.Path);
			}
			
			if (reqMethod.Equals(RequestMethod.GET.ToString()) && request.Content != null)
			{
				// add request content to the URI string when NOT POST method (GET, PUT, DELETE).
				requestUriString += request.Content;
			}
			
			SystemLogger.Log (SystemLogger.Module .CORE, "Requesting service: " + requestUriString);
			return requestUriString;
		}
Exemplo n.º 5
0
 public abstract Task<IOResponse> InvokeService(IORequest request, IOService service);
Exemplo n.º 6
0
 public abstract Task<string> InvokeServiceForBinary(IORequest request, IOService service, string storePath);
Exemplo n.º 7
0
        private async Task<HttpRequestMessage> BuildMultipartWebRequest(IORequest request, IOService service, string requestUriString)
        {

            var webRequest = new HttpRequestMessage(HttpMethod.Post, new Uri(requestUriString));
            webRequest.Headers.Add("Keep-Alive", "true");
            var sBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
            var multipartFormDataContent = new HttpMultipartFormDataContent(sBoundary);

            if (request.Content != null)
            {
                var items = request.Content.TrimEnd('&').Split('&');
                foreach (var keyValue in items.Select(item => item.Split('=')))
                {
                    multipartFormDataContent.Add(new HttpStringContent(keyValue[1]), keyValue[0]);
                }
            }
            webRequest.Content = multipartFormDataContent;
            if (request.Attachment == null) return webRequest;
            foreach (var attachData in request.Attachment)
            {
                try
                {
                    if (!String.IsNullOrWhiteSpace(attachData.ReferenceUrl))
                    {
                        var attachmentFile = await WindowsPhoneUtils.GetFileFromReferenceURL(attachData.ReferenceUrl);
                        if (attachmentFile != null)
                        {
                            multipartFormDataContent.Add(new HttpStreamContent(await attachmentFile.OpenReadAsync()), attachData.FormFieldKey, attachData.FileName ?? attachmentFile.Name);
                        }
                        else
                        {
                            WindowsPhoneUtils.Log("**** [MULTIPART_FORM_DATA]. # File from referenced URL: " + attachData.ReferenceUrl + ", does not exists in filesystem, please check provided ReferenceUrl!");
                        }
                    }
                    else
                    {
                        WindowsPhoneUtils.Log("**** [MULTIPART_FORM_DATA]. # Attached file does not contain a valid ReferenceUrl field. IGNORED");
                    }
                }
                catch (Exception ex)
                {
                    WindowsPhoneUtils.Log(ex.Message);
                }
            }
            return webRequest;
        }
Exemplo n.º 8
0
		/// <summary>
		/// Invokes a service for getting a big binary, storing it into filesystem and returning the reference url.
		/// Only OCTET_BINARY service types are allowed.
		/// </summary>
		/// <returns>The reference Url for the stored file (if success, null otherwise.</returns>
		/// <param name="request">Request.</param>
		/// <param name="service">Service.</param>
		/// <param name="storePath">Store path.</param>
		public virtual string InvokeServiceForBinary (IORequest request, IOService service, string storePath) {

			if (service != null) {
				
				if (service.Endpoint == null) {
					SystemLogger.Log (SystemLogger.Module .CORE, "No endpoint configured for this service name: " + service.Name);
					return null;
				} 

				if (!ServiceType.OCTET_BINARY.Equals (service.Type)) {
					SystemLogger.Log (SystemLogger.Module .CORE, "This method only admits OCTET_BINARY service types");
					return null;
				}
				
				SystemLogger.Log (SystemLogger.Module .CORE, "Request content: " + request.Content);
				byte[] requestData = request.GetRawContent ();
				
				String reqMethod = service.RequestMethod.ToString(); // default is POST
				if (request.Method != null && request.Method != String.Empty) reqMethod = request.Method.ToUpper();
				
				String requestUriString = this.FormatRequestUriString(request, service, reqMethod);
				Thread timeoutThread = null;
				
				try {
					
					// Security - VALIDATIONS
					ServicePointManager.ServerCertificateValidationCallback = ValidateWebCertificates;
					
					// Building Web Request to send
					HttpWebRequest webReq = this.BuildWebRequest(request, service, requestUriString, reqMethod);
					
					// Throw a new Thread to check absolute timeout
					timeoutThread = new Thread(CheckInvokeTimeout);
					timeoutThread.Start(webReq);
					
					// POSTING DATA using timeout
                    if (!reqMethod.Equals(RequestMethod.GET.ToString()) && requestData != null && !ServiceType.MULTIPART_FORM_DATA.Equals(service.Type))
					{
						// send data only for POST method.
						SystemLogger.Log (SystemLogger.Module.CORE, "Sending data on the request stream... (POST)");
						SystemLogger.Log (SystemLogger.Module.CORE, "request data length: " + requestData.Length);
						using (Stream requestStream = webReq.GetRequestStream()) {
							SystemLogger.Log (SystemLogger.Module.CORE, "request stream: " + requestStream);
							requestStream.Write (requestData, 0, requestData.Length);
						}
					}
					
					using (HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse()) {
						
						SystemLogger.Log (SystemLogger.Module.CORE, "getting response...");
						return this.ReadWebResponseAndStore(webReq, webResp, service, storePath);
					}
					
				} catch (WebException ex) {
					SystemLogger.Log (SystemLogger.Module .CORE, "WebException requesting service: " + requestUriString + ".", ex);
				} catch (Exception ex) {
					SystemLogger.Log (SystemLogger.Module .CORE, "Unnandled Exception requesting service: " + requestUriString + ".", ex);
				} finally {
					// abort any previous timeout checking thread
					if(timeoutThread!=null && timeoutThread.IsAlive) {
						timeoutThread.Abort();
					}
				}
			} else {
				SystemLogger.Log (SystemLogger.Module .CORE, "Null service received for invoking.");
			}
			
			return null;
		}
Exemplo n.º 9
0
        private async Task<IOResponse> ReadWebResponse(HttpRequestMessage webRequest, HttpResponseMessage webResponse, IOService service)
        {
            var response = new IOResponse();

            // result types (string or byte array)
            byte[] resultBinary = null;
            string result = null;

            var responseMimeTypeOverride = webResponse.Content.Headers.ContentType.MediaType;

            using (var stream = (await webResponse.Content.ReadAsInputStreamAsync()).AsStreamForRead())
            {
                WindowsPhoneUtils.Log("getting response stream...");
                if (ServiceType.OCTET_BINARY.Equals(service.Type))
                {
                    var lengthContent = (int)webResponse.Content.Headers.ContentLength;
                    // testing log line
                    // SystemLogger.Log (SystemLogger.Module.CORE, "content-length header: " + lengthContent +", max file size: " + MAX_BINARY_SIZE);
                    var bufferReadSize = DEFAULT_BUFFER_READ_SIZE;
                    if (lengthContent >= 0 && lengthContent <= bufferReadSize)
                    {
                        bufferReadSize = lengthContent;
                    }

                    if (lengthContent > MAX_BINARY_SIZE)
                    {
                        WindowsPhoneUtils.Log("WARNING! - file exceeds the maximum size defined in platform (" + MAX_BINARY_SIZE + " bytes)");
                    }
                    else
                    {
                        // Read to end of stream in blocks
                        WindowsPhoneUtils.Log("buffer read: " + bufferReadSize + " bytes");
                        var memBuffer = new MemoryStream();
                        var readBuffer = new byte[bufferReadSize];
                        int readLen;
                        do
                        {
                            //readLen = stream.Read(readBuffer, 0, readBuffer.Length);
                            readLen = await stream.ReadAsync(readBuffer, 0, readBuffer.Length);
                            memBuffer.Write(readBuffer, 0, readLen);
                        } while (readLen > 0);

                        resultBinary = memBuffer.ToArray();
                        memBuffer.Flush();
                    }
                }
                else
                {
                    WindowsPhoneUtils.Log("reading response content...");
                    using (var reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                        WindowsPhoneUtils.Log("Response Content: " + result);
                    }
                }
            }

            /*************
             * CACHE
             ************

            // preserve cache-control header from remote server, if any
            var cacheControlHeader = (webResponse.Headers.CacheControl != null) ? webResponse.Headers.CacheControl.ToString() : String.Empty;
            if (!String.IsNullOrWhiteSpace(cacheControlHeader))
            {
                WindowsPhoneUtils.Log("Found Cache-Control header on response: " + cacheControlHeader + ", using it on internal response...");
                if (response.Headers == null)
                {
                    response.Headers = new IOHeader[1];
                }
                var cacheHeader = new IOHeader { Name = "Cache-Control", Value = cacheControlHeader };
                response.Headers[0] = cacheHeader;
            }
            */
            /*************
             * HEADERS HANDLING
             *************/
            if (webResponse.Headers != null)
            {
                response.Headers = new IOHeader[webResponse.Headers.Count];

                var size = 0;
                foreach (var headerKey in webResponse.Headers.Keys)
                {
                    string headerValue;
                    webResponse.Headers.TryGetValue(headerKey, out headerValue);
                    var objHeader = new IOHeader { Name = headerKey, Value = headerValue };
                    response.Headers[size++] = objHeader;
                }
            }


            /*************
             * COOKIES HANDLING
             *************/

            // get response cookies (stored on cookiecontainer)
            if (response.Session == null)
            {
                response.Session = new IOSessionContext();
            }

            var filter = new HttpBaseProtocolFilter();
            var cookieCollection = filter.CookieManager.GetCookies(webRequest.RequestUri);

            var myCookies = new List<IOCookie>();

            foreach (var cookieFound in cookieCollection)
            {
                var value = cookieFound.ToString().Replace(String.Concat(cookieFound.Name, "="), String.Empty);
                WindowsPhoneUtils.Log("Found cookie on response: " + cookieFound.Name + "=" + value);
                if (cookieFound.ToString().Split(new string[] { "Path=" }, StringSplitOptions.None).Length > 2 || cookieFound.ToString().Split(new string[] { "Domain=" }, StringSplitOptions.None).Length > 2) continue;
                WindowsPhoneUtils.Log("Added cookie to response: " + cookieFound.Name + "=" + value);
                var cookie = new IOCookie { Name = cookieFound.Name, Value = value };
                myCookies.Add(cookie);
            }
            response.Session.Cookies = myCookies.ToArray();

            if (ServiceType.OCTET_BINARY.Equals(service.Type))
            {
                if (responseMimeTypeOverride != null && !responseMimeTypeOverride.Equals(ContentTypes[service.Type]))
                {
                    response.ContentType = responseMimeTypeOverride;
                }
                else
                {
                    response.ContentType = ContentTypes[service.Type];
                }
                response.ContentBinary = resultBinary; // Assign binary content here
            }
            else
            {
                response.ContentType = ContentTypes[service.Type];
                response.Content = result;
            }

            return response;
        }
Exemplo n.º 10
0
        private async Task<HttpRequestMessage> BuildWebRequest(IORequest request, IOService service, string requestUriString, string reqMethod)
        {
            var _clientBaseConfig = WindowsPhoneUtils.CreateHttpClientOptions(true);
            var requestHttpMethod = HttpMethod.Post;
            HttpRequestMessage webRequest = null;

            try
            {
                if (service.Type == ServiceType.MULTIPART_FORM_DATA)
                {
                    webRequest = await BuildMultipartWebRequest(request, service, requestUriString);
                }
                else
                {
                    switch (service.RequestMethod)
                    {
                        case RequestMethod.GET:
                            requestHttpMethod = HttpMethod.Get;
                            break;
                    }

                    if (!String.IsNullOrWhiteSpace(request.Method))
                        switch (request.Method.ToLower())
                        {
                            case "get":
                                requestHttpMethod = HttpMethod.Get;
                                break;
                            case "delete":
                                requestHttpMethod = HttpMethod.Delete;
                                break;
                            case "head":
                                requestHttpMethod = HttpMethod.Head;
                                break;
                            case "options":
                                requestHttpMethod = HttpMethod.Options;
                                break;
                            case "patch":
                                requestHttpMethod = HttpMethod.Patch;
                                break;
                            case "put":
                                requestHttpMethod = HttpMethod.Put;
                                break;
                            default:
                                requestHttpMethod = HttpMethod.Post;
                                break;

                        }

                    webRequest = new HttpRequestMessage(requestHttpMethod, new Uri(requestUriString));

                    // check specific request ContentType defined, and override service type in that case
                    // check specific request ContentType defined, and override service type in that case
                    if (requestHttpMethod == HttpMethod.Get)
                    {
                        webRequest.RequestUri =
                            new Uri(String.Concat(service.Endpoint.Host, service.Endpoint.Path, request.Content),
                                UriKind.RelativeOrAbsolute);
                    }
                    else
                    {
                        if (webRequest.Content == null && request.Content != null)
                            webRequest.Content = new HttpBufferContent(request.GetRawContent().AsBuffer());
                    }

                    var sContentType = request.ContentType;

                    if (String.IsNullOrWhiteSpace(sContentType))
                    {
                        sContentType = ContentTypes[service.Type];
                    }

                    WindowsPhoneUtils.Log("Request method: " + webRequest.Method);

                    webRequest.Headers.Accept.Add(new HttpMediaTypeWithQualityHeaderValue(sContentType));

                    if (webRequest.Method == HttpMethod.Post && request.Content != null)
                    {
                        webRequest.Content.Headers.ContentLength = (ulong?)request.GetContentLength();
                        WindowsPhoneUtils.Log("Request content length: " + request.GetContentLength());
                    }
                    else
                    {
                        webRequest.Content = new HttpStringContent("");
                    }
                    WindowsPhoneUtils.Log("webRequest content length: " + webRequest.Content.Headers.ContentLength);
                    webRequest.Content.Headers.ContentType = new HttpMediaTypeHeaderValue(sContentType);
                    webRequest.Headers.Add("Keep-Alive", "true");
                }
                if (webRequest == null) return null;
                WindowsPhoneUtils.Log("Request UserAgent : " + IOUserAgent);

                /*************
            * HEADERS HANDLING
            *************/

                // add specific headers to the request
                if (request.Headers != null && request.Headers.Length > 0)
                {
                    foreach (var header in request.Headers)
                    {
                        webRequest.Headers.Add(header.Name, header.Value);
                        WindowsPhoneUtils.Log("Added request header: " + header.Name + "=" +
                                              webRequest.Headers[header.Name]);
                    }
                }

                /*************
            * COOKIES HANDLING
            *************/

                // Assign the cookie container on the request to hold cookie objects that are sent on the response.
                // Required even though you no cookies are send.
                //webReq.CookieContainer = this.cookieContainer;

                // add cookies to the request cookie container
                if (request.Session != null && request.Session.Cookies != null && request.Session.Cookies.Length > 0)
                {
                    foreach (
                        var cookie in request.Session.Cookies.Where(cookie => !String.IsNullOrWhiteSpace(cookie.Name)))
                    {
                        _clientBaseConfig.CookieManager.SetCookie(new HttpCookie(cookie.Name, new Uri(requestUriString).Host, "/") { Value = cookie.Value });
                        WindowsPhoneUtils.Log("Added cookie [" + cookie.Name + "] to request.");
                    }
                }
                WindowsPhoneUtils.Log("HTTP Request cookies: " +
                                      _clientBaseConfig.CookieManager.GetCookies(new Uri(requestUriString)).Count);
            }
            catch (Exception ex)
            {
                WindowsPhoneUtils.Log("INVOKE SERVICE ERROR:" + ex.Message);
            }


            /*************
             * SETTING A PROXY (ENTERPRISE ENVIRONMENTS)
             *************/
            /*
            if (service.Endpoint.ProxyUrl != null)
            {
            WebProxy myProxy = new WebProxy();
            Uri proxyUri = new Uri(service.Endpoint.ProxyUrl);
            myProxy.Address = proxyUri;
            webReq.Proxy = myProxy;
            }
            */
            return webRequest;
        }
Exemplo n.º 11
0
 public override async Task<string> InvokeServiceForBinary(IORequest request, IOService service, string storePath)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 12
0
 public override async Task<IOResponseHandle> InvokeService(IORequest request, IOService service, IOResponseHandler handler)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 13
0
        public override async Task<IOResponse> InvokeService(IORequest request, IOService service)
        {
            var response = new IOResponse();
            var clientBaseConfig = WindowsPhoneUtils.CreateHttpClientOptions(!request.StopAutoRedirect);
            if (service != null)
            {
                if (service.Endpoint == null)
                {
                    WindowsPhoneUtils.Log("No endpoint configured for this service name: " + service.Name);
                    return null;
                }
                WindowsPhoneUtils.Log("Request content: " + request.Content);

                var reqMethod = service.RequestMethod.ToString(); // default is POST
                if (!string.IsNullOrEmpty(request.Method)) reqMethod = request.Method.ToUpper();

                var requestUriString = FormatRequestUriString(request, service, reqMethod);
                HttpRequestMessage webReq = null;
                try
                {
                    webReq = await BuildWebRequest(request, service, requestUriString, reqMethod);
                    using (var client = new HttpClient(clientBaseConfig))
                    {
                        //ONLY DEFINE PROPERTIES ONCE, IF A REQUEST HAS BEEN SENT, HTTPCLIENT CANNOT MODIFY PROPERTIES
                        client.DefaultRequestHeaders.TryAppendWithoutValidation("User-Agent", IOUserAgent);
                        var cts = new CancellationTokenSource(new TimeSpan(0, 0, DEFAULT_RESPONSE_TIMEOUT));
                        var webResp = await client.SendRequestAsync(webReq).AsTask(cts.Token);
                        WindowsPhoneUtils.Log("getting response... ");
                        response = await ReadWebResponse(webReq, webResp, service);
                    }
                }
                catch (Exception ex)
                {
                    //Certificate errors
                    if ((ex.HResult & 65535) == 12045)
                    {
                        if (webReq != null)
                        {
                            var certErrors = webReq.TransportInformation.ServerCertificateErrors;
                        }
                    }
                    WindowsPhoneUtils.Log("Exception requesting service: " + requestUriString + "." + ex.Message);
                    response.ContentType = ContentTypes[ServiceType.REST_JSON];
                    response.Content = "Exception Requesting Service: " + requestUriString + ". Message: " + ex.Message;
                }
            }
            else
            {
                WindowsPhoneUtils.Log("Null service received for invoking.");
            }
            return response;
        }
Exemplo n.º 14
0
        /*
        private static Stream GetStreamForResponse(HttpWebResponse webResponse)
        {
            Stream stream;
            switch (webResponse.ContentEncoding.ToUpperInvariant())
            {
                case "GZIP":
                    stream = new GZipStream(webResponse.GetResponseStream(), CompressionMode.Decompress);
                    break;
                case "DEFLATE":
                    stream = new DeflateStream(webResponse.GetResponseStream(), CompressionMode.Decompress);
                    break;

                default:
                    stream = webResponse.GetResponseStream();
                    //stream.ReadTimeout = readTimeOut;
                    break;
            }
            return stream;
        }
        */

		private IOResponse ReadWebResponse(HttpWebRequest webRequest, HttpWebResponse webResponse, IOService service) {
			IOResponse response = new IOResponse ();
            
            
			// result types (string or byte array)
			byte[] resultBinary = null;
			string result = null;
            
			string responseMimeTypeOverride = webResponse.GetResponseHeader ("Content-Type");
            
			using (Stream stream = webResponse.GetResponseStream()) {
				SystemLogger.Log (SystemLogger.Module.CORE, "getting response stream...");
				if (ServiceType.OCTET_BINARY.Equals (service.Type)) {
                    
					int lengthContent = -1;
					if (webResponse.GetResponseHeader ("Content-Length") != null && webResponse.GetResponseHeader ("Content-Length") != "") {
						lengthContent = Int32.Parse (webResponse.GetResponseHeader ("Content-Length"));
					}
					// testing log line
					// SystemLogger.Log (SystemLogger.Module.CORE, "content-length header: " + lengthContent +", max file size: " + MAX_BINARY_SIZE);
					int bufferReadSize = DEFAULT_BUFFER_READ_SIZE;
					if (lengthContent >= 0 && lengthContent<=bufferReadSize) {
						bufferReadSize = lengthContent;
					}
                    
					if(lengthContent>MAX_BINARY_SIZE) {
						SystemLogger.Log (SystemLogger.Module.CORE, 
						                  "WARNING! - file exceeds the maximum size defined in platform (" + MAX_BINARY_SIZE+ " bytes)");
					} else {
						// Read to end of stream in blocks
						SystemLogger.Log (SystemLogger.Module.CORE, "buffer read: " + bufferReadSize + " bytes");
						MemoryStream memBuffer = new MemoryStream ();
						byte[] readBuffer = new byte[bufferReadSize];
						int readLen = 0;
						do {
							readLen = stream.Read (readBuffer, 0, readBuffer.Length);
							memBuffer.Write (readBuffer, 0, readLen);
						} while (readLen >0);
						
						resultBinary = memBuffer.ToArray ();
						memBuffer.Close ();
						memBuffer = null;
					}
				} else {
					SystemLogger.Log (SystemLogger.Module.CORE, "reading response content...");
					using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
						result = reader.ReadToEnd ();
					}
				}

			}

			/*************
			 * CACHE
			 *************/

			// preserve cache-control header from remote server, if any
            /*
			string cacheControlHeader = webResponse.GetResponseHeader ("Cache-Control");
			if (cacheControlHeader != null && cacheControlHeader != "") {
				SystemLogger.Log (SystemLogger.Module.CORE, "Found Cache-Control header on response: " + cacheControlHeader + ", using it on internal response...");
				if(response.Headers == null) {
					response.Headers = new IOHeader[1];
				}
				IOHeader cacheHeader = new IOHeader();
				cacheHeader.Name = "Cache-Control";
				cacheHeader.Value = cacheControlHeader;
				response.Headers[0] = cacheHeader;
			}
             */

            
            /*************
			 * HEADERS HANDLING
			 *************/
            if (webResponse.Headers != null)
            {   
                response.Headers = new IOHeader[webResponse.Headers.Count];
                
                int size = 0;
                foreach(string headerKey in webResponse.Headers.AllKeys) {
                    string headerValue = webResponse.GetResponseHeader(headerKey);
                    IOHeader objHeader = new IOHeader();
				    objHeader.Name = headerKey;
				    objHeader.Value = headerValue;
                    SystemLogger.Log(SystemLogger.Module.CORE, "Found Header on response: " + headerKey + "=" + headerValue);
                    response.Headers[size++] = objHeader;
                }
            }

			/*************
			 * COOKIES HANDLING
			 *************/

			// get response cookies (stored on cookiecontainer)
			if (response.Session == null) {
				response.Session = new IOSessionContext ();
				
			}
            
			response.Session.Cookies = new IOCookie[this.cookieContainer.Count];
			IEnumerator enumerator = this.cookieContainer.GetCookies (webRequest.RequestUri).GetEnumerator ();
			int i = 0;
			while (enumerator.MoveNext()) {
				Cookie cookieFound = (Cookie)enumerator.Current;
				SystemLogger.Log (SystemLogger.Module.CORE, "Found cookie on response: " + cookieFound.Name + "=" + cookieFound.Value);
				IOCookie cookie = new IOCookie ();
				cookie.Name = cookieFound.Name;
				cookie.Value = cookieFound.Value;
				response.Session.Cookies [i] = cookie;
				i++;
			}

			if (ServiceType.OCTET_BINARY.Equals (service.Type)) {
				if (responseMimeTypeOverride != null && !responseMimeTypeOverride.Equals (contentTypes [service.Type])) {
					response.ContentType = responseMimeTypeOverride;
				} else {
					response.ContentType = contentTypes [service.Type];
				}
				response.ContentBinary = resultBinary; // Assign binary content here
			} else {
				response.ContentType = contentTypes [service.Type];
				response.Content = result;
			}

            
			return response;

		}
Exemplo n.º 15
0
        private HttpWebRequest BuildWebRequest(IORequest request, IOService service, string requestUriString, string reqMethod)
        {
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(requestUriString);

            webReq.Method      = reqMethod;        // default is POST
            webReq.ContentType = contentTypes [service.Type];

            // check specific request ContentType defined, and override service type in that case
            if (request.ContentType != null && request.ContentType.Length > 0)
            {
                webReq.ContentType = request.ContentType;
            }

            SystemLogger.Log(SystemLogger.Module.CORE, "Request content type: " + webReq.ContentType);
            SystemLogger.Log(SystemLogger.Module.CORE, "Request method: " + webReq.Method);

            webReq.Accept        = webReq.ContentType;      // setting "Accept" header with the same value as "Content Type" header, it is needed to be defined for some services.
            webReq.ContentLength = request.GetContentLength();
            SystemLogger.Log(SystemLogger.Module.CORE, "Request content length: " + webReq.ContentLength);
            webReq.Timeout          = DEFAULT_RESPONSE_TIMEOUT;    // in millisecods (default is 100 seconds)
            webReq.ReadWriteTimeout = DEFAULT_READWRITE_TIMEOUT;   // in milliseconds
            webReq.KeepAlive        = false;
            webReq.ProtocolVersion  = HttpVersion.Version10;
            if (request.ProtocolVersion == HTTPProtocolVersion.HTTP11)
            {
                webReq.ProtocolVersion = HttpVersion.Version11;
            }


            webReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            // user agent needs to be informed - some servers check this parameter and send 500 errors when not informed.
            webReq.UserAgent = this.IOUserAgent;
            SystemLogger.Log(SystemLogger.Module.CORE, "Request UserAgent : " + webReq.UserAgent);

            /*************
            * HEADERS HANDLING
            *************/

            // add specific headers to the request
            if (request.Headers != null && request.Headers.Length > 0)
            {
                foreach (IOHeader header in request.Headers)
                {
                    webReq.Headers.Add(header.Name, header.Value);
                    SystemLogger.Log(SystemLogger.Module.CORE, "Added request header: " + header.Name + "=" + webReq.Headers.Get(header.Name));
                }
            }

            /*************
            * COOKIES HANDLING
            *************/

            // Assign the cookie container on the request to hold cookie objects that are sent on the response.
            // Required even though you no cookies are send.
            webReq.CookieContainer = this.cookieContainer;

            // add cookies to the request cookie container
            if (request.Session != null && request.Session.Cookies != null && request.Session.Cookies.Length > 0)
            {
                foreach (IOCookie cookie in request.Session.Cookies)
                {
                    if (cookie != null && cookie.Name != null)
                    {
                        webReq.CookieContainer.Add(webReq.RequestUri, new Cookie(cookie.Name, cookie.Value));
                        SystemLogger.Log(SystemLogger.Module.CORE, "Added cookie [" + cookie.Name + "] to request.");
                    }
                }
            }
            SystemLogger.Log(SystemLogger.Module.CORE, "HTTP Request cookies: " + webReq.CookieContainer.GetCookieHeader(webReq.RequestUri));

            /*************
            * SETTING A PROXY (ENTERPRISE ENVIRONMENTS)
            *************/

            if (service.Endpoint.ProxyUrl != null)
            {
                WebProxy myProxy  = new WebProxy();
                Uri      proxyUri = new Uri(service.Endpoint.ProxyUrl);
                myProxy.Address = proxyUri;
                webReq.Proxy    = myProxy;
            }

            return(webReq);
        }
Exemplo n.º 16
0
		private string ReadWebResponseAndStore(HttpWebRequest webRequest, HttpWebResponse webResponse, IOService service, string storePath) {

			using (Stream stream = webResponse.GetResponseStream()) {
				SystemLogger.Log (SystemLogger.Module.CORE, "getting response stream...");

				int lengthContent = -1;
				if (webResponse.GetResponseHeader ("Content-Length") != null && webResponse.GetResponseHeader ("Content-Length") != "") {
					lengthContent = Int32.Parse (webResponse.GetResponseHeader ("Content-Length"));
				}
				// testing log line
				// SystemLogger.Log (SystemLogger.Module.CORE, "content-length header: " + lengthContent +", max file size: " + MAX_BINARY_SIZE);
				int bufferReadSize = DEFAULT_BUFFER_READ_SIZE;
				if (lengthContent >= 0 && lengthContent<=bufferReadSize) {
					bufferReadSize = lengthContent;
				}
				SystemLogger.Log (SystemLogger.Module.CORE, "buffer read: " + bufferReadSize + " bytes");
				string fullStorePath = Path.Combine(this.GetDirectoryRoot (), storePath);
				SystemLogger.Log (SystemLogger.Module.CORE, "storing file at: " + fullStorePath);
				FileStream streamWriter = new FileStream (fullStorePath, FileMode.Create);

				byte[] readBuffer = new byte[bufferReadSize];
				int readLen = 0;
				int totalRead = 0;
				do {
					readLen = stream.Read (readBuffer, 0, readBuffer.Length);
					streamWriter.Write (readBuffer, 0, readLen);
					totalRead = totalRead + readLen;
				} while (readLen >0);


				SystemLogger.Log (SystemLogger.Module.CORE, "total bytes: " + totalRead);
				streamWriter.Close ();
				streamWriter = null;

				return storePath;
			}
		}
Exemplo n.º 17
0
        private IOResponse ReadWebResponse(HttpWebRequest webRequest, HttpWebResponse webResponse, IOService service)
        {
            IOResponse response = new IOResponse();

            // result types (string or byte array)
            byte[] resultBinary = null;
            string result       = null;

            string responseMimeTypeOverride = webResponse.GetResponseHeader("Content-Type");

            using (Stream stream = webResponse.GetResponseStream()) {
                SystemLogger.Log(SystemLogger.Module.CORE, "getting response stream...");
                if (ServiceType.OCTET_BINARY.Equals(service.Type))
                {
                    int lengthContent = -1;
                    if (webResponse.GetResponseHeader("Content-Length") != null && webResponse.GetResponseHeader("Content-Length") != "")
                    {
                        lengthContent = Int32.Parse(webResponse.GetResponseHeader("Content-Length"));
                    }
                    // testing log line
                    // SystemLogger.Log (SystemLogger.Module.CORE, "content-length header: " + lengthContent +", max file size: " + MAX_BINARY_SIZE);
                    int bufferReadSize = DEFAULT_BUFFER_READ_SIZE;
                    if (lengthContent >= 0 && lengthContent <= bufferReadSize)
                    {
                        bufferReadSize = lengthContent;
                    }

                    if (lengthContent > MAX_BINARY_SIZE)
                    {
                        SystemLogger.Log(SystemLogger.Module.CORE,
                                         "WARNING! - file exceeds the maximum size defined in platform (" + MAX_BINARY_SIZE + " bytes)");
                    }
                    else
                    {
                        // Read to end of stream in blocks
                        SystemLogger.Log(SystemLogger.Module.CORE, "buffer read: " + bufferReadSize + " bytes");
                        MemoryStream memBuffer  = new MemoryStream();
                        byte[]       readBuffer = new byte[bufferReadSize];
                        int          readLen    = 0;
                        do
                        {
                            readLen = stream.Read(readBuffer, 0, readBuffer.Length);
                            memBuffer.Write(readBuffer, 0, readLen);
                        } while (readLen > 0);

                        resultBinary = memBuffer.ToArray();
                        memBuffer.Close();
                        memBuffer = null;
                    }
                }
                else
                {
                    SystemLogger.Log(SystemLogger.Module.CORE, "reading response content...");
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
                        result = reader.ReadToEnd();
                    }
                }
            }

            /*************
            * CACHE
            *************/

            // preserve cache-control header from remote server, if any
            string cacheControlHeader = webResponse.GetResponseHeader("Cache-Control");

            if (cacheControlHeader != null && cacheControlHeader != "")
            {
                SystemLogger.Log(SystemLogger.Module.CORE, "Found Cache-Control header on response: " + cacheControlHeader + ", using it on internal response...");
                if (response.Headers == null)
                {
                    response.Headers = new IOHeader[1];
                }
                IOHeader cacheHeader = new IOHeader();
                cacheHeader.Name    = "Cache-Control";
                cacheHeader.Value   = cacheControlHeader;
                response.Headers[0] = cacheHeader;
            }

            /*************
            * COOKIES HANDLING
            *************/

            // get response cookies (stored on cookiecontainer)
            if (response.Session == null)
            {
                response.Session = new IOSessionContext();
            }
            response.Session.Cookies = new IOCookie[this.cookieContainer.Count];
            IEnumerator enumerator = this.cookieContainer.GetCookies(webRequest.RequestUri).GetEnumerator();
            int         i          = 0;

            while (enumerator.MoveNext())
            {
                Cookie cookieFound = (Cookie)enumerator.Current;
                SystemLogger.Log(SystemLogger.Module.CORE, "Found cookie on response: " + cookieFound.Name + "=" + cookieFound.Value);
                IOCookie cookie = new IOCookie();
                cookie.Name  = cookieFound.Name;
                cookie.Value = cookieFound.Value;
                response.Session.Cookies [i] = cookie;
                i++;
            }

            if (ServiceType.OCTET_BINARY.Equals(service.Type))
            {
                if (responseMimeTypeOverride != null && !responseMimeTypeOverride.Equals(contentTypes [service.Type]))
                {
                    response.ContentType = responseMimeTypeOverride;
                }
                else
                {
                    response.ContentType = contentTypes [service.Type];
                }
                response.ContentBinary = resultBinary;                 // Assign binary content here
            }
            else
            {
                response.ContentType = contentTypes [service.Type];
                response.Content     = result;
            }


            return(response);
        }
Exemplo n.º 18
0
		public IOResponseHandle InvokeService (IORequest request, IOService service, IOResponseHandler handler)
		{
			throw new NotImplementedException ();
		}
Exemplo n.º 19
0
        private string ReadWebResponseAndStore(HttpWebRequest webRequest, HttpWebResponse webResponse, IOService service, string storePath)
        {
            using (Stream stream = webResponse.GetResponseStream()) {
                SystemLogger.Log(SystemLogger.Module.CORE, "getting response stream...");

                int lengthContent = -1;
                if (webResponse.GetResponseHeader("Content-Length") != null && webResponse.GetResponseHeader("Content-Length") != "")
                {
                    lengthContent = Int32.Parse(webResponse.GetResponseHeader("Content-Length"));
                }
                // testing log line
                // SystemLogger.Log (SystemLogger.Module.CORE, "content-length header: " + lengthContent +", max file size: " + MAX_BINARY_SIZE);
                int bufferReadSize = DEFAULT_BUFFER_READ_SIZE;
                if (lengthContent >= 0 && lengthContent <= bufferReadSize)
                {
                    bufferReadSize = lengthContent;
                }
                SystemLogger.Log(SystemLogger.Module.CORE, "buffer read: " + bufferReadSize + " bytes");
                string fullStorePath = Path.Combine(this.GetDirectoryRoot(), storePath);
                SystemLogger.Log(SystemLogger.Module.CORE, "storing file at: " + fullStorePath);
                FileStream streamWriter = new FileStream(fullStorePath, FileMode.Create);

                byte[] readBuffer = new byte[bufferReadSize];
                int    readLen    = 0;
                int    totalRead  = 0;
                do
                {
                    readLen = stream.Read(readBuffer, 0, readBuffer.Length);
                    streamWriter.Write(readBuffer, 0, readLen);
                    totalRead = totalRead + readLen;
                } while (readLen > 0);


                SystemLogger.Log(SystemLogger.Module.CORE, "total bytes: " + totalRead);
                streamWriter.Close();
                streamWriter = null;

                return(storePath);
            }
        }
Exemplo n.º 20
0
 public abstract Task<IOResponseHandle> InvokeService(IORequest request, IOService service, IOResponseHandler handler);
Exemplo n.º 21
0
		/// <summary>
		/// Method overrided, to start activity notification while invoking external service. 
		/// </summary>
		/// <param name="request">
		/// A <see cref="IORequest"/>
		/// </param>
		/// <param name="service">
		/// A <see cref="IOService"/>
		/// </param>
		/// <returns>
		/// A <see cref="IOResponse"/>
		/// </returns>
		public override IOResponse InvokeService (IORequest request, IOService service)
		{

			this.IOUserAgent = IPhoneUtils.GetInstance().GetUserAgent();
			INotification notificationService = (INotification)IPhoneServiceLocator.GetInstance().GetService("notify");
			try { 
				notificationService.StartNotifyActivity();
			} catch(Exception e) {
				SystemLogger.Log(SystemLogger.Module.PLATFORM, "Cannot StartNotifyActivity. Message: " + e.Message);
			}
			IOResponse response = base.InvokeService (request, service);
			
			try { 
				notificationService.StopNotifyActivity();
			} catch(Exception e) {
				SystemLogger.Log(SystemLogger.Module.PLATFORM, "Cannot StopNotifyActivity. Message: " + e.Message);
			}
			
			return response;
    	}
Exemplo n.º 22
0
        /// <summary>
        /// Gets the service from URL.
        /// </summary>
        /// <returns>The service from URL.</returns>
        /// <param name="url">URL.</param>
        public virtual IOService GetServiceFromUrl(String url)
        {
            IOService service = new IOService();
            service.Name = "updateModule";
            service.Endpoint = new IOServiceEndpoint();
            service.Endpoint.Host = url;
            service.Endpoint.Port = 0;
            service.Endpoint.Path = "";
            service.RequestMethod = RequestMethod.GET;
            service.Type = ServiceType.OCTET_BINARY;

            return service;
        }
Exemplo n.º 23
0
        private HttpWebRequest BuildWebRequest(IORequest request, IOService service, string requestUriString, string reqMethod)
        {
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create (requestUriString);
            webReq.Method = reqMethod; // default is POST
            webReq.ContentType = contentTypes [service.Type];

                    // check specific request ContentType defined, and override service type in that case
                    if (request.ContentType != null && request.ContentType.Length > 0) {
                webReq.ContentType = request.ContentType;
                    }

            SystemLogger.Log (SystemLogger.Module.CORE, "Request content type: " + webReq.ContentType);
            SystemLogger.Log (SystemLogger.Module.CORE, "Request method: " + webReq.Method);

            webReq.Accept = webReq.ContentType; // setting "Accept" header with the same value as "Content Type" header, it is needed to be defined for some services.
            webReq.ContentLength = request.GetContentLength ();
            SystemLogger.Log (SystemLogger.Module.CORE, "Request content length: " + webReq.ContentLength);
            webReq.Timeout = DEFAULT_RESPONSE_TIMEOUT; // in millisecods (default is 100 seconds)
            webReq.ReadWriteTimeout = DEFAULT_READWRITE_TIMEOUT; // in milliseconds
            webReq.KeepAlive = false;
            webReq.ProtocolVersion = HttpVersion.Version10;
            if (request.ProtocolVersion == HTTPProtocolVersion.HTTP11) webReq.ProtocolVersion = HttpVersion.Version11;

                    // user agent needs to be informed - some servers check this parameter and send 500 errors when not informed.
            webReq.UserAgent = this.IOUserAgent;
            SystemLogger.Log (SystemLogger.Module.CORE, "Request UserAgent : " + webReq.UserAgent);

            /*************
             * HEADERS HANDLING
             *************/

                    // add specific headers to the request
                    if (request.Headers != null && request.Headers.Length > 0) {
                        foreach (IOHeader header in request.Headers) {
                    webReq.Headers.Add (header.Name, header.Value);
                    SystemLogger.Log (SystemLogger.Module.CORE, "Added request header: " + header.Name + "=" + webReq.Headers.Get (header.Name));
                        }
                    }

            /*************
             * COOKIES HANDLING
             *************/

                    // Assign the cookie container on the request to hold cookie objects that are sent on the response.
                    // Required even though you no cookies are send.
            webReq.CookieContainer = this.cookieContainer;

                    // add cookies to the request cookie container
                    if (request.Session != null && request.Session.Cookies != null && request.Session.Cookies.Length > 0) {
                        foreach (IOCookie cookie in request.Session.Cookies) {
                    webReq.CookieContainer.Add (webReq.RequestUri, new Cookie (cookie.Name, cookie.Value));
                            SystemLogger.Log (SystemLogger.Module.CORE, "Added cookie [" + cookie.Name + "] to request.");
                        }
                    }
            SystemLogger.Log (SystemLogger.Module.CORE, "HTTP Request cookies: " + webReq.CookieContainer.GetCookieHeader (webReq.RequestUri));

            /*************
             * SETTING A PROXY (ENTERPRISE ENVIRONMENTS)
             *************/

                    if (service.Endpoint.ProxyUrl != null) {
                        WebProxy myProxy = new WebProxy ();
                        Uri proxyUri = new Uri (service.Endpoint.ProxyUrl);
                        myProxy.Address = proxyUri;
                webReq.Proxy = myProxy;
                    }

            return webReq;
        }