示例#1
0
        private async void EvaluateResponse(HttpResponseMessage apiResponse, Exception apiEx)
        {
            var response = await Response.FromWebResponse(this, apiResponse, apiEx);

            // post (async) callback back to the main/UI thread
            // Unity: SynchronizationContext doesn't do anything
            //        use the Dispatcher
#if !UNITY
            _sync.Post(delegate {
                _callback(response);
                IsCompleted = true;
                _callback   = null;
#if NETFX_CORE
                if (null != _request)
                {
                    _request.Dispose();
                    _request = null;
                }
#endif
            }, null);
#else
            UnityToolbag.Dispatcher.InvokeAsync(() => {
                _callback(response);
                IsCompleted = true;
                _callback   = null;
#if NETFX_CORE
                if (null != _request)
                {
                    _request.Dispose();
                    _request = null;
                }
#endif
            });
#endif
        }
示例#2
0
        static void SendFridgeReport()
        {
            // Generate egg positions
            string eggPositions = ((eggReader0.Read() == true) ? "1" : "0") + ","
                                  + ((eggReader1.Read() == true) ? "1" : "0") + ","
                                  + ((eggReader2.Read() == true) ? "1" : "0") + ","
                                  + ((eggReader3.Read() == true) ? "1" : "0") + ","
                                  + ((eggReader4.Read() == true) ? "1" : "0") + ","
                                  + ((eggReader5.Read() == true) ? "1" : "0");

            // Read weights
            //double weightReader0 = 0.745;
            //double weightReader1 = 0.00000;

            weights[0] = CalculateWeight(weightReader0.Read());
            weights[1] = CalculateWeight(weightReader1.Read());


#if CreatingJson
            JsonObject jo = new JsonObject();

            jo.Add("eggs", eggPositions);
            jo.Add("fridgeid", fridgeId.ToString());
            jo.Add("slot1weight", weights[0].ToString());
            jo.Add("slot2weight", weights[1].ToString());

            Debug.Print(jo.ToString());
#endif

#if SendingToSparkfun
            // https://data.sparkfun.com/input/*********
            try
            {
                byte[] postData = Encoding.UTF8.GetBytes(jo.ToString());

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://data.sparkfun.com/input/********");
                request.Method = "POST";
                request.Headers.Add("Phant-Private-Key", "xxxxxxxxxxxxxx");
                request.ContentType   = "application/json";
                request.ContentLength = postData.Length;
                request.KeepAlive     = false;

                Debug.Print("request set");

                Stream postDataStream = request.GetRequestStream();
                postDataStream.Write(postData, 0, postData.Length);
                postDataStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                request.Dispose();
                Debug.Print(response.StatusCode.ToString());

                Debug.Print("response done");
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message.ToString());
            }
#endif
        }
示例#3
0
        private void callCallbackAndcleanUp(Response response)
        {
            _callback(response);
            IsCompleted = true;
            _callback   = null;
#if NETSTANDARD2_0
            if (null != _request)
            {
                _request.Dispose();
                _request = null;
            }
#endif
        }
示例#4
0
            protected virtual void Dispose(bool disposing)
            {
                if (!disposedValue)
                {
                    if (disposing)
                    {
                        _httpWebResponse.Dispose();
                        _httpWebRequest.Dispose();
                    }

                    disposedValue = true;
                }
            }
示例#5
0
        public static Bitmap DownloadImageFromUrl(string url, WebProxy useProxy = null)
        {
            HttpWebRequest  webRequest  = null;
            HttpWebResponse webResponse = null;

            try
            {
                webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                if (useProxy != null)
                {
                    webRequest.Proxy = useProxy;
                }

                webRequest.Timeout          = Utils.Timeout;
                webRequest.ReadWriteTimeout = Utils.Timeout;

                webResponse = (HttpWebResponse)webRequest.GetResponse();
                Stream sr = webResponse.GetResponseStream();

                int    pos = 0, length;
                byte[] gifBuffer;

                gifBuffer = new byte[(int)webResponse.ContentLength];

                while (pos != webResponse.ContentLength)
                {
                    length = sr.Read(gifBuffer, pos, gifBuffer.Length - pos);
                    pos   += length;
                }
                Bitmap retImg = new Bitmap(gifBuffer, Bitmap.BitmapImageType.Gif);

                return(retImg);
            }
            catch (Exception)
            {
                return(null);
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse.Dispose();
                }
                if (webRequest != null)
                {
                    webRequest.Dispose();
                }
            }
        }
