Inheritance: Unity.Core.IO.IOHeaders
Example #1
0
        private string FormatRequestUriString(IORequest request, IOService service, string reqMethod)
        {
            string requestUriString = String.Format("{0}:{1}{2}", service.Endpoint.Host, service.Endpoint.Port, service.Endpoint.Path);

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

            if (reqMethod.Equals(RequestMethod.GET.ToString()) && request.Content != null)
            {
                // add request content to the URI string when NOT POST method (GET, PUT, DELETE).
                requestUriString += request.Content;
            }

            SystemLogger.Log(SystemLogger.Module.CORE, "Requesting service: " + requestUriString);
            return(requestUriString);
        }
        public bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            SystemLogger.Log (SystemLogger.Module .CORE, " ############## " + this.GetType () + " -> " + request.Url);
            if (request.Url.StartsWith (REMOTE_RESOURCE_URI)) {
                SystemLogger.Log (SystemLogger.Module .CORE, "Remote resource protocol.");
                try {
                    string commandParams = request.Url.Substring (REMOTE_RESOURCE_URI.Length);
                    string[] commandParamsArray = commandParams.Split (new char[] { '/' });
                    if (commandParamsArray.Length > 0) {
                        string ioServiceName = commandParamsArray [0];

                        Object unityIOService = serviceLocator.GetService (UNITY_IO_SERVICE_NAME);
                        if (unityIOService != null && ioServiceName != null) {
                            IIo io = (IIo)unityIOService;
                            string parameters = commandParams.Substring (ioServiceName.Length + 1);

                            IORequest ioRequest = new IORequest ();
                            ioRequest.Content = parameters;
                            IOResponse ioResponse = io.InvokeService (ioRequest, ioServiceName);
                            if (ioResponse != null) {
                                response.ContentType = ioResponse.ContentType;
                                response.RawContent = ioResponse.ContentBinary;
                            }
                        }
                    }

                    if (response.RawContent == null) {
                        response.Content = "No content available.";
                        SystemLogger.Log (SystemLogger.Module .CORE, "No content available for request [" + request.Url + "," + request.Method + "]. Continue to next handler...");
                        return false;
                    }

                    return true;
                } catch (Exception e) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "Exception when parsing request [" + request.Url + "]", e);
                    response.Content = "Malformed request.";
                    return false;
                }
            } else {
                SystemLogger.Log (SystemLogger.Module .CORE, "Non remote resource protocol. Continue to next handler...");
                return false;
            }
        }
Example #3
0
 public abstract Task<string> InvokeServiceForBinary(IORequest request, IOService service, string storePath);
Example #4
0
 public abstract Task<IOResponse> InvokeService(IORequest request, IOService service);
Example #5
0
 public abstract Task<IOResponseHandle> InvokeService(IORequest request, IOService service, IOResponseHandler handler);
Example #6
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;
		}
Example #7
0
		public IOResponseHandle InvokeService (IORequest request, IOService service, IOResponseHandler handler)
		{
			throw new NotImplementedException ();
		}
Example #8
0
 public IOResponseHandle InvokeService(IORequest request, string serviceName, ServiceType type, IOResponseHandler handler)
 {
     throw new NotImplementedException();
 }
Example #9
0
        private HttpWebRequest BuildMultipartWebRequest(HttpWebRequest webReq, IORequest request, IOService service, string requestUriString)
        {
            webReq.Method = "POST";
            webReq.KeepAlive = true;
            SystemLogger.Log(SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. Request method fixed to 'POST' (only this is allowed for a form-data), and KeepAlive true");
            
            string boundary = CreateFormDataBoundary();
            webReq.ContentType = contentTypes[service.Type] + boundary;
            SystemLogger.Log(SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. Adding boundary to content-type: " + webReq.ContentType);
            // KO in some servers if Accept header is filled 
            //webReq.Accept = contentTypes[service.Type]; // setting "Accept" header with the same value as "Content Type" header, it is needed to be defined for some services.

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

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

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

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

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

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

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

            return webReq;
        }
Example #10
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;
        }
Example #11
0
 /// <summary>
 /// Invokes service, given its name and type, using the provided request.
 /// </summary>
 /// <param name="request">IO request.</param>
 /// <param name="serviceName"></param>
 /// <param name="type"></param>
 /// <returns>IO response.</returns>
 public IOResponse InvokeService(IORequest request, string serviceName, ServiceType type)
 {
     return(InvokeService(request, GetService(serviceName, type)));
 }
        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;
        }
        private async Task<HttpRequestMessage> BuildMultipartWebRequest(IORequest request, IOService service, string requestUriString)
        {

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

            if (request.Content != null)
            {
                var items = request.Content.TrimEnd('&').Split('&');
                foreach (var keyValue in items.Select(item => item.Split('=')))
                {
                    multipartFormDataContent.Add(new HttpStringContent(keyValue[1]), keyValue[0]);
                }
            }
            webRequest.Content = multipartFormDataContent;
            if (request.Attachment == null) return webRequest;
            foreach (var attachData in request.Attachment)
            {
                try
                {
                    if (!String.IsNullOrWhiteSpace(attachData.ReferenceUrl))
                    {
                        var attachmentFile = await WindowsPhoneUtils.GetFileFromReferenceURL(attachData.ReferenceUrl);
                        if (attachmentFile != null)
                        {
                            multipartFormDataContent.Add(new HttpStreamContent(await attachmentFile.OpenReadAsync()), attachData.FormFieldKey, attachData.FileName ?? attachmentFile.Name);
                        }
                        else
                        {
                            WindowsPhoneUtils.Log("**** [MULTIPART_FORM_DATA]. # File from referenced URL: " + attachData.ReferenceUrl + ", does not exists in filesystem, please check provided ReferenceUrl!");
                        }
                    }
                    else
                    {
                        WindowsPhoneUtils.Log("**** [MULTIPART_FORM_DATA]. # Attached file does not contain a valid ReferenceUrl field. IGNORED");
                    }
                }
                catch (Exception ex)
                {
                    WindowsPhoneUtils.Log(ex.Message);
                }
            }
            return webRequest;
        }
 public override async Task<string> InvokeServiceForBinary(IORequest request, IOService service, string storePath)
 {
     throw new NotImplementedException();
 }
 public override async Task<IOResponseHandle> InvokeService(IORequest request, string serviceName, ServiceType type, IOResponseHandler handler)
 {
     throw new NotImplementedException();
 }
 public override async Task<IOResponseHandle> InvokeService(IORequest request, IOService service, IOResponseHandler handler)
 {
     throw new NotImplementedException();
 }
 public override async Task<IOResponse> InvokeService(IORequest request, string serviceName, ServiceType type)
 {
     return await InvokeService(request, await GetService(serviceName, type));
 }
        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;
        }
