public virtual IORequest GetRequestWithRequiredHeaders()
        {
            IORequest request = new IORequest();

            if(_context != null && _context.Credentials!=null && _context.Credentials.Length>0) {
                // Basic Authentication available
                // Credentials should be a base64 encoding for the "username:password" concatenation string
                // TODO  allow other authentication types in the future
                IOHeader authHeader = new IOHeader ();
                authHeader.Name	= "Authorization";
                authHeader.Value = "Basic " + _context.Credentials;

                request.Headers = new IOHeader[] { authHeader };

            }

            // Accept header is needed to avoid "406 not acceptable" error, but should be set in the request final object
            // I/O Services use the request content type to set this value on the final request object
            request.ContentType = "*/*";

            return request;
        }
Example #2
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);
        }
Example #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;

		}
        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;
        }