Esempio n. 1
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) {

				if (service.Endpoint == null) {
					SystemLogger.Log (SystemLogger.Module .CORE, "No endpoint configured for this service name: " + service.Name);
					return response;
				}
                SystemLogger.Log(SystemLogger.Module.CORE, "Endpoint: " + service.Endpoint.Host+service.Endpoint.Path);
				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...");
                        response = this.ReadWebResponse(webReq, webResp, service);
                    }

				} 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;
				} 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 response;
		}
Esempio n. 2
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);
        }
Esempio n. 3
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;

		}
Esempio n. 4
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)
            {
                if (service.Endpoint == null)
                {
                    SystemLogger.Log(SystemLogger.Module.CORE, "No endpoint configured for this service name: " + service.Name);
                    return(response);
                }

                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)
                    {
                        // 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...");
                        response = this.ReadWebResponse(webReq, webResp, service);
                    }
                } 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;
                } 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(response);
        }
Esempio n. 5
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;
            }

            /*************
            * 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);
        }
Esempio n. 6
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;
        }
Esempio n. 7
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;
        }
Esempio n. 8
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;
        }