Example #19
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);
        }
Example #20
0
        private HttpWebRequest BuildWebRequest(IORequest request, IOService service, string requestUriString, string reqMethod)
        {
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(requestUriString);

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

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

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

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

            // [MOBPLAT-200] ... Allow Gzip or Deflate decompression methods
            webReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

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

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

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

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

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

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

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

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

            return(webReq);
        }
Example #21
0
 public IOResponseHandle InvokeService(IORequest request, IOService service, IOResponseHandler handler)
 {
     throw new NotImplementedException();
 }
Example #22
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)
                    {
                        // 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);
        }
Example #23
0
		private string FormatRequestUriString(IORequest request, IOService service, string reqMethod) {

			string requestUriString = String.Format ("{0}:{1}{2}", service.Endpoint.Host, service.Endpoint.Port, service.Endpoint.Path);
			if (service.Endpoint.Port == 0) 
			{
				requestUriString = String.Format ("{0}{1}", service.Endpoint.Host, service.Endpoint.Path);
			}
			
			if (reqMethod.Equals(RequestMethod.GET.ToString()) && request.Content != null)
			{
				// add request content to the URI string when NOT POST method (GET, PUT, DELETE).
				requestUriString += request.Content;
			}
			
			SystemLogger.Log (SystemLogger.Module .CORE, "Requesting service: " + requestUriString);
			return requestUriString;
		}
Example #24
0
 public abstract Task <IOResponse> InvokeService(IORequest request, IOService service);
Example #25
0
        private HttpWebRequest BuildWebRequest(IORequest request, IOService service, string requestUriString, string reqMethod) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			return webReq;
		}
Example #26
0
 public abstract Task <IOResponse> InvokeService(IORequest request, string serviceName, ServiceType type);
Example #27
0
		/// <summary>
		/// Invokes service, given its name and type, using the provided request.
		/// </summary>
		/// <param name="request">IO request.</param>
		/// <param name="serviceName"></param>
		/// <param name="type"></param>
		/// <returns>IO response.</returns>
		public IOResponse InvokeService (IORequest request, string serviceName, ServiceType type)
		{
			return InvokeService (request, GetService (serviceName, type));
		}
Example #28
0
 public abstract Task <IOResponseHandle> InvokeService(IORequest request, IOService service, IOResponseHandler handler);
Example #29
0
		public IOResponseHandle InvokeService (IORequest request, string serviceName, ServiceType type, IOResponseHandler handler)
		{
			throw new NotImplementedException ();
		}
Example #30
0
 public abstract Task <IOResponseHandle> InvokeService(IORequest request, string serviceName, ServiceType type, IOResponseHandler handler);
Example #31
0
 public abstract Task<IOResponse> InvokeService(IORequest request, string serviceName, ServiceType type);
Example #32
0
 public abstract Task <string> InvokeServiceForBinary(IORequest request, IOService service, string storePath);
Example #33
0
 public abstract Task<IOResponseHandle> InvokeService(IORequest request, string serviceName, ServiceType type, IOResponseHandler handler);
Example #34
0
		/// <summary>
		/// Method overrided, to start activity notification while invoking external service. 
		/// </summary>
		/// <param name="request">
		/// A <see cref="IORequest"/>
		/// </param>
		/// <param name="service">
		/// A <see cref="IOService"/>
		/// </param>
		/// <returns>
		/// A <see cref="IOResponse"/>
		/// </returns>
		public override IOResponse InvokeService (IORequest request, IOService service)
		{

			this.IOUserAgent = IPhoneUtils.GetInstance().GetUserAgent();
			INotification notificationService = (INotification)IPhoneServiceLocator.GetInstance().GetService("notify");
			try { 
				notificationService.StartNotifyActivity();
			} catch(Exception e) {
				SystemLogger.Log(SystemLogger.Module.PLATFORM, "Cannot StartNotifyActivity. Message: " + e.Message);
			}
			IOResponse response = base.InvokeService (request, service);
			
			try { 
				notificationService.StopNotifyActivity();
			} catch(Exception e) {
				SystemLogger.Log(SystemLogger.Module.PLATFORM, "Cannot StopNotifyActivity. Message: " + e.Message);
			}
			
			return response;
    	}
Example #35
0
        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 #36
0
        private HttpWebRequest BuildWebRequest(IORequest request, IOService service, string requestUriString, string reqMethod)
        {
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create (requestUriString);
            webReq.Method = reqMethod; // default is POST
            webReq.ContentType = contentTypes [service.Type];

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

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

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

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

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

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

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

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

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

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

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

            return webReq;
        }