示例#6
0
        private static string Execute(string param)
        {
            string         fullPath = path + param;
            HttpWebRequest request  = WebRequest.Create(fullPath) as HttpWebRequest;

            request.Timeout   = 3000;
            request.KeepAlive = false;
            HttpWebResponse response = null;

            try
            {
                Logger.Trace("Sending request: " + fullPath);

#if OnBoardMonitorEmulator
                return(OnBoardMonitorEmulator.DevicesEmulation.VolumioEmulator.MakeHttpRequest(param));
#endif

                response = request?.GetResponse() as HttpWebResponse;
                using (var stream = response?.GetResponseStream())
                {
                    byte[] bytes = new byte[stream.Length];
                    stream.Read(bytes, 0, bytes.Length);
                    var text = ASCIIEncoding.GetString(bytes, 0, bytes.Length);
                    Logger.Trace("Responded successfull. Bytes: " + bytes.ToHex(' ') + ". Text: " + text);
                    return(text);
                }
            }
            catch (Exception ex)
            {
                var webException = ex as WebException;
                var status       = webException != null ? (int)webException.Status : -1;
                throw new Exception("WebExStatus: " + status, ex);
            }
            finally
            {
                response?.Dispose();
#if NETMF
                request?.Dispose();
#endif
            }
            return(string.Empty);
        }
示例#7
0
        public bool SetWeatherPlace(string place, WebProxy useProxy = null)
        {
            place = place.ToLower();

            _weatherCondition = null;

            //if in cache, don't do a query
            if (_placesWoeidCache.Contains(place))
            {
                _isValidPlace = true;
                _placeWoeid   = (string)_placesWoeidCache[place];
                _place        = place;
                return(true);
            }
            else
            {
                _place        = string.Empty;
                _isValidPlace = false;
            }

            #region format place (replace spaces with %20) and get query url
            string findPlaceUrl = _findPlaceUrl_part1;
            for (int i = 0; i < place.Length; i++)
            {
                char c = place[i];
                switch (c)
                {
                case ' ':
                    findPlaceUrl += "%20";
                    break;

                default:
                    findPlaceUrl += c;
                    break;
                }
            }
            findPlaceUrl += _findPlaceUrl_part2;
            #endregion

            HttpWebRequest  webRequest  = null;
            HttpWebResponse webResponse = null;
            XmlReader       xmlReader   = null;
            try
            {
                webRequest = (HttpWebRequest)HttpWebRequest.Create(findPlaceUrl);
                if (useProxy != null)
                {
                    webRequest.Proxy = useProxy;
                }

                webRequest.Timeout          = Utils.Timeout;
                webRequest.ReadWriteTimeout = Utils.Timeout;

                webResponse = (HttpWebResponse)webRequest.GetResponse();
                xmlReader   = XmlReader.Create(webResponse.GetResponseStream());
                if (xmlReader.ReadToFollowing("woeid"))
                {
                    //store in cache the found woeid
                    string woeid = xmlReader.ReadElementString();
                    _placesWoeidCache.Add(place, woeid);
                    _placeWoeid   = woeid;
                    _place        = place;
                    _isValidPlace = true;
                }
            }
            catch (Exception)
            { }
            finally
            {
                if (xmlReader != null)
                {
                    xmlReader.Close();
                    xmlReader.Dispose();
                }
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse.Dispose();
                }
                if (webRequest != null)
                {
                    webRequest.Dispose();
                }
            }
            return(_isValidPlace);
        }
