コード例 #1
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;
		}
コード例 #2
0
ファイル: AbstractIO.cs プロジェクト: thomascLM/appverse-core
        /// <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);
        }
コード例 #3
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;
        }
コード例 #4
0
ファイル: AbstractIO.cs プロジェクト: lsp1357/appverse-mobile
        /// <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)
                    {
                        // 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);
        }
コード例 #5
0
ファイル: AbstractIO.cs プロジェクト: thomascLM/appverse-core
        /// <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;
        }