示例#8
0
        public bool GetWeather(WebProxy useProxy = null)
        {
            if (!_isValidPlace)
            {
                return(false);
            }

            string getWeatherUrl = _getWeatherUrl + _placeWoeid;

            HttpWebRequest  webRequest  = null;
            HttpWebResponse webResponse = null;
            XmlReader       xmlReader   = null;

            YahooWeatherCondition condition = new YahooWeatherCondition();

            try
            {
                webRequest = (HttpWebRequest)HttpWebRequest.Create(getWeatherUrl);
                if (useProxy != null)
                {
                    webRequest.Proxy = useProxy;
                }

                webRequest.Timeout          = Utils.Timeout;
                webRequest.ReadWriteTimeout = Utils.Timeout;

                webResponse = (HttpWebResponse)webRequest.GetResponse();
                xmlReader   = XmlReader.Create(webResponse.GetResponseStream());
                if (xmlReader.ReadToFollowing("yweather:location"))
                {
                    YahooLocation fLocation = new YahooLocation();
                    fLocation.City     = xmlReader.GetAttribute("city");
                    fLocation.Region   = xmlReader.GetAttribute("region");
                    fLocation.Country  = xmlReader.GetAttribute("country");
                    condition.Location = fLocation;
                }
                else
                {
                    return(false);
                }

                string unitTemp, unitDistance, unitPressure, unitSpeed;
                if (xmlReader.ReadToFollowing("yweather:units"))
                {
                    unitTemp     = xmlReader.GetAttribute("temperature");
                    unitDistance = xmlReader.GetAttribute("distance");
                    unitPressure = xmlReader.GetAttribute("pressure");
                    unitSpeed    = xmlReader.GetAttribute("speed");
                }
                else
                {
                    return(false);
                }

                if (xmlReader.ReadToFollowing("yweather:wind"))
                {
                    YahooWindConditions fWind = new YahooWindConditions();
                    fWind.Chill              = xmlReader.GetAttribute("chill");
                    fWind.Direction          = double.Parse(xmlReader.GetAttribute("direction"));
                    fWind.Speed              = xmlReader.GetAttribute("speed") + " " + unitSpeed;
                    condition.WindConditions = fWind;
                }
                else
                {
                    return(false);
                }

                if (xmlReader.ReadToFollowing("yweather:atmosphere"))
                {
                    YahooAtmosphereConditions fAtmoshpere = new YahooAtmosphereConditions();
                    fAtmoshpere.Humidity = xmlReader.GetAttribute("humidity");

                    string pressureString = xmlReader.GetAttribute("pressure");
                    double pressureValue  = double.Parse(pressureString);
                    double deltaPressure  = pressureValue - 1013.25;
                    fAtmoshpere.Pressure           = pressureString + " " + unitPressure + " (" + (deltaPressure >= 0 ? "+" : string.Empty) + deltaPressure.ToString("f2") + ")";
                    fAtmoshpere.Visibility         = xmlReader.GetAttribute("visibility") + " " + unitDistance;
                    condition.AtmosphereConditions = fAtmoshpere;
                }
                else
                {
                    return(false);
                }

                if (xmlReader.ReadToFollowing("yweather:astronomy"))
                {
                    YahooAstronomy fAstronomy = new YahooAstronomy();
                    fAstronomy.SunRise  = xmlReader.GetAttribute("sunrise");
                    fAstronomy.SunSet   = xmlReader.GetAttribute("sunset");
                    condition.Astronomy = fAstronomy;
                }
                else
                {
                    return(false);
                }

                if (xmlReader.ReadToFollowing("yweather:condition"))
                {
                    condition.State       = xmlReader.GetAttribute("text");
                    condition.StateImage  = GetImageForState(xmlReader.GetAttribute("code").Trim(), useProxy);
                    condition.Temperature = xmlReader.GetAttribute("temp") + "°" + unitTemp;
                }
                else
                {
                    return(false);
                }

                ArrayList forecasts = new ArrayList();
                while (xmlReader.ReadToFollowing("yweather:forecast"))
                {
                    YahooForecast fForecast = new YahooForecast();
                    fForecast.Day             = xmlReader.GetAttribute("day");
                    fForecast.TemperatureLow  = xmlReader.GetAttribute("low") + "°";
                    fForecast.TemperatureHigh = xmlReader.GetAttribute("high") + "°";
                    fForecast.State           = xmlReader.GetAttribute("text");
                    fForecast.StateImage      = GetImageForState(xmlReader.GetAttribute("code").Trim(), useProxy);

                    forecasts.Add(fForecast);
                }

                condition.Forecasts = (YahooForecast[])forecasts.ToArray(typeof(YahooForecast));

                condition.GetTime = DateTime.Now;
                _weatherCondition = condition;

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                if (xmlReader != null)
                {
                    xmlReader.Close();
                    xmlReader.Dispose();
                }
                if (webResponse != null)
                {
                    webResponse.Dispose();
                    webResponse.Close();
                }
                if (webRequest != null)
                {
                    webRequest.Dispose();
                }
            }
        }
        public static BasicHttpResponse SendWebRequest(X509Certificate[] certificates, Uri url, string authHeader, string dateHeader, string versionHeader, byte[] payload = null, int contentLength = 0, string httpVerb = "GET", bool expect100Continue = false, string acceptType = "application/json;odata=minimalmetadata", Hashtable additionalHeaders = null)
        {
            string         responseBody       = "";
            HttpStatusCode responseStatusCode = HttpStatusCode.Ambiguous;

            try
            {
                HttpWebResponse response                    = null;
                string          _responseHeader_ETag        = null;
                string          _responseHeader_Content_MD5 = null;
                HttpWebRequest  request = null;
                try
                {
                    request = PrepareRequest(url, authHeader, dateHeader, versionHeader, payload, contentLength, httpVerb, expect100Continue, acceptType, additionalHeaders);
                    if (request != null)
                    {
                        // Assign the certificates. The value must not be null if the
                        // connection is HTTPS.
                        request.HttpsAuthentCerts = TableClient.caCerts;

                        //HttpWebRequest.DefaultWebProxy = new WebProxy("4.2.2.2", true);

                        // Evtl. set request.KeepAlive to use a persistent connection.
                        request.KeepAlive        = false;
                        request.Timeout          = 100000;          // timeout 100 sec = standard
                        request.ReadWriteTimeout = 100000;          // timeout 100 sec, standard = 300
                        //lock (theLock1)
                        //{
                        if (_debug_level == DebugLevel.DebugErrorsPlusMessages)
                        {
                            _Print_Debug("Time of request (no DLST): " + DateTime.Now);
                            _Print_Debug("Url: " + url.AbsoluteUri);
                        }
                        //}

                        // This is needed since there is an exception if the GetRequestStream method is called with GET or HEAD
                        if ((httpVerb != "GET") && (httpVerb != "HEAD"))
                        {
                            using (Stream requestStream = request.GetRequestStream())
                            {
                                requestStream.Write(payload, 0, contentLength);
                            }
                        }

                        response = (HttpWebResponse)request.GetResponse();

                        if (response != null)
                        {
                            if (response.Headers.Count > 0)
                            {
                                try
                                {
                                    _responseHeader_ETag = response.GetResponseHeader("ETag");
                                }
                                catch { }

                                try
                                {
                                    _responseHeader_Content_MD5 = response.GetResponseHeader("Content-MD5");
                                }
                                catch { }
                            }
                            responseStatusCode = response.StatusCode;
                            Stream dataStream = response.GetResponseStream();

                            StreamReader reader = new StreamReader(dataStream);
                            responseBody = reader.ReadToEnd();
                            //Report all incomming data to the debug
                            lock (theLock1)
                            {
                                if (_debug_level == DebugLevel.DebugAll)
                                {
                                    _Print_Debug(responseBody);
                                }
                            }
                            reader.Close();
                            if (response.StatusCode == HttpStatusCode.Forbidden)
                            //if ((response.StatusCode == HttpStatusCode.Forbidden) || (response.StatusCode == HttpStatusCode.NotFound))
                            {
                                lock (theLock1)
                                {
                                    _Print_Debug("Problem with signature. Check next debug statement for stack");

                                    throw new WebException("Forbidden", null, WebExceptionStatus.TrustFailure, response);
                                }
                            }
                            response.Close();
                            if (responseBody == null)
                            {
                                responseBody = "No body content";
                            }

                            //_Print_Debug(responseBody);
                            return(new BasicHttpResponse()
                            {
                                ETag = _responseHeader_ETag, Body = responseBody, StatusCode = responseStatusCode
                            });
                        }
                        else
                        {
                            return(new BasicHttpResponse()
                            {
                                ETag = _responseHeader_ETag, Body = responseBody, StatusCode = responseStatusCode
                            });
                        }
                    }
                    else
                    {
                        lock (theLock1)
                        {
                            _Print_Debug("Failure: Request is null");
                        }
                        return(new BasicHttpResponse()
                        {
                            ETag = _responseHeader_ETag, Body = responseBody, StatusCode = responseStatusCode
                        });
                    }
                }
                catch (WebException ex)
                {
                    lock (theLock1)
                    {
                        _Print_Debug("An error occured. Status code:" + ((HttpWebResponse)ex.Response).StatusCode);
                    }
                    responseStatusCode = ((HttpWebResponse)ex.Response).StatusCode;
                    using (Stream stream = ex.Response.GetResponseStream())
                    {
                        int theRead = stream.ReadByte();

                        //return new BasicHttpResponse() { ETag = _responseHeader_ETag, Body = responseBody, StatusCode = responseStatusCode };


                        using (StreamReader sr = new StreamReader(stream))
                        {
                            StringBuilder sB    = new StringBuilder("");
                            Char[]        chunk = new char[20];

                            while (sr.Peek() > -1)
                            {
                                int readBytes = sr.Read(chunk, 0, chunk.Length);
                                sB.Append(chunk, 0, readBytes);
                            }
                            responseBody = sB.ToString();
                            lock (theLock1)
                            {
                                _Print_Debug(responseBody);
                            }

                            /*
                             * var s = sr.ReadToEnd();
                             * lock (theLock1)
                             * {
                             *  _Print_Debug(s);
                             * }
                             * responseBody = s;
                             */

                            return(new BasicHttpResponse()
                            {
                                ETag = _responseHeader_ETag, Body = responseBody, StatusCode = responseStatusCode
                            });
                        }
                    }
                }

                catch (Exception ex2)
                {
                    lock (theLock1)
                    {
                        _Print_Debug("Exception in HttpWebRequest.GetResponse(): " + ex2.Message);
                        _Print_Debug("ETag: " + _responseHeader_ETag + " Body: " + responseBody + " StatusCode: " + responseStatusCode);
                    }
                    return(new BasicHttpResponse()
                    {
                        ETag = _responseHeader_ETag, Body = responseBody, StatusCode = responseStatusCode
                    });
                }
                finally
                {
                    if (response != null)
                    {
                        response.Dispose();
                    }
                    if (request != null)
                    {
                        request.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                lock (theLock1)
                {
                    _Print_Debug("Exception in HttpWebRequest: " + ex.Message);
                }
                return(new BasicHttpResponse()
                {
                    ETag = null, Body = responseBody, StatusCode = responseStatusCode
                });
            }
        }
示例#10
0
        public bool GetWeather(string place, WebProxy useProxy = null)
        {
            _weatherCondition = null;
            string requestUrl = _getWeatherUrl;

            #region format place (replace spaces with %20) and get query url
            for (int i = 0; i < place.Length; i++)
            {
                char c = place[i];
                switch (c)
                {
                case ' ':
                    requestUrl += "%20";
                    break;

                default:
                    requestUrl += c;
                    break;
                }
            }
            #endregion

            HttpWebRequest  webRequest  = null;
            HttpWebResponse webResponse = null;
            XmlReader       xmlReader   = null;
            try
            {
                webRequest = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
                if (useProxy != null)
                {
                    webRequest.Proxy = useProxy;
                }

                webRequest.Timeout          = Utils.Timeout;
                webRequest.ReadWriteTimeout = Utils.Timeout;

                webResponse = (HttpWebResponse)webRequest.GetResponse();
                xmlReader   = XmlReader.Create(webResponse.GetResponseStream());

                if (!xmlReader.ReadToFollowing("forecast_information"))
                {
                    return(false);
                }

                GoogleForecast newForecast = new GoogleForecast();
                if (!xmlReader.ReadToDescendant("city"))
                {
                    return(false);
                }
                newForecast.City = xmlReader.GetAttribute("data");
                if (!xmlReader.ReadToNextSibling("unit_system"))
                {
                    return(false);
                }
                newForecast.UnitSystem = xmlReader.GetAttribute("data");

                GoogleCurrentCondition currentCondition;
                newForecast.CurrentCondition = currentCondition = new GoogleCurrentCondition();

                if (!xmlReader.ReadToFollowing("current_conditions"))
                {
                    return(false);
                }
                if (!xmlReader.ReadToDescendant("condition"))
                {
                    return(false);
                }
                currentCondition.Condition = xmlReader.GetAttribute("data");
                if (!xmlReader.ReadToNextSibling("temp_c"))
                {
                    return(false);
                }
                currentCondition.Temp = xmlReader.GetAttribute("data") + "°C";
                if (!xmlReader.ReadToNextSibling("humidity"))
                {
                    return(false);
                }
                currentCondition.Humidity = xmlReader.GetAttribute("data");
                if (!xmlReader.ReadToNextSibling("icon"))
                {
                    return(false);
                }
                currentCondition.Icon = GetImage(xmlReader.GetAttribute("data"), useProxy);
                if (!xmlReader.ReadToNextSibling("wind_condition"))
                {
                    return(false);
                }
                currentCondition.Wind = xmlReader.GetAttribute("data");

                ArrayList forecasts = new ArrayList();
                while (xmlReader.ReadToFollowing("forecast_conditions"))
                {
                    GoogleForecastCondition forecast = new GoogleForecastCondition();
                    if (!xmlReader.ReadToDescendant("day_of_week"))
                    {
                        return(false);
                    }
                    forecast.DayOfWeek = xmlReader.GetAttribute("data");
                    if (!xmlReader.ReadToNextSibling("low"))
                    {
                        return(false);
                    }
                    forecast.TempLow = xmlReader.GetAttribute("data");
                    if (newForecast.UnitSystem == "US")
                    {
                        forecast.TempLow = Utils.ConvertFahrenheitToCelsius(forecast.TempLow);
                    }

                    if (!xmlReader.ReadToNextSibling("high"))
                    {
                        return(false);
                    }
                    forecast.TempHigh = xmlReader.GetAttribute("data");
                    if (newForecast.UnitSystem == "US")
                    {
                        forecast.TempHigh = Utils.ConvertFahrenheitToCelsius(forecast.TempHigh);
                    }

                    if (!xmlReader.ReadToNextSibling("icon"))
                    {
                        return(false);
                    }
                    forecast.Icon = GetImage(xmlReader.GetAttribute("data"), useProxy);
                    if (!xmlReader.ReadToNextSibling("condition"))
                    {
                        return(false);
                    }
                    forecast.Condition = xmlReader.GetAttribute("data");
                    forecasts.Add(forecast);
                }
                newForecast.Forecasts    = (GoogleForecastCondition[])forecasts.ToArray(typeof(GoogleForecastCondition));
                newForecast.ForecastTime = DateTime.Now;
                _weatherCondition        = newForecast;

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                if (xmlReader != null)
                {
                    xmlReader.Close();
                    xmlReader.Dispose();
                }
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse.Dispose();
                }
                if (webRequest != null)
                {
                    webRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// Processes a message
        /// </summary>
        /// <param name="stream">The message being processed.</param>
        /// <param name="ctx">The context associated with the message.</param>
        /// <returns>The handling status for this operation.</returns>
        protected override ChainResult OnProcessInputMessage(ref WsMessage msg, BindingContext ctx)
        {
            byte[] soapResponse         = null;
            WebHeaderCollection headers = null;

            if (ctx is ClientBindingContext)
            {
                HttpWebRequest request = ctx.ContextObject as HttpWebRequest;

                if (request == null)
                {
                    msg = null;
                    return(ChainResult.Abort);
                }

                HttpWebResponse resp = request.GetResponse() as HttpWebResponse;

                if (resp == null)
                {
                    throw new WebException("", WebExceptionStatus.ReceiveFailure); // No response was received on the HTTP channel
                }

                try
                {
                    headers = (System.Net.WebHeaderCollection)resp.Headers;

                    if (resp.ProtocolVersion != HttpVersion.Version11)
                    {
                        throw new IOException(); // Invalid http version in response line.
                    }

                    if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.Accepted)
                    {
                        if (resp.ContentType.IndexOf("application/soap+xml") == -1)
                        {
                            throw new IOException(); // Bad status code in response
                        }
                    }

                    if (resp.ContentLength > 0)
                    {
                        // Return the soap response.
                        soapResponse = new byte[(int)resp.ContentLength];
                        Stream respStream = resp.GetResponseStream();

                        respStream.ReadTimeout = (int)(ctx.ReceiveTimeout.Ticks / TimeSpan.TicksPerMillisecond);

                        // Now need to read all data. We read in the loop until resp.ContentLength or zero bytes read.
                        // Zero bytes read means there was error on server and it did not send all data.
                        int respLength = (int)resp.ContentLength;
                        for (int totalBytesRead = 0; totalBytesRead < respLength;)
                        {
                            int bytesRead = respStream.Read(soapResponse, totalBytesRead, (int)resp.ContentLength - totalBytesRead);
                            // If nothing is read - means server closed connection or timeout. In this case no retry.
                            if (bytesRead == 0)
                            {
                                break;
                            }

                            // Adds number of bytes read on this iteration.
                            totalBytesRead += bytesRead;
                        }

                        headers = resp.Headers;
                    }
                    //
                    // ContentLenght == 0 is OK
                    //
                    else if (resp.ContentLength < 0)
                    {
                        throw new ProtocolViolationException(); // Invalid http header, content lenght < 0
                    }
                }
                finally
                {
                    resp.Dispose();
                    request.Dispose();
                    ctx.ContextObject = null;
                }
            }
            else // server waits for messages
            {
                HttpListenerContext listenerContext;

                try
                {
                    if (m_persistConn && ctx.ContextObject != null)
                    {
                        listenerContext = (HttpListenerContext)ctx.ContextObject;

                        listenerContext.Reset();
                    }
                    else
                    {
                        if (m_httpListener == null)
                        {
                            msg = null;
                            return(ChainResult.Abort);
                        }

                        listenerContext = m_httpListener.GetContext();
                    }

                    if (listenerContext == null)
                    {
                        msg = null;
                        return(ChainResult.Abort);
                    }

                    ctx.ContextObject = listenerContext;

                    // The context returned by m_httpListener.GetContext(); can be null in case the service was stopped.
                    HttpListenerRequest listenerRequest = listenerContext.Request;

                    HttpListenerResponse listenerResponse = listenerContext.Response;

                    listenerRequest.InputStream.ReadTimeout    = (int)(ctx.ReceiveTimeout.Ticks / TimeSpan.TicksPerMillisecond);
                    listenerResponse.OutputStream.WriteTimeout = (int)(ctx.SendTimeout.Ticks / TimeSpan.TicksPerMillisecond);

                    headers = (System.Net.WebHeaderCollection)listenerRequest.Headers;

                    System.Ext.Console.Write("Request From: " + listenerRequest.RemoteEndPoint.ToString());

                    // Checks and process headers important for DPWS
                    if (!ProcessKnownHeaders(listenerContext))
                    {
                        msg = null;
                        return(ChainResult.Abort);
                    }

                    soapResponse = null;

                    int messageLength = (int)listenerRequest.ContentLength64;
                    if (messageLength > 0)
                    {
                        // If there is content length for the message, we read it complete.
                        soapResponse = new byte[messageLength];

                        for (int offset = 0; offset < messageLength;)
                        {
                            int noRead = listenerRequest.InputStream.Read(soapResponse, offset, messageLength - offset);
                            if (noRead == 0)
                            {
                                throw new IOException("Http server got only " + offset + " bytes. Expected to read " + messageLength + " bytes.");
                            }

                            offset += noRead;
                        }
                    }
                    else
                    {
                        // In this case the message is chunk encoded, but m_httpRequest.InputStream actually does processing.
                        // So we we read until zero bytes are read.
                        bool readComplete = false;
                        int  bufferSize   = ReadPayload;
                        soapResponse = new byte[bufferSize];
                        int offset = 0;
                        while (!readComplete)
                        {
                            while (offset < ReadPayload)
                            {
                                int noRead = listenerRequest.InputStream.Read(soapResponse, offset, messageLength - offset);
                                // If we read zero bytes - means this is end of message. This is how InputStream.Read for chunked encoded data.
                                if (noRead == 0)
                                {
                                    readComplete = true;
                                    break;
                                }

                                offset += noRead;
                            }

                            // If read was not complete - increase the buffer.
                            if (!readComplete)
                            {
                                bufferSize += ReadPayload;
                                byte[] newMessageBuf = new byte[bufferSize];
                                Array.Copy(soapResponse, newMessageBuf, offset);
                                soapResponse = newMessageBuf;
                            }
                        }
                    }
                }
                catch
                {
                    ctx.ContextObject = null;
                    throw;
                }
            }

            if (headers != null)
            {
                string [] keys = headers.AllKeys;
                int       len  = keys.Length;

                ArrayList props = ctx.BindingProperties;

                for (int i = 0; i < len; i++)
                {
                    string key = keys[i];

                    if (!WebHeaderCollection.IsRestricted(key))
                    {
                        props.Add(new BindingProperty("header", key, headers[key]));
                    }
                }
            }

            System.Ext.Console.Write(soapResponse);


            msg.Body = soapResponse;

            return(ChainResult.Continue);
        }
示例#12
0
        public static HttpWebRequest BuildServerRequest(string url, byte[] fileBytes, string fileParamName, string fileContentType, string fileName)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString();

            byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");

            string fileHeader = "";

            byte[] fileHeaderBytes = null;
            byte[] fileTrailer     = null;

            ArrayList formItems  = new ArrayList();
            int       requestLen = 0;

            if (fileBytes != null && fileBytes.Length > 0)
            {
                fileHeader      = "Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\"" + fileName + "\"\r\nContent-Type: " + fileContentType + "\r\n\r\n";
                fileHeaderBytes = System.Text.Encoding.UTF8.GetBytes(fileHeader);
                //fileTrailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                fileTrailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                requestLen += boundarybytes.Length + fileHeaderBytes.Length + fileTrailer.Length + fileBytes.Length;
            }

            //var eof = System.Text.Encoding.UTF8.GetBytes();
            var            eof           = System.Text.Encoding.UTF8.GetBytes("\r\n");
            HttpWebRequest request       = null;
            Stream         requestStream = null;

            request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.HttpsAuthentCerts = null;


            if (request.Headers["Content-Type"] != null)
            {
                request.Headers.Remove("Content-Type");
            }

            request.ContentType = "multipart/form-data; boundary=" + boundary;

            request.Method = "POST";
            // request.KeepAlive = true;
            request.ContentLength = requestLen;
            request.Expect        = string.Empty;


            try
            {
                requestStream = request.GetRequestStream();

                foreach (var item in formItems)
                {
                    requestStream.Write(boundarybytes, 0, boundarybytes.Length);
                    var bytes = item as byte[];
                    requestStream.Write(bytes, 0, bytes.Length);
                }



                if (fileBytes != null && fileBytes.Length > 0)
                {
                    requestStream.Write(boundarybytes, 0, boundarybytes.Length);
                    requestStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);
                    int chunkSize = 1427; // any larger will cause an SSL request to fail

                    for (int i = 0; i < fileBytes.Length; i += chunkSize)
                    {
                        var toWrite = chunkSize;

                        if (i + 1 + chunkSize > fileBytes.Length)
                        {
                            toWrite = fileBytes.Length - i;
                        }

                        requestStream.Write(fileBytes, i, toWrite);
                    }

                    requestStream.Write(fileTrailer, 0, fileTrailer.Length);
                }



                requestStream.Close();
                requestStream.Dispose();
                requestStream = null;
            }

            catch (Exception ex)
            {
                if (request != null)
                {
                    request.Dispose();
                }

                request = null;

                Debug.Print(ex.ToString());
            }

            finally
            {
                if (requestStream != null)
                {
                    requestStream.Dispose();
                }
            }

            return(request);
        }