Esempio n. 1
1
    public void Request(string url)
    {
        Stopwatch timer = new Stopwatch();
        StringBuilder respBody = new StringBuilder();

        this.request = (HttpWebRequest)WebRequest.Create(url);

        try {
            timer.Start();
            this.response = (HttpWebResponse)this.request.GetResponse();
            byte[] buf = new byte[8192];
            Stream respStream = this.response.GetResponseStream();
            int count = 0;
            do {
                count = respStream.Read(buf, 0, buf.Length);
                if (count != 0)
                    respBody.Append(Encoding.ASCII.GetString(buf, 0, count));
            }
            while (count > 0);
            timer.Stop();

            this.responseBody = respBody.ToString();
            this.statusCode = (int)(HttpStatusCode)this.response.StatusCode;
            this.responseTime = timer.ElapsedMilliseconds / 1000.0;
        } catch (WebException ex) {
            this.response = (HttpWebResponse)ex.Response;
            this.responseBody = "No Server Response";
            this.escapedBody = "No Server Response";
            this.responseTime = 0.0;
        }
    }
    const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout

    #endregion Fields

    #region Methods

    public static String GetResponseBody(HttpWebResponse response)
    {
        Stream responseStream = response.GetResponseStream();
        Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader responseStreamReader = new StreamReader(responseStream,enc);
        return responseStreamReader.ReadToEnd();
    }
Esempio n. 3
1
    private static Boolean getResponse(HttpWebRequest request)
    {
        try
        {
            response = request.GetResponse() as HttpWebResponse;
            return true;
        }
        catch (WebException e)
        {
            Console.WriteLine("Exception Message :" + e.Message);
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                var response = ((HttpWebResponse)e.Response);
                Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);

                var stream = response.GetResponseStream();
                var reader = new StreamReader(stream);
                var text = reader.ReadToEnd();
                Console.WriteLine("Response Description : {0}", text);

            }
            return false;
        }
    }
Esempio n. 4
0
    /// <summary>  
    ///  傳送推播的訊息
    /// </summary>  
    /// <param name="message">推播的訊息內容</param>  
    /// <returns>傳送的結果Json Format</returns>
    public string Send(string message)
    {
        // Escape condition 防呆
        if (REGID == null || APIKey == null)
        {
            return "[ERROR] Reg.ID or API Key has not been set";
        }

        InitGCMClient();
        PostPayload(message);

        try
        {
            gcmResponse = gcmRequest.GetResponse() as HttpWebResponse;
        }
        catch (WebException we)
        {
            return "[ERROR] There is a problem within processing GCM message \n" + we.Message;
        }

        ResultJSON = ReadResponse(gcmResponse);

        //ErrorHandle(ResultJSON);
        //NewRegIDHandle(ResultJSON);

        return ResultJSON;
    }
    public static ResponseCategories CategorizeResponse(HttpWebResponse httpResponse)
    {
        //Just incase there are more success codes defined in the future by
            // HttpStatusCode, We will checkf or the "success" ranges
            // instead of using teh HttpStatusCode enum as it overloads some values.

            int statusCode = (int)httpResponse.StatusCode;

            if ((statusCode >= 100) && (statusCode <= 199))
            {
                return ResponseCategories.Informational;
            }
            else if ((statusCode >= 200) && (statusCode <= 299))
            {
                return ResponseCategories.Success;
            }
            else if ((statusCode >= 300) && (statusCode <= 399))
            {
                return ResponseCategories.Redirected;
            }
            else if ((statusCode >= 400) && (statusCode <= 499))
            {
                return ResponseCategories.ClientError;
            }
            else if ((statusCode >= 500) && (statusCode <= 599))
            {
                return ResponseCategories.ServerError;
            }
            return ResponseCategories.Unknown;
    }
Esempio n. 6
0
 string JSONResponse(HttpWebResponse webResponse)
 {
     StreamReader rdr = new StreamReader(webResponse.GetResponseStream());
     string strResponse = rdr.ReadToEnd();
     rdr.Close();
     return strResponse;
 }
Esempio n. 7
0
    public static void HandleResponse(HttpWebResponse response)
    {
        // response status line
        Debug.Print("HTTP/" + response.ProtocolVersion + " " +
                    response.StatusCode + " " +
                    response.StatusDescription);

        // response headers
        string[] headers = response.Headers.AllKeys;
        foreach (string name in headers)
        {
            Debug.Print(name + ": " + response.Headers[name]);
        }

        // response body
        var buffer = new byte[(int)response.ContentLength];
        Stream stream = response.GetResponseStream();
        int toRead = buffer.Length;
        while (toRead > 0)
        {
            // already read: buffer.Length - toRead
            int read = stream.Read(buffer, buffer.Length - toRead, toRead);
            toRead = toRead - read;
        }
        char[] chars = Encoding.UTF8.GetChars(buffer);
        Debug.Print(new string(chars));
    }
            protected ResponseRecord populateResponseRecord(HttpWebResponse response)
            {
                Stream responseStream = response.GetResponseStream();

                ResponseRecord responseRecord = new ResponseRecord();
                responseRecord.ResponseHeaders = response.Headers;
                responseRecord.ResponseStream = responseStream;

                return responseRecord;
            }
Esempio n. 9
0
    static void write(HttpWebResponse response)
    {
        write(response.Headers);

        using (Stream data = response.GetResponseStream()) {
            using (TextReader port = new StreamReader(data)) {
                write(port);
            }
        }
    }
Esempio n. 10
0
 internal static void GetHttpWebResponse(InvalidOperationException exception, ref HttpWebResponse response)
 {
     if (null == response)
     {
         WebException webexception = (exception as WebException);
         if (null != webexception)
         {
             response = (HttpWebResponse)webexception.Response;
         }
     }
 }
Esempio n. 11
0
 public boolean DoIt(HttpWebResponse response)
 {
     // interesting language feature: Fully qualified constants in case
     switch(response.StatusCode)
     {
         case HttpStatusCode.Accepted:
         case HttpStatusCode.Ambiguous:
         case HttpStatusCode.Forbidden:
         {
             return true;
         }
         default:
         {
             return false;
         }
     }
 }
        void testProxies(object sender, DoWorkEventArgs e)
        {
            try
            {
                int i = (int)e.Argument;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://m.youtube.com/");
                //request.Proxy = getProxy(sender);
                HttpWebResponse response = null;
                try
                {
                    //request.UserAgent = UserAgent;

                    WebProxy PROXY = new WebProxy();
                    string   ip = null, port = null, user = null, pass = null;
                    string   pr = proxies[i];

                    ip = pr.Substring(0, pr.IndexOf(":"));
                    pr = pr.Substring(pr.IndexOf(":") + 1, pr.Length - pr.IndexOf(":") - 1);
                    if (pr.Contains(":"))
                    {
                        port = pr.Substring(0, pr.IndexOf(":"));
                        pr   = pr.Substring(pr.IndexOf(":") + 1, pr.Length - pr.IndexOf(":") - 1);
                        user = pr.Substring(0, pr.IndexOf(":"));
                        pr   = pr.Substring(pr.IndexOf(":") + 1, pr.Length - pr.IndexOf(":") - 1);
                        pass = pr.Substring(0, pr.Length);
                    }
                    else
                    {
                        port = pr.Substring(0, pr.Length);
                    }

                    PROXY.Address = new Uri("http://" + ip + ":" + port);
                    if (user != null & pass != null)
                    {
                        NetworkCredential nc = new NetworkCredential(user, pass);
                        PROXY.Credentials = nc;
                    }
                    request.Proxy = PROXY;
                    //request.Timeout = proxyTimeout * 1000;
                    response = (HttpWebResponse)request.GetResponse();
                    Stream       stream     = response.GetResponseStream();
                    StreamReader streamRead = new StreamReader(stream);
                    string       RS         = streamRead.ReadToEnd();


                    if (RS.Contains("<title>YouTube</title>"))
                    {
                        good.Add(proxies[i]);
                    }
                }
                catch
                { }
                finally
                {
                    request.Abort();
                }
            }
            catch { }
            finally { runningProxyThreads--; }
        }
Esempio n. 13
0
        private void BtLook_Click(object sender, EventArgs e)
        {
            tabControl.SelectedTab = tabDriver;
            double lat = 0;
            double lng = 0;

            drivers = new List <Driver>();
            if (tbFrom.Text.Length < 1)
            {
                return;
            }

            HttpWebRequest webRequest = WebRequest.CreateHttp("http://localhost:56081/api/managerappone/getinformationaddress/" + tbFrom.Text);

            webRequest.Method = "GET";
            HttpWebResponse webResponse = null;

            try
            {
                webResponse = webRequest.GetResponse() as HttpWebResponse;
                if (webResponse.StatusCode != HttpStatusCode.OK)
                {
                    if (webResponse != null)
                    {
                        webResponse.Close();
                    }
                    return;
                }
                using (var jsonStream = new StreamReader(webResponse.GetResponseStream()))
                {
                    string buffReader = jsonStream.ReadToEnd();
                    buffReader = buffReader.Trim('\"');
                    string[] latlng = buffReader.Split(',');
                    lat = double.Parse(latlng[0]);
                    lng = double.Parse(latlng[1]);
                }
            }
            catch (WebException exec)
            {
                if (exec.Status == WebExceptionStatus.ProtocolError)
                {
                    webResponse = (HttpWebResponse)exec.Response;
                    MessageBox.Show("Error code: " + webResponse.StatusCode.ToString());
                }
                else
                {
                    MessageBox.Show("Error: " + exec.Status.ToString());
                }
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                }
            }
            //find driver
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(
                new
            {
                lat     = lat,
                lng     = lng,
                typeCar = 0,
                radius  = 60000
            });

            webRequest             = WebRequest.CreateHttp("http://localhost:56081/api/managerappone/finddriver");
            webRequest.Method      = "PUT";
            webRequest.ContentType = "application/json";
            var buffer = Encoding.UTF8.GetBytes(json);

            webRequest.ContentLength = buffer.Length;
            webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
            webResponse = null;
            try
            {
                webResponse = webRequest.GetResponse() as HttpWebResponse;
                if (webResponse.StatusCode != HttpStatusCode.OK)
                {
                    if (webResponse != null)
                    {
                        webResponse.Close();
                    }
                    return;
                }
                using (var jsonStream = new StreamReader(webResponse.GetResponseStream()))
                {
                    var    t          = 0;
                    string buffReader = jsonStream.ReadToEnd();
                    drivers    = JsonConvert.DeserializeObject <List <Driver> >(buffReader);
                    DriverBoxs = new DriverBox[drivers.Count];
                    for (int ii = 0; ii < DriverBoxs.Length; ii++)
                    {
                        DriverBoxs[ii] = new DriverBox();
                        tabDriver.Controls.Add(DriverBoxs[ii].Box);
                        DriverBoxs[ii].Box.Height = 115;
                        DriverBoxs[ii].Box.Width  = tabDriver.Width;
                        DriverBoxs[ii].Box.Text   = "Driver " + ii.ToString();
                        DriverBoxs[ii].Box.Top    = t;
                        t += 120;

                        DriverBoxs[ii].Box.Controls.Add(DriverBoxs[ii].Name);
                        DriverBoxs[ii].Name.Width = DriverBoxs[ii].Box.Width;
                        DriverBoxs[ii].Name.Text  = "Name: " + drivers[ii].Name;
                        DriverBoxs[ii].Name.Top   = 15;

                        DriverBoxs[ii].Box.Controls.Add(DriverBoxs[ii].Lat);
                        DriverBoxs[ii].Lat.Width = DriverBoxs[ii].Box.Width;
                        DriverBoxs[ii].Lat.Text  = "Lat: " + drivers[ii].Lat;
                        DriverBoxs[ii].Lat.Top   = 40;

                        DriverBoxs[ii].Box.Controls.Add(DriverBoxs[ii].Lng);
                        DriverBoxs[ii].Lng.Width = DriverBoxs[ii].Box.Width;
                        DriverBoxs[ii].Lng.Text  = "Lng: " + drivers[ii].Lng;
                        DriverBoxs[ii].Lng.Top   = 65;

                        DriverBoxs[ii].Box.Controls.Add(DriverBoxs[ii].Button);
                        DriverBoxs[ii].Button.Width  = DriverBoxs[ii].Box.Width;
                        DriverBoxs[ii].Button.Text   = "Book this car";
                        DriverBoxs[ii].Button.Left   = (DriverBoxs[ii].Box.Width - DriverBoxs[ii].Button.Width) / 2 - 1;
                        DriverBoxs[ii].Button.Top    = 90;
                        DriverBoxs[ii].Button.Name   = ii.ToString();
                        DriverBoxs[ii].Button.Click += new System.EventHandler(BtBookCar_Click);
                    }
                }
            }
            catch (WebException exec)
            {
                if (exec.Status == WebExceptionStatus.ProtocolError)
                {
                    webResponse = (HttpWebResponse)exec.Response;
                    MessageBox.Show("Error code: " + webResponse.StatusCode.ToString());
                }
                else
                {
                    MessageBox.Show("Error: " + exec.Status.ToString());
                }
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                }
            }
        }
Esempio n. 14
0
        private void btnExoneraIcms_Click(object sender, EventArgs e)
        {
            #region Primeiro Get Request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlInicioPrivado);
            request.ClientCertificates.Add(ObterCertificado());

            request.UseDefaultCredentials = true;
            request.PreAuthenticate       = true;
            request.Credentials           = CredentialCache.DefaultCredentials;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            var token = response.Headers.GetValues(4);
            response.Close();
            #endregion

            #region Segundo Get Request
            string tokenString = token[0] + ";" + token[1];

            request        = (HttpWebRequest)WebRequest.Create(urlDeclararICMS);
            request.Method = "GET";

            request.PreAuthenticate     = true;
            request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
            request.UserAgent           = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Mobile Safari/537.36";
            request.ClientCertificates.Add(ObterCertificado());

            request.Headers.Add("Cookie", tokenString);

            response = (HttpWebResponse)request.GetResponse();

            response.Close();
            #endregion

            #region Post Form
            string dataForm = "tp=3&numDI=19%2F0288362-6&primeiraDeclaracao=true&uf=AM&mandadoJudicial=&banco=&agencia=&contaCorrente=&valor=&dataDar=";

            HttpWebRequest HttpWebRequestPost = (HttpWebRequest)HttpWebRequest.Create(urlDeclararICMS);
            HttpWebRequestPost.Method = "POST";

            byte[] data = Encoding.ASCII.GetBytes(dataForm);

            HttpWebRequestPost.ContentLength = data.Length;
            HttpWebRequestPost.Referer       = urlDeclararICMS;
            HttpWebRequestPost.ContentType   = "application/x-www-form-urlencoded";
            HttpWebRequestPost.ClientCertificates.Add(ObterCertificado());
            HttpWebRequestPost.KeepAlive = true;
            HttpWebRequestPost.Headers.Add("Cookie", tokenString);
            HttpWebRequestPost.UserAgent = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Mobile Safari/537.36";

            HttpWebRequestPost.Headers.Add("Pragma", "no-cache");
            HttpWebRequestPost.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3";
            HttpWebRequestPost.Headers.Add("Accept-Encoding", "gzip, deflate");
            HttpWebRequestPost.Headers.Add("Accept-Language", "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,es;q=0.6");

            HttpWebRequestPost.AllowAutoRedirect = true;
            HttpWebRequestPost.Timeout           = 60000;

            TransportContext context;

            using (Stream requestStreamPost = HttpWebRequestPost.GetRequestStream(out context))
            {
                requestStreamPost.Write(data, 0, data.Length);

                using (HttpWebResponse HttpWebResponsePost = (HttpWebResponse)HttpWebRequestPost.GetResponse())
                {
                    using (Stream responseStreamPost = HttpWebResponsePost.GetResponseStream())
                    {
                        StreamReader StreamReaderPost = new StreamReader(responseStreamPost, Encoding.Default);
                        string       pageContent      = StreamReaderPost.ReadToEnd();
                    }
                }
            }
            #endregion
        }
Esempio n. 15
0
        private Attachment[] GetAttachmentsWithSOAP(string[] attachmentIds, string authToken, string ewsUrl)
        {
            string getAttachmentRequest =
                @"<?xml version=""1.0"" encoding=""utf-8""?>
                <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
                xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
                xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""
                xmlns:t=""http://schemas.microsoft.com/exchange/services/2006/types"">
                <soap:Header>
                <t:RequestServerVersion Version=""Exchange2013"" />
                </soap:Header>
                    <soap:Body>
                    <GetAttachment xmlns=""http://schemas.microsoft.com/exchange/services/2006/messages""
                    xmlns:t=""http://schemas.microsoft.com/exchange/services/2006/types"">
                        <AttachmentShape/>
                        <AttachmentIds>";

            foreach (string id in attachmentIds)
            {
                getAttachmentRequest = getAttachmentRequest + @"            <t:AttachmentId Id=""" + id + @"""/>";
            }
            getAttachmentRequest +=
                @"        </AttachmentIds>
                    </GetAttachment>
                    </soap:Body>
                </soap:Envelope>";

            // Prepare a web request object.
            HttpWebRequest webRequest = WebRequest.CreateHttp(ewsUrl);

            webRequest.Headers.Add("Authorization", string.Format("Bearer {0}", authToken));
            webRequest.PreAuthenticate   = true;
            webRequest.AllowAutoRedirect = false;
            webRequest.Method            = "POST";
            webRequest.ContentType       = "text/xml; charset=utf-8";

            // Construct the SOAP message for the GetAttchment operation.
            byte[] bodyBytes = System.Text.Encoding.UTF8.GetBytes(getAttachmentRequest);
            webRequest.ContentLength = bodyBytes.Length;

            Stream requestStream = webRequest.GetRequestStream();

            requestStream.Write(bodyBytes, 0, bodyBytes.Length);
            requestStream.Close();

            // Make the request to the Exchange server and get the response.
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            // If the response is okay, create an XML document from the
            // response and process the request.
            if (webResponse.StatusCode == HttpStatusCode.OK)
            {
                Stream responseStream = webResponse.GetResponseStream();

                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(responseStream);

                XmlNodeList fileNameNodes = xmlDocument.GetElementsByTagName("t:Name");
                XmlNodeList byteNodes     = xmlDocument.GetElementsByTagName("t:Content");

                Attachment[] attachments = new Attachment[fileNameNodes.Count];

                for (int i = 0; i < fileNameNodes.Count; i++)
                {
                    attachments[i] = new Attachment();
                    attachments[i].AttachmentName  = fileNameNodes[i].InnerText;
                    attachments[i].AttachmentBytes = Convert.FromBase64String(byteNodes[i].InnerText);
                }

                // Close the response stream.
                responseStream.Close();
                webResponse.Close();

                return(attachments); //new Attachment() { AttachmentBytes = bytes, AttachmentName = fileName };
            }

            return(null);
        }
Esempio n. 16
0
		HttpResponseMessage CreateResponseMessage (HttpWebResponse wr, HttpRequestMessage requestMessage)
		{
			var response = new HttpResponseMessage (wr.StatusCode);
			response.RequestMessage = requestMessage;
			response.ReasonPhrase = wr.StatusDescription;
			response.Content = new StreamContent (wr.GetResponseStream ());

			var headers = wr.Headers;
			for (int i = 0; i < headers.Count; ++i) {
				var key = headers.GetKey(i);
				var value = headers.GetValues (i);

				if (HttpHeaders.GetKnownHeaderKind (key) == Headers.HttpHeaderKind.Content)
					response.Content.Headers.AddWithoutValidation (key, value);
				else
					response.Headers.AddWithoutValidation (key, value);
			}

			return response;
		}
        private MsoCookies getSamlToken()
        {
            MsoCookies ret = new MsoCookies();

            try
            {
                var sharepointSite = new
                {
                    Wctx   = office365Login,
                    Wreply = _host.GetLeftPart(UriPartial.Authority) + "/_forms/default.aspx?wa=wsignin1.0"
                };

                //get token from STS
                string stsResponse = getResponse(office365STS, sharepointSite.Wreply);

                // parse the token response
                XDocument doc = XDocument.Parse(stsResponse);

                // get the security token
                var crypt = from result in doc.Descendants()
                            where result.Name == XName.Get("BinarySecurityToken", wsse)
                            select result;

                // get the token expiration
                var expires = from result in doc.Descendants()
                              where result.Name == XName.Get("Expires", wsu)
                              select result;
                ret.Expires = Convert.ToDateTime(expires.First().Value);


                HttpWebRequest request = createRequest(sharepointSite.Wreply);
                byte[]         data    = Encoding.UTF8.GetBytes(crypt.FirstOrDefault().Value);
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                    stream.Close();

                    using (HttpWebResponse webResponse = request.GetResponse() as HttpWebResponse)
                    {
                        // Handle redirect, added may 2011 for P-subscriptions
                        if (webResponse.StatusCode == HttpStatusCode.MovedPermanently)
                        {
                            HttpWebRequest request2 = createRequest(webResponse.Headers["Location"]);
                            using (Stream stream2 = request2.GetRequestStream())
                            {
                                stream2.Write(data, 0, data.Length);
                                stream2.Close();

                                using (HttpWebResponse webResponse2 = request2.GetResponse() as HttpWebResponse)
                                {
                                    ret.FedAuth = webResponse2.Cookies["FedAuth"].Value;
                                    ret.rtFa    = webResponse2.Cookies["rtFa"].Value;
                                    ret.Host    = request2.RequestUri;
                                }
                            }
                        }
                        else
                        {
                            ret.FedAuth = webResponse.Cookies["FedAuth"].Value;
                            ret.rtFa    = webResponse.Cookies["rtFa"].Value;
                            ret.Host    = request.RequestUri;
                        }
                    }
                }
            }
            catch (Exception)
            {
                return(null);
            }
            return(ret);
        }
Esempio n. 18
0
		HttpResponseMessage CreateResponseMessage (HttpWebResponse wr, HttpRequestMessage requestMessage, CancellationToken cancellationToken)
		{
			var response = new HttpResponseMessage (wr.StatusCode);
			response.RequestMessage = requestMessage;
			response.ReasonPhrase = wr.StatusDescription;
			response.Content = new StreamContent (wr.GetResponseStream (), cancellationToken);

			var headers = wr.Headers;
			for (int i = 0; i < headers.Count; ++i) {
				var key = headers.GetKey(i);
				var value = headers.GetValues (i);

				HttpHeaders item_headers;
				if (HttpHeaders.GetKnownHeaderKind (key) == Headers.HttpHeaderKind.Content)
					item_headers = response.Content.Headers;
				else
					item_headers = response.Headers;
					
				item_headers.TryAddWithoutValidation (key, value);
			}

			requestMessage.RequestUri = wr.ResponseUri;

			return response;
		}
Esempio n. 19
0
 public void updateCookies(HttpWebResponse _webResponse)
 {
     localCookie.Add(_webResponse.Cookies);
 }
Esempio n. 20
0
    private void OnPostResponse(IAsyncResult asyncResult)
    {
        responseReceived = true;
        Debug.Log("OnPostResponse");
        byte[] imageBuffer = new byte[1024 * 1024];

        Debug.Log("Starting request");
        // get the response
        HttpWebRequest req = (HttpWebRequest)asyncResult.AsyncState;

        try
        {
            Debug.Log("OnPostResponse try entered.");
            HttpWebResponse resp = (HttpWebResponse)req.EndGetResponse(asyncResult);
            Debug.Log("response received");
            // find our magic boundary value
            string contentType = resp.Headers["Content-Type"];
            if (!string.IsNullOrEmpty(contentType) && !contentType.Contains("="))
            {
                Debug.Log("MJPEG Exception thrown");
                throw new Exception("Invalid content-type header.  The camera is likely not returning a proper MJPEG stream.");
            }

            string boundary      = resp.Headers["Content-Type"].Split('=')[1].Replace("\"", "");
            byte[] boundaryBytes = Encoding.UTF8.GetBytes(boundary.StartsWith("--") ? boundary : "--" + boundary);

            Stream       s  = resp.GetResponseStream();
            BinaryReader br = new BinaryReader(s);

            _streamActive = true;
            byte[] buff = br.ReadBytes(_chunkSize);

            while (_streamActive)
            {
                // find the JPEG header
                int imageStart = FindBytes(buff, jpegHeader);// buff.Find(jpegHeader);

                if (imageStart != -1)
                {
                    // copy the start of the JPEG image to the imageBuffer
                    int size = buff.Length - imageStart;
                    Array.Copy(buff, imageStart, imageBuffer, 0, size);

                    while (true)
                    {
                        buff = br.ReadBytes(_chunkSize);

                        // Find the end of the jpeg
                        int imageEnd = FindBytes(buff, boundaryBytes);
                        if (imageEnd != -1)
                        {
                            // copy the remainder of the JPEG to the imageBuffer
                            Array.Copy(buff, 0, imageBuffer, size, imageEnd);
                            size += imageEnd;

                            // Copy the latest frame into `CurrentFrame`
                            byte[] frame = new byte[size];
                            Array.Copy(imageBuffer, 0, frame, 0, size);
                            currentFrame = frame;

                            // tell whoever's listening that we have a frame to draw
                            if (FrameReady != null)
                            {
                                FrameReady(this, new FrameReadyEventArgs());
                            }
                            // copy the leftover data to the start
                            Array.Copy(buff, imageEnd, buff, 0, buff.Length - imageEnd);

                            // fill the remainder of the buffer with new data and start over
                            byte[] temp = br.ReadBytes(imageEnd);

                            Array.Copy(temp, 0, buff, buff.Length - imageEnd, temp.Length);
                            break;
                        }

                        // copy all of the data to the imageBuffer
                        Array.Copy(buff, 0, imageBuffer, size, buff.Length);
                        size += buff.Length;

                        if (!_streamActive)
                        {
                            Debug.Log("CLOSING");
                            resp.Close();
                            break;
                        }
                    }
                }
            }
            resp.Close();
        }
        catch (Exception ex)
        {
            if (Error != null)
            {
                _context.Post(delegate { Error(this, new ErrorEventArgs()
                    {
                        Message = ex.Message
                    }); }, null);
            }
            Debug.Log("retrying");
            //ParseStream(lastUri, lastUsername, lastPassword);
            return;
        }
    }
        /// <summary>
        /// Direct implementation of client APIs to string values
        /// </summary>
        /// <param name="verb"></param>
        /// <param name="relativePath"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        private FileResult RestCallFile(string verb, AvaTaxPath relativePath, object content = null)
        {
            string path        = CombinePath(_envUri.ToString(), relativePath.ToString());
            string jsonPayload = null;

            // Use HttpWebRequest so we can get a decent response
            var wr = (HttpWebRequest)WebRequest.Create(path);

            wr.Proxy = null;

            // Add headers
            foreach (var key in _clientHeaders.Keys)
            {
                wr.Headers.Add(key, _clientHeaders[key]);
            }

            // Convert the name-value pairs into a byte array
            wr.Method = verb;
            if (content != null)
            {
                wr.ContentType = Constants.JSON_MIME_TYPE;
                wr.ServicePoint.Expect100Continue = false;

                // Encode the payload
                jsonPayload = JsonConvert.SerializeObject(content, SerializerSettings);
                var    encoding = new UTF8Encoding();
                byte[] data     = encoding.GetBytes(jsonPayload);
                wr.ContentLength = data.Length;

                // Call the server
                using (var s = wr.GetRequestStream()) {
                    s.Write(data, 0, data.Length);
                    s.Close();
                }
            }

            // Transmit, and get back the response, save it to a temp file
            try {
                using (var response = wr.GetResponse()) {
                    using (var inStream = response.GetResponseStream()) {
                        const int BUFFER_SIZE = 1024;
                        var       chunks      = new List <byte>();
                        var       totalBytes  = 0;
                        var       bytesRead   = 0;

                        do
                        {
                            var buffer = new byte[BUFFER_SIZE];
                            bytesRead = inStream.Read(buffer, 0, BUFFER_SIZE);
                            if (bytesRead == BUFFER_SIZE)
                            {
                                chunks.AddRange(buffer);
                            }
                            else
                            {
                                for (int i = 0; i < bytesRead; i++)
                                {
                                    chunks.Add(buffer[i]);
                                }
                            }
                            totalBytes += bytesRead;
                        } while (bytesRead > 0);

                        if (totalBytes <= 0)
                        {
                            throw new IOException("Response contained no data");
                        }

                        // Here's your file result
                        var fr = new FileResult()
                        {
                            ContentType = response.Headers["Content-Type"].ToString(),
                            Filename    = GetDispositionFilename(response.Headers["Content-Disposition"].ToString()),
                            Data        = chunks.ToArray()
                        };

                        // Track the API call
                        var eventargs = new AvaTaxCallEventArgs()
                        {
                            Code = ((HttpWebResponse)response).StatusCode, Duration = null, HttpVerb = wr.Method, RequestBody = jsonPayload, ResponseBody = fr.Data, RequestUri = new Uri(path)
                        };
                        OnCallCompleted(eventargs);
                        return(fr);
                    }
                }

                // Catch a web exception
            } catch (WebException webex) {
                HttpWebResponse httpWebResponse = webex.Response as HttpWebResponse;
                if (httpWebResponse != null)
                {
                    using (Stream stream = httpWebResponse.GetResponseStream()) {
                        using (StreamReader reader = new StreamReader(stream)) {
                            var errString = reader.ReadToEnd();

                            // Track the API call
                            var eventargs = new AvaTaxCallEventArgs()
                            {
                                Code = ((HttpWebResponse)httpWebResponse).StatusCode, Duration = null, HttpVerb = wr.Method, RequestBody = jsonPayload, ResponseString = errString, RequestUri = new Uri(path)
                            };
                            OnCallCompleted(eventargs);

                            // Pass on the error
                            var err = JsonConvert.DeserializeObject <ErrorResult>(errString);
                            throw new AvaTaxError(err, httpWebResponse.StatusCode);
                        }
                    }
                }

                // If we can't parse it as an AvaTax error, just throw
                throw webex;
            }
        }
        public void Authorize(Pusher pusher, Action <object> callback)
        {
            JsonData data;

            if (IsPrivate)
            {
                if (string.IsNullOrWhiteSpace(Pusher.channel_auth_endpoint))
                {
                    throw new InvalidOperationException("Pusher.channel_auth_endpoint must be set to authorize a channel");
                }

                string url = Pusher.channel_auth_endpoint + "?socket_id=" + pusher.socket_id + "&channel_name=" + this.name;

                AutoResetEvent downloadedEvent = new AutoResetEvent(false);
                string         response        = string.Empty;

                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.Method      = "POST";
                    request.Accept      = "application/json";
                    request.ContentType = "application/x-www-form-urlencoded";

                    bool supportsCookieContainer = true;
#if SILVERLIGHT
                    supportsCookieContainer = request.SupportsCookieContainer;
#endif
                    if (Pusher.AuthCookieContainer != null && supportsCookieContainer)
                    {
                        request.CookieContainer = Pusher.AuthCookieContainer;
                    }

                    request.BeginGetResponse(delegate(IAsyncResult asynchronousResult)
                    {
                        HttpWebResponse resp = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                        Stream stream        = resp.GetResponseStream();
                        var sr   = new StreamReader(stream);
                        response = sr.ReadToEnd();
                        downloadedEvent.Set();
                    }, null);

                    bool triggered = downloadedEvent.WaitOne(Pusher.connection_timeout);
                    if (!triggered)
                    {
                        Pusher.Log("Auth call timed out after {0} milliseconds", Pusher.connection_timeout);
                        data = new JsonData();
                    }
                    else
                    {
                        data = (JsonData)Pusher.Parser(response);
                    }
                }
                catch (Exception ex)
                {
                    Pusher.Log("Exception occurred in Auth call. {0}", ex);
                    data = new JsonData();
                }
            }
            else
            {
                data = new JsonData();
            }
            callback(data);
        }
Esempio n. 23
0
        /// <summary>
        /// Web Request Wrapper
        /// </summary>
        /// <param name="method">Http Method</param>
        /// <param name="url">Full url to the web resource</param>
        /// <param name="postData">Data to post in querystring format</param>
        /// <returns>The web server response.</returns>
        public string WebRequestWithPut(Method method, string url, string postData)
        {

            //oauth_consumer_key=5s5OSkySDF_mG_dLkduT3l7gokQ68hBtEpY5a9ebJVDH2r5BG8Opb6mUQhPgmQEB
            //oauth_nonce=9708457
            //oauth_signature_method=HMAC-SHA1
            //oauth_timestamp=1259135648
            //oauth_token=387026c7-27bd-4a11-b76e-fbe052ce88ad
            //oauth_verifier=31838
            //oauth_version=1.0
            //oauth_signature=4wYKoBy4ndrR4ziDNTd5mQV%2fcLY%3d

            //url = "http://api.linkedin.com/v1/people/~/current-status";
            Uri uri = new Uri(url);

            string nonce = this.GenerateNonce();
            string timeStamp = this.GenerateTimeStamp();

            string outUrl, querystring;

            //Generate Signature
            string sig = this.GenerateSignatureBase(uri,
                this.ConsumerKey,
                this.ConsumerSecret,
                this.Token,
                this.TokenSecret,
                "PUT",
                timeStamp,
                nonce,
                out outUrl,
                out querystring);

            querystring += "&oauth_signature=" + HttpUtility.UrlEncode(sig);
            NameValueCollection qs = HttpUtility.ParseQueryString(querystring);
            string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
            xml += "<current-status>is setting their status using the LinkedIn API.</current-status>";

            HttpWebRequest webRequest = null;
            string responseData = "";

            webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
            webRequest.ContentType = "text/xml";
            webRequest.Method = "PUT";
         
            webRequest.ServicePoint.Expect100Continue = false;

            webRequest.Headers.Add("Authorization", "OAuth realm=\"\"");
            webRequest.Headers.Add("oauth_consumer_key", this.ConsumerKey);
            webRequest.Headers.Add("oauth_token", this.Token);
            webRequest.Headers.Add("oauth_signature_method", "HMAC-SHA1");
            webRequest.Headers.Add("oauth_signature", sig);
            webRequest.Headers.Add("oauth_timestamp", timeStamp);
            webRequest.Headers.Add("oauth_nonce", nonce);
            webRequest.Headers.Add("oauth_verifier", this.Verifier);
            webRequest.Headers.Add("oauth_version", "1.0");

            //webRequest.KeepAlive = true;

            StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
            try
            {
                requestWriter.Write(postData);
            }
            catch
            {
                throw;
            }
            finally
            {
                requestWriter.Close();
                requestWriter = null;
            }


            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            string returnString = response.StatusCode.ToString();

            webRequest = null;

            return responseData;

        }
Esempio n. 24
0
    public WebReq(string _siteName, getPost _opType, Connection _connection, bool _silent = true, string _strBuffer = "")
    {
        HttpWebRequest localRequest;
        string requestMethod;

        hostSiteName = _siteName;
        currentRequest = _opType;
        formConnection = _connection;

        switch (currentRequest)
        {
            case getPost.get:
                webRequestGET = (HttpWebRequest)WebRequest.Create(_siteName);
                requestMethod = "GET";
                localRequest = webRequestGET;
                break;
            case getPost.post:
                webRequestPOST = (HttpWebRequest)WebRequest.Create(_siteName);
                requestMethod = "POST";
                localRequest = webRequestPOST;
                break;
            default:
                localRequest = null;
                requestMethod = "";
                break;
        }
        localRequest.ContentType = "application/x-www-form-urlencoded";
        localRequest.Method = requestMethod;
        addCookie(localRequest, formConnection);

        if (_strBuffer.Length != 0 && currentRequest == getPost.post)
        {
            byte[] buffer = Encoding.ASCII.GetBytes(_strBuffer);
            localRequest.ContentLength = buffer.Length;
            Stream PostData = localRequest.GetRequestStream();
            PostData.Write(buffer, 0, buffer.Length);
            PostData.Close();
        }
        webResponse = (HttpWebResponse)localRequest.GetResponse();
        Answer = webResponse.GetResponseStream();
    }
Esempio n. 25
0
                /// <summary>
                /// ���N�G�X�g�ɑ΂��郌�X�|���X��擾���܂��B
                /// </summary>
                /// <returns></returns>
                protected internal HttpWebResponse getResponse()
                {
                    HttpWebResponse res = (HttpWebResponse)this.webReq.GetResponse();
                    SimpleLogger.WriteLine("[ Response ] ---------------------------------------");
                    SimpleLogger.WriteLine("Status: " + (int)res.StatusCode + " " + res.StatusCode.ToString());
                    SimpleLogger.WriteLine(res.Headers.ToString().Replace("\n\r", Environment.NewLine));

                    //��M����Cookie�̃R���N�V������擾����
                    if (this.webReq.CookieContainer != null && this.webReq.CookieContainer.GetCookies(this.webReq.RequestUri).Count > 0)
                    {
                        SimpleLogger.Write( "Cookies: { " );
                        // Cookie�������Cookie���ƒl��񋓂���
                        foreach (Cookie cook in this.webReq.CookieContainer.GetCookies(this.webReq.RequestUri))
                        {
                            SimpleLogger.Write("{0}=\"{1}\"; ", cook.Name, cook.Value);
                        }
                        SimpleLogger.Write("}" + Environment.NewLine);
                        //�擾����Cookie��ۑ����Ă���
                        //this.cc.Add(this.webReq.CookieContainer.GetCookies(this.webReq.RequestUri));
                        this.cc = this.webReq.CookieContainer;
                        res.Cookies = this.webReq.CookieContainer.GetCookies(this.webReq.RequestUri);
                    }
                    SimpleLogger.WriteLine("----------------------------------------------------");

                    Stream resStream = res.GetResponseStream();
                    StreamReader sr = new StreamReader(resStream, enc);
                    this.resString = sr.ReadToEnd();
                    sr.Close();
                    resStream.Close();

                    this.webRes = res;
                    res.Close();

                    return this.webRes;
                }
    /// <summary>
    /// Set status of URL check.
    /// </summary>
    /// <param name="response">Web response to obtain data about URL</param>
    /// <returns>URL status text</returns>
    private string SetStatusText(HttpWebResponse response)
    {
        if ((response == null) || (response.StatusCode == HttpStatusCode.OK))
        {
            return SetStatusText();
        }

        // If web response is available, obtain status from that
        string errorText = GetErrorText("Response status code: " + response.StatusCode, response.StatusDescription);
        return SetStatusText(errorText);
    }
        /// <summary>
        /// Direct implementation of client APIs to string values
        /// </summary>
        /// <param name="verb"></param>
        /// <param name="relativePath"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        private string RestCallString(string verb, AvaTaxPath relativePath, object content = null)
        {
            string path        = CombinePath(_envUri.ToString(), relativePath.ToString());
            string jsonPayload = null;

            // Use HttpWebRequest so we can get a decent response
            var wr = (HttpWebRequest)WebRequest.Create(path);

            wr.Proxy = null;

            // Add headers
            foreach (var key in _clientHeaders.Keys)
            {
                wr.Headers.Add(key, _clientHeaders[key]);
            }

            // Convert the name-value pairs into a byte array
            wr.Method        = verb;
            wr.ContentLength = 0;
            if (content != null)
            {
                wr.ContentType = Constants.JSON_MIME_TYPE;
                wr.ServicePoint.Expect100Continue = false;

                // Encode the payload
                jsonPayload = JsonConvert.SerializeObject(content, SerializerSettings);
                var    encoding = new UTF8Encoding();
                byte[] data     = encoding.GetBytes(jsonPayload);
                wr.ContentLength = data.Length;

                // Call the server
                using (var s = wr.GetRequestStream()) {
                    s.Write(data, 0, data.Length);
                    s.Close();
                }
            }

            // Transmit, and get back the response, save it to a temp file
            try {
                using (var response = wr.GetResponse()) {
                    using (var inStream = response.GetResponseStream()) {
                        using (var reader = new StreamReader(inStream)) {
                            var responseString = reader.ReadToEnd();

                            // Track the API call
                            var eventargs = new AvaTaxCallEventArgs()
                            {
                                Code = ((HttpWebResponse)response).StatusCode, Duration = null, HttpVerb = wr.Method, RequestBody = jsonPayload, ResponseString = responseString, RequestUri = new Uri(path)
                            };
                            OnCallCompleted(eventargs);

                            // Here's the results
                            return(responseString);
                        }
                    }
                }

                // Catch a web exception
            } catch (WebException webex) {
                HttpWebResponse httpWebResponse = webex.Response as HttpWebResponse;
                if (httpWebResponse != null)
                {
                    using (Stream stream = httpWebResponse.GetResponseStream()) {
                        using (StreamReader reader = new StreamReader(stream)) {
                            var errString = reader.ReadToEnd();

                            // Track the API call
                            var eventargs = new AvaTaxCallEventArgs()
                            {
                                Code = ((HttpWebResponse)httpWebResponse).StatusCode, Duration = null, HttpVerb = wr.Method, RequestBody = jsonPayload, ResponseString = errString, RequestUri = new Uri(path)
                            };
                            OnCallCompleted(eventargs);

                            // Here's the results
                            var err = JsonConvert.DeserializeObject <ErrorResult>(errString);
                            throw new AvaTaxError(err, httpWebResponse.StatusCode);
                        }
                    }
                }

                // If we can't parse it as an AvaTax error, just throw
                throw webex;
            }
        }
 /// <summary>
 /// Sets the response when received from the underlying HttpWebRequest
 /// </summary>
 /// <param name="webResponse">The response recieved.</param>
 private void SetHttpWebResponse(HttpWebResponse webResponse)
 {
     Debug.Assert(webResponse != null, "Can't set a null response.");
     this.response = webResponse;
 }
 private static void CopyResponseStream(HttpContext context, HttpWebResponse res)
 {
     //Copy response data or redirect
     context.Response.StatusCode = (int)res.StatusCode;
     using (var resStream = res.GetResponseStream())
     {
         if (string.IsNullOrEmpty(res.CharacterSet)) // Binary response (image)
         {
             var resBytes = new byte[res.ContentLength];
             resStream.Read(resBytes, 0, resBytes.Length);
             context.Response.OutputStream.Write(resBytes, 0, resBytes.Length);
         }
         else
         {
             var enc = Encoding.GetEncoding(res.CharacterSet); // text response
             using (var rd = new System.IO.StreamReader(resStream))
             {
                 var resString = rd.ReadToEnd();
                 context.Response.Output.Write(resString);
             }
         }
     }
 }
        private static (List <dynamic> list, ReturnCode statusCode) ResolveOverHttps(string clientIpAddress, string domainName, string dohUrl,
                                                                                     bool proxyEnable = false, IWebProxy wProxy = null, RecordType type = RecordType.A)
        {
            string         dnsStr;
            List <dynamic> recordList = new List <dynamic>();

            using (MWebClient webClient = new MWebClient())
            {
                webClient.Headers["User-Agent"] = "AuroraDNSC/0.1";

//                webClient.AllowAutoRedirect = false;

                if (proxyEnable)
                {
                    webClient.Proxy = wProxy;
                }

                try
                {
                    dnsStr = webClient.DownloadString(dohUrl + @"?ct=application/dns-json&" +
                                                      $"name={domainName}&type={type.ToString().ToUpper()}&edns_client_subnet={clientIpAddress}");
                }
                catch (WebException e)
                {
                    HttpWebResponse response = (HttpWebResponse)e.Response;
                    try
                    {
                        BgwLog($@"| - Catch WebException : {Convert.ToInt32(response.StatusCode)} {response.StatusCode} | {domainName} | {dohUrl}");
                    }
                    catch (Exception exception)
                    {
                        BgwLog($@"| - Catch WebException : {exception.Message} | {domainName} | {dohUrl}");

                        //MainWindow.NotifyIcon.ShowBalloonTip(360, "AuroraDNS - 错误",
                        //    $"异常 : {exception.Message} {Environment.NewLine} {domainName}", ToolTipIcon.Warning);
                    }

                    if (dohUrl == DnsSettings.HttpsDnsUrl)
                    {
                        BgwLog($@"| -- SecondDoH : {DnsSettings.SecondHttpsDnsUrl}");
                        return(ResolveOverHttps(clientIpAddress, domainName, DnsSettings.SecondHttpsDnsUrl,
                                                proxyEnable, wProxy, type));
                    }

                    return(new List <dynamic>(), ReturnCode.ServerFailure);
                }
            }

            JsonValue dnsJsonValue = Json.Parse(dnsStr);

            int statusCode = dnsJsonValue.AsObjectGetInt("Status");

            if (statusCode != 0)
            {
                return(new List <dynamic>(), (ReturnCode)statusCode);
            }

            if (dnsStr.Contains("\"Answer\""))
            {
                var dnsAnswerJsonList = dnsJsonValue.AsObjectGetArray("Answer");

                foreach (var itemJsonValue in dnsAnswerJsonList)
                {
                    string answerAddr       = itemJsonValue.AsObjectGetString("data");
                    string answerDomainName = itemJsonValue.AsObjectGetString("name");
                    int    answerType       = itemJsonValue.AsObjectGetInt("type");
                    int    ttl = itemJsonValue.AsObjectGetInt("TTL");

                    switch (type)
                    {
                    case RecordType.A:
                    {
                        if (Convert.ToInt32(RecordType.A) == answerType)
                        {
                            ARecord aRecord = new ARecord(
                                DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr));

                            recordList.Add(aRecord);
                        }
                        else if (Convert.ToInt32(RecordType.CName) == answerType)
                        {
                            CNameRecord cRecord = new CNameRecord(
                                DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));

                            recordList.Add(cRecord);

                            //recordList.AddRange(ResolveOverHttps(clientIpAddress,answerAddr));
                            //return recordList;
                        }

                        break;
                    }

                    case RecordType.Aaaa:
                    {
                        if (Convert.ToInt32(RecordType.Aaaa) == answerType)
                        {
                            AaaaRecord aaaaRecord = new AaaaRecord(
                                DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr));
                            recordList.Add(aaaaRecord);
                        }
                        else if (Convert.ToInt32(RecordType.CName) == answerType)
                        {
                            CNameRecord cRecord = new CNameRecord(
                                DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                            recordList.Add(cRecord);
                        }
                        break;
                    }

                    case RecordType.CName when answerType == Convert.ToInt32(RecordType.CName):
                    {
                        CNameRecord cRecord = new CNameRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(cRecord);
                        break;
                    }

                    case RecordType.Ns when answerType == Convert.ToInt32(RecordType.Ns):
                    {
                        NsRecord nsRecord = new NsRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(nsRecord);
                        break;
                    }

                    case RecordType.Mx when answerType == Convert.ToInt32(RecordType.Mx):
                    {
                        MxRecord mxRecord = new MxRecord(
                            DomainName.Parse(answerDomainName), ttl,
                            ushort.Parse(answerAddr.Split(' ')[0]),
                            DomainName.Parse(answerAddr.Split(' ')[1]));
                        recordList.Add(mxRecord);
                        break;
                    }

                    case RecordType.Txt when answerType == Convert.ToInt32(RecordType.Txt):
                    {
                        TxtRecord txtRecord = new TxtRecord(DomainName.Parse(answerDomainName), ttl, answerAddr);
                        recordList.Add(txtRecord);
                        break;
                    }

                    case RecordType.Ptr when answerType == Convert.ToInt32(RecordType.Ptr):
                    {
                        PtrRecord ptrRecord = new PtrRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(ptrRecord);
                        break;
                    }

                    default:
                    {
                        statusCode = Convert.ToInt32(ReturnCode.ServerFailure);
                        break;
                    }
                    }
                }
            }

            return(recordList, (ReturnCode)statusCode);
        }
Esempio n. 31
0
        /// <summary>
        /// This is the asynchronous job handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void jobWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // Now hook up asynchronous job eventhandlers to the right connectors
            // We do the unassign first to make sure we don't get two handles
            // -= can safely be called even when it doesn't exist
            LoggerHandler += new EventHandler <string>(loggerhandler);

            SetVisible(btnCancel, true);
            SetEnabled(btnCancel, false);
            SetEnabled(btnUpload, false);
            SetEnabled(btnDelete, false);
            try
            {
                // First zip up the contents of the folder and put them somewhere:
                SendLogMessage(String.Format("{0} Making temporary zip file...", Environment.NewLine));
                DirectoryInfo gcdprojpath = GCDCore.Project.ProjectManager.Project.ProjectFile.Directory;
                FileInfo      tempzipfile = new FileInfo(Path.GetTempPath() + Guid.NewGuid().ToString() + ".zip");

                List <string> files = Directory.GetFiles(gcdprojpath.FullName, "*", SearchOption.AllDirectories).ToList();

                //Creates a new, blank zip file to work with - the file will be
                //finalized when the using statement completes
                using (ZipArchive zfile = ZipFile.Open(tempzipfile.FullName, ZipArchiveMode.Create))
                {
                    // CompressionLevel.BestCompression
                    foreach (string abspath in files)
                    {
                        string relPath = MakeRelativePath(gcdprojpath.FullName, abspath);
                        // Rename the project file so we can find it easily online
                        if (relPath.EndsWith(".gcd") && !relPath.Contains(Path.DirectorySeparatorChar))
                        {
                            relPath = "project.gcd";
                        }
                        // We normalize the slashes here to make things easier for linux to deal with
                        zfile.CreateEntryFromFile(abspath, relPath.Replace(Path.DirectorySeparatorChar, '/'));
                    }
                }
                SendLogMessage(String.Format("created."));

                // Now get and store the credentials we need to upload directly to S3
                SendLogMessage(String.Format("{0} Retrieving upload url...", Environment.NewLine));
                APIReturn jsonret;
                using (WebClient wcreq = new WebClient())
                {
                    wcreq.Headers["x-api-key"] = APIKEY;
                    string jsonString;
                    if (GCDCore.Project.ProjectManager.Project.OnlineParams.ContainsKey("GCDUUID"))
                    {
                        // This is actually an overwrite
                        wcreq.Headers["GCDAUTH"] = GCDCore.Project.ProjectManager.Project.OnlineParams["PubKey"];
                        jsonString = wcreq.UploadString(String.Format("{0}/project/{1}", GCDCore.Properties.Resources.UploadAPIUrl,
                                                                      GCDCore.Project.ProjectManager.Project.OnlineParams["GCDUUID"]), "POST", "");
                    }
                    // This is a new project. Upload as per usual
                    else
                    {
                        jsonString = wcreq.UploadString(String.Format("{0}/project/new", GCDCore.Properties.Resources.UploadAPIUrl), "POST", "");
                    }

                    jsonret = JsonConvert.DeserializeObject <APIReturn>(jsonString);
                    SendLogMessage(String.Format("retrieved."));
                }

                // Upload the file to S3
                SendLogMessage(String.Format("{0} Uploading zip...", Environment.NewLine));

                // Read file data
                FileStream fs   = new FileStream(tempzipfile.FullName, FileMode.Open, FileAccess.Read);
                byte[]     data = new byte[fs.Length];
                fs.Read(data, 0, data.Length);
                fs.Close();

                // Generate post objects by first adding in all the fields we got back from S3 then the binary data
                Dictionary <string, object> postParameters = new Dictionary <string, object>();
                foreach (KeyValuePair <string, string> kvp in jsonret.upload_fields.fields)
                {
                    postParameters.Add(kvp.Key, kvp.Value);
                }
                postParameters.Add("file", new FormUpload.FileParameter(data, "project.zip", "application/zip"));

                // Create request and receive response
                FormUpload fUp = new FormUpload();
                using (HttpWebResponse webResponse = fUp.MultipartFormDataPost(jsonret.upload_fields.url, "Someone", postParameters))
                {
                    // from: https://stackoverflow.com/questions/20726797/showing-progress-in-percentage-while-uploading-and-downloading-using-httpwebrequhttps://stackoverflow.com/questions/20726797/showing-progress-in-percentage-while-uploading-and-downloading-using-httpwebrequhttps://stackoverflow.com/questions/20726797/showing-progress-in-percentage-while-uploading-and-downloading-using-httpwebrequhttps://stackoverflow.com/questions/20726797/showing-progress-in-percentage-while-uploading-and-downloading-using-httpwebrequhttps://stackoverflow.com/questions/20726797/showing-progress-in-percentage-while-uploading-and-downloading-using-httpwebrequhttps://stackoverflow.com/questions/20726797/showing-progress-in-percentage-while-uploading-and-downloading-using-httpwebrequhttps://stackoverflow.com/questions/20726797/showing-progress-in-percentage-while-uploading-and-downloading-using-httpwebrequhttps://stackoverflow.com/questions/20726797/showing-progress-in-percentage-while-uploading-and-downloading-using-httpwebrequhttps://stackoverflow.com/questions/20726797/showing-progress-in-percentage-while-uploading-and-downloading-using-httpwebrequhttps://stackoverflow.com/questions/20726797/showing-progress-in-percentage-while-uploading-and-downloading-using-httpwebrequhttps://stackoverflow.com/questions/20726797/showing-progress-in-percentage-while-uploading-and-downloading-using-httpwebrequhttps://stackoverflow.com/questions/20726797/showing-progress-in-percentage-while-uploading-and-downloading-using-httpwebrequ
                    // Allocate space for the content
                    // Process response
                    StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());

                    //var readdata = new byte[fUp.contentLength];
                    //int currentIndex = 0;
                    //int bytesReceived = 0;
                    var buffer = new char[256];
                    //do
                    //{
                    //    bytesReceived = responseReader.Read(buffer, 0, 256);
                    //    //Array.Copy(buffer, 0, readdata, currentIndex, bytesReceived);
                    //    currentIndex += bytesReceived;

                    //    // Report percentage
                    //    double percentage = (double)currentIndex / fUp.contentLength;
                    //    jobWorker.ReportProgress((int)(percentage * 100));
                    //} while (currentIndex < fUp.contentLength);

                    jobWorker.ReportProgress(100);
                    //string fullResponse = responseReader.ReadToEnd();
                    webResponse.Close();
                }

                // Now set the response values so we can find them later
                GCDCore.Project.ProjectManager.Project.OnlineParams["GCDUUID"] = jsonret.uuid;
                GCDCore.Project.ProjectManager.Project.OnlineParams["PubKey"]  = jsonret.pubKey;

                // Clean up the temporary file
                SendLogMessage(String.Format("{0} Cleaning up...", Environment.NewLine));
                tempzipfile.Refresh();
                if (tempzipfile.Exists)
                {
                    tempzipfile.Delete();
                }
                SendLogMessage(String.Format("done!"));
                GCDCore.Project.ProjectManager.Project.Save();
                SendLogMessage(String.Format("{0} Process Complete", Environment.NewLine));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(String.Format("EXCEPTION: {0}", ex.Message));
            }
            // Report something having changed.
            RecalcState();
        }
Esempio n. 32
0
        public HttpWebResponse MakeRequest(string parameters)
        {
            var             request  = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
            HttpWebResponse response = null;

            request.Method        = Method.ToString();
            request.ContentLength = 0;
            request.ContentType   = ContentType;
            request.Timeout       = 60000;
            request.ServicePoint.Expect100Continue = false;

            if (SessionCookie != null)
            {
                request.Headers.Add(HttpRequestHeader.Cookie, SessionCookie);
            }

            if (!string.IsNullOrEmpty(PostData) && (Method == HttpVerb.POST || Method == HttpVerb.PUT))
            {
                var encoding = new UTF8Encoding();
                var bytes    = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
                request.ContentLength = bytes.Length;

                try
                {
                    using (var writeStream = request.GetRequestStream())
                    {
                        writeStream.Write(bytes, 0, bytes.Length);
                    }
                }
                catch (WebException ex)
                {
                    st.insertLog("Error: " + ex.Message, "Exception Error", "", HillerServiceDataMigrator.LogId);
                    //log.Error("Error: " + ex.Message, ex);
                }
            }


            //   st.insertLog("Json Data: " + PostData, "Info", "", HillerServiceDataMigrator.LogId);

            try
            {
                response = (HttpWebResponse)request.GetResponse();

                //   st.insertLog("HttpWebResponse " + response.Headers.ToString(), "Info", "", HillerServiceDataMigrator.LogId);
                //log.Debug("HttpWebResponse " + response.Headers.ToString());
                //  st.insertLog("HTTPStatusCode: " + response.StatusCode.ToString(), "Info", "", HillerServiceDataMigrator.LogId);
                //log.Debug("HTTPStatusCode: " + response.StatusCode.ToString());
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message             = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                    ApplicationException ex = new ApplicationException(message);

                    st.insertLog(message, "Exception Error", "", HillerServiceDataMigrator.LogId);

                    //   log.Error(message, ex);
                    return(null);
                }
            }
            catch (Exception ex)
            {
                st.insertLog("Error: " + ex.Message, "Exception Error", "", HillerServiceDataMigrator.LogId);
                // log.Error("Error: "+ex.Message, ex);
            }

            return(response);
        }
 public WebException(string message, Exception innerException, HttpWebResponse response)
     : base(message, innerException)
 {
     this.response = response;
 }
Esempio n. 34
0
        /// <summary>
        /// 通过Post方式请求
        /// </summary>
        /// <param name="url">Url</param>
        /// <param name="PostData">参数</param>
        /// <param name="timeout">超时时间</param>
        /// <param name="userAgent"></param>
        /// <param name="referer">引用页</param>
        /// <param name="requestEncoding">编码</param>
        /// <param name="cookies">CookieContainer</param>
        /// <param name="proxy">代理</param>
        /// <param name="returl">返回请求的Url</param>
        /// <returns></returns>
        public string PostHttpResponse(string url, string PostData, int?timeout, string userAgent, string referer, Encoding requestEncoding, ref CookieContainer cookies, WebProxy proxy, out string returl)
        {
            returl = "";

            try
            {
                if (string.IsNullOrEmpty(url))
                {
                    throw new ArgumentNullException("url");
                }

                if (requestEncoding == null)
                {
                    throw new ArgumentNullException("requestEncoding");
                }

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

                ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;

                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded";

                if (proxy != null)
                {
                    request.Proxy = proxy;
                }

                if (!string.IsNullOrEmpty(userAgent))
                {
                    request.UserAgent = userAgent;
                }

                else
                {
                    request.UserAgent = DefaultUserAgent;
                }

                if (timeout.HasValue)
                {
                    request.Timeout = timeout.Value;
                }

                if (cookies != null)
                {
                    request.CookieContainer = cookies;
                }

                if (referer != null)
                {
                    request.Referer = referer;
                }

                //如果需要POST数据
                if (PostData != null)
                {
                    byte[] data = requestEncoding.GetBytes(PostData);
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();

                if (httpWebResponse.CharacterSet != null)
                {
                    requestEncoding = Encoding.GetEncoding(httpWebResponse.CharacterSet);
                }

                this.responseEncoding = requestEncoding;

                Stream       responseStream = httpWebResponse.GetResponseStream();
                StreamReader streamReader   = new StreamReader(responseStream, requestEncoding);
                string       html           = streamReader.ReadToEnd();

                foreach (Cookie cookie in httpWebResponse.Cookies)
                {
                    cookies.Add(cookie);
                }

                returl = httpWebResponse.ResponseUri.ToString();

                streamReader.Close();
                responseStream.Close();
                request.Abort();
                httpWebResponse.Close();

                return(html);
            }
            catch (Exception er)
            {
                return(er.Message);
            }
        }
Esempio n. 35
0
        /// <summary>
        /// 建立请求,以模拟远程HTTP的POST请求方式构造并获取支付宝的处理结果,带文件上传功能
        /// </summary>
        /// <param name="sParaTemp">请求参数数组</param>
        /// <param name="strMethod">提交方式。两个值可选:post、get</param>
        /// <param name="fileName">文件绝对路径</param>
        /// <param name="data">文件数据</param>
        /// <param name="contentType">文件内容类型</param>
        /// <param name="lengthFile">文件长度</param>
        /// <returns>支付宝处理结果</returns>
        public static string BuildRequest(SortedDictionary <string, string> sParaTemp, string strMethod, string fileName, byte[] data, string contentType, int lengthFile)
        {
            //待请求参数数组
            Dictionary <string, string> dicPara = new Dictionary <string, string>();

            dicPara = BuildRequestPara(sParaTemp);

            //构造请求地址
            string strUrl = GATEWAY_NEW + "_input_charset=" + _input_charset;

            //设置HttpWebRequest基本信息
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl);

            //设置请求方式:get、post
            request.Method = strMethod;
            //设置boundaryValue
            string boundaryValue = DateTime.Now.Ticks.ToString("x");
            string boundary      = "--" + boundaryValue;

            request.ContentType = "\r\nmultipart/form-data; boundary=" + boundaryValue;
            //设置KeepAlive
            request.KeepAlive = true;
            //设置请求数据,拼接成字符串
            StringBuilder sbHtml = new StringBuilder();

            foreach (KeyValuePair <string, string> key in dicPara)
            {
                sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"" + key.Key + "\"\r\n\r\n" + key.Value + "\r\n");
            }
            sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"withhold_file\"; filename=\"");
            sbHtml.Append(fileName);
            sbHtml.Append("\"\r\nContent-Type: " + contentType + "\r\n\r\n");
            string postHeader = sbHtml.ToString();
            //将请求数据字符串类型根据编码格式转换成字节流
            Encoding code = Encoding.GetEncoding(_input_charset);

            byte[] postHeaderBytes = code.GetBytes(postHeader);
            byte[] boundayBytes    = Encoding.ASCII.GetBytes("\r\n" + boundary + "--\r\n");
            //设置长度
            long length = postHeaderBytes.Length + lengthFile + boundayBytes.Length;

            request.ContentLength = length;

            //请求远程HTTP
            Stream requestStream = request.GetRequestStream();
            Stream myStream;

            try
            {
                //发送数据请求服务器
                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                requestStream.Write(data, 0, lengthFile);
                requestStream.Write(boundayBytes, 0, boundayBytes.Length);
                HttpWebResponse HttpWResp = (HttpWebResponse)request.GetResponse();
                myStream = HttpWResp.GetResponseStream();
            }
            catch (WebException e)
            {
                return(e.ToString());
            }
            finally
            {
                if (requestStream != null)
                {
                    requestStream.Close();
                }
            }

            //读取支付宝返回处理结果
            StreamReader  reader       = new StreamReader(myStream, code);
            StringBuilder responseData = new StringBuilder();

            String line;

            while ((line = reader.ReadLine()) != null)
            {
                responseData.Append(line);
            }
            myStream.Close();
            return(responseData.ToString());
        }
Esempio n. 36
0
        /// <summary>
        /// 通过GET方式请求
        /// </summary>
        /// <param name="url">Url</param>
        /// <param name="timeout">超时时间</param>
        /// <param name="userAgent">浏览器标志</param>
        /// <param name="referer">引用页</param>
        /// <param name="requestEncoding">编码</param>
        /// <param name="cookies">CookieContainer</param>
        /// <param name="proxy">代理</param>
        /// <param name="returl">返回请求的Url</param>
        /// <returns></returns>
        public string GetHttpResponse(string url, int?timeout, string userAgent, string referer, Encoding requestEncoding, ref CookieContainer cookies, WebProxy proxy, out string returl)
        {
            returl = "";

            try
            {
                if (string.IsNullOrEmpty(url))
                {
                    throw new ArgumentNullException("url");
                }

                if (requestEncoding == null)
                {
                    throw new ArgumentNullException("requestEncoding");
                }

                ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

                request.Method    = "GET";
                request.UserAgent = DefaultUserAgent;

                if (proxy != null)
                {
                    request.Proxy = proxy;
                }

                if (!string.IsNullOrEmpty(userAgent))
                {
                    request.UserAgent = userAgent;
                }

                if (timeout.HasValue)
                {
                    request.Timeout = timeout.Value;
                }

                if (cookies != null)
                {
                    request.CookieContainer = cookies;
                }

                if (referer != null)
                {
                    request.Referer = referer;
                }

                HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();

                if (httpWebResponse.CharacterSet != null)
                {
                    requestEncoding = Encoding.GetEncoding(httpWebResponse.CharacterSet);
                }

                this.responseEncoding = requestEncoding;

                string html = "";

                using (Stream responseStream = httpWebResponse.GetResponseStream())
                {
                    using (StreamReader streamReader = new StreamReader(responseStream, requestEncoding))
                    {
                        html = streamReader.ReadToEnd();

                        foreach (Cookie cookie in httpWebResponse.Cookies)
                        {
                            cookies.Add(cookie);
                        }

                        returl = httpWebResponse.ResponseUri.ToString();
                    }
                }

                request.Abort();

                httpWebResponse.Close();

                return(html);
            }
            catch (Exception er)
            {
                return(er.Message);
            }
        }
Esempio n. 37
0
        public bool PostState(JObject deviceBlob)
        {
            //POST UD/HOUSEID/ROOMID/DEVICEID

            UInt64 houseID;
            UInt64 roomID;
            UInt64 deviceID;

#if DEBUG
            try
            {
                houseID  = (UInt64)deviceBlob["houseID"];
                roomID   = (UInt64)deviceBlob["roomID"];
                deviceID = (UInt64)deviceBlob["deviceID"];
            }
            catch (WebException ex)
            {
                LogFile.AddLog("House -- Could not access correct keys: " + ex.Message + "\n");
                return(false);
            }
            return(true);
#else
            try
            {
                houseID  = (UInt64)deviceBlob["houseID"];
                roomID   = (UInt64)deviceBlob["roomID"];
                deviceID = (UInt64)deviceBlob["deviceID"];
            }
            catch (Exception ex)
            {
                LogFile.AddLog("House -- Invalid Keys are used: " + ex.Message + "\n");
                return(false);
            }

            try
            {
                WebRequest request = WebRequest.Create(DeviceRepository.storageURL + "UD/" + houseID + "/" + roomID + "/" + deviceID);
                request.ContentType = "application/json";
                request.Method      = "POST";

                try
                {
                    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                    {
                        streamWriter.Write(deviceBlob.ToString());
                        streamWriter.Flush();
                        streamWriter.Close();
                    }

                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            throw new Exception(String.Format(
                                                    "Server error (HTTP {0}: {1}).",
                                                    response.StatusCode,
                                                    response.StatusDescription));
                        }
                    }
                }

                catch (Exception ex)
                {
                    LogFile.AddLog("House -- Failed to Post state change to Storage: " + ex.Message + "\n");
                    return(false);
                }

                try
                {
#if DEBUG
                    if (!AppCache.AddDeviceBlob_DEBUG(deviceBlob))
                    {
                        throw new Exception("AppCache add device failed when adding: " + deviceBlob.ToString());
                    }
#else
                    if (!AppCache.AddDeviceBlob(deviceBlob))
                    {
                        throw new Exception("AppCache add device failed when adding: " + deviceBlob.ToString());
                    }
#endif
                }
                catch (Exception ex)
                {
                    LogFile.AddLog("House -- " + ex.Message + "\n");
                    return(false);
                }
            }

            catch (SystemException ex)
            {
                LogFile.AddLog("DeviceStateHouse -- Failed to create URL from data provided: " + ex.Message + "\n");
                return(false);
            }

            return(true);
#endif
        }
Esempio n. 38
0
        private static void CheckSocketConnect <T>(object internetState)
        {
            lock (_internetCheckLock)
            {
                isInternetCheckRunning = true;
            }

            HttpWebRequest             myRequest     = null;
            Action <bool>              callback      = null;
            Action <PubnubClientError> errorCallback = null;

            string[] channels      = null;
            string[] channelGroups = null;

            try
            {
                InternetState <T> state = internetState as InternetState <T>;
                if (state != null)
                {
                    callback      = state.Callback;
                    errorCallback = state.ErrorCallback;
                    channels      = state.Channels;
                    channelGroups = state.ChannelGroups;
                }

                mreSocketAsync = new ManualResetEvent(false);

                myRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://pubsub.pubnub.com/time/0");
                myRequest.BeginGetResponse(cb =>
                {
                    try
                    {
                        using (HttpWebResponse resp = myRequest.EndGetResponse(cb) as HttpWebResponse)
                        {
                            if (resp != null && resp.StatusCode == HttpStatusCode.OK)
                            {
                                LoggingMethod.WriteToLog(string.Format("DateTime {0} CheckSocketConnect Resp {1}", DateTime.Now.ToString(), HttpStatusCode.OK.ToString()), LoggingMethod.LevelInfo);
                                _status = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LoggingMethod.WriteToLog(string.Format("DateTime {0} CheckSocketConnect Failed {1}", DateTime.Now.ToString(), ex.ToString()), LoggingMethod.LevelInfo);
                    }
                    finally
                    {
                        mreSocketAsync.Set();
                    }
                }, null);

                mreSocketAsync.WaitOne(330);
            }
            catch (Exception ex)
            {
                _status = false;
                ParseCheckSocketConnectException <T>(ex, channels, channelGroups, errorCallback, callback);
            }
            finally
            {
                isInternetCheckRunning = false;
                mres.Set();
            }
        }
Esempio n. 39
0
        private void OnSubscribeOrRenewSubscriptionResponseReceived(IAsyncResult ar)
        {
            ChangeEventSubscriptionState state = (ChangeEventSubscriptionState)ar.AsyncState;

            using (_cpData.Lock.EnterWrite())
                _pendingCalls.Remove(state);

            CpService service = state.Service;

            try
            {
                HttpWebResponse response = (HttpWebResponse)state.Request.EndGetResponse(ar);
                try
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        service.InvokeEventSubscriptionFailed(new UPnPError((uint)response.StatusCode, response.StatusDescription));
                        return;
                    }
                    string dateStr    = response.Headers.Get("DATE");
                    string sid        = response.Headers.Get("SID");
                    string timeoutStr = response.Headers.Get("TIMEOUT");
                    int    timeout;
                    if (string.IsNullOrEmpty(timeoutStr) || (!timeoutStr.StartsWith("Second-") ||
                                                             !int.TryParse(timeoutStr.Substring("Second-".Length).Trim(), out timeout)))
                    {
                        service.InvokeEventSubscriptionFailed(new UPnPError((int)HttpStatusCode.BadRequest, "Invalid answer from UPnP device"));
                        return;
                    }

                    // The date header is not always available, and it is not always accurate either.
                    DateTime date = DateTime.Now;
                    if (DateTime.TryParseExact(dateStr, "R", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime parsedDate))
                    {
                        date = parsedDate.ToLocalTime();
                    }

                    DateTime expiration = date.AddSeconds(timeout);
                    if (expiration < DateTime.Now)
                    {
                        // If the timeout is in the past already, assume it is invalid and estimate
                        // the timeout timestamp. This workaround is necessary for devices that do
                        // not have their date set correctly (so the DATE header is unusable).
                        expiration = DateTime.Now.AddSeconds(timeout);
                    }

                    EventSubscription subscription;
                    using (_cpData.Lock.EnterWrite())
                    {
                        if (_subscriptions.TryGetValue(sid, out subscription))
                        {
                            subscription.Expiration = expiration;
                        }
                        else
                        {
                            _subscriptions.Add(sid, new EventSubscription(sid, state.ServiceDescriptor, service, expiration));
                        }
                        CheckSubscriptionRenewalTimer(_subscriptions.Values);
                    }
                }
                finally
                {
                    response.Close();
                }
            }
            catch (WebException e)
            {
                HttpWebResponse response = (HttpWebResponse)e.Response;
                service.InvokeEventSubscriptionFailed(new UPnPError(response == null ? 503 : (uint)response.StatusCode, "Cannot complete event subscription"));
                if (response != null)
                {
                    response.Close();
                }
            }
        }
Esempio n. 40
0
 public HttpMethodEventArgs(HttpWebResponse response)
     : this()
 {
     _Response = response;
 }
Esempio n. 41
0
        private void BtFind_Click(object sender, EventArgs e)
        {
            if (tbPhone.Text.Length < 1)
            {
                return;
            }
            HttpWebRequest webResquest = WebRequest.CreateHttp("http://localhost:56081/api/managerappone/getinformationcall/" + tbPhone.Text);

            webResquest.Method      = "GET";
            webResquest.ContentType = "application/json";
            HttpWebResponse webResponse = null;

            label_his_phone.Text  = tbPhone.Text;
            label_his_addr.Text   = tbFrom.Text;
            label_his_status.Text = "0";
            label_his_type.Text   = user.TypeCar.ToString();
            try
            {
                webResponse = webResquest.GetResponse() as HttpWebResponse;
                using (var jsonStream = new StreamReader(webResponse.GetResponseStream()))
                {
                    var result = JObject.Parse(jsonStream.ReadToEnd());
                    user.Phone           = tbPhone.Text;
                    user.Fullname        = tbFullName.Text;
                    user.Address         = result.Value <string>("address");
                    user.Status          = result.Value <int>("status");
                    user.TypeCar         = result.Value <int>("typeCar");
                    user.Time            = result.Value <string>("time");
                    user.AddressFormated = result.Value <string>("addressFormated");

                    jsonStream.Close();
                }
                tbFrom.Text = user.AddressFormated;
                if (user.TypeCar == 0)
                {
                    rdbStandard.Checked = true;
                    rdbPremium.Checked  = false;
                }
                else
                {
                    rdbStandard.Checked = false;
                    rdbPremium.Checked  = true;
                }

                label_his_phone.Text = user.Phone;
                label_his_addr.Text  = user.AddressFormated;
                //        0 :
                //    1 : đang tìm xe
                //    2 : đã định vị
                //    3 :
                switch (user.Status)
                {
                case 0:
                    label_his_status.Text = "chưa xac định tọa độ";
                    break;

                case 1:
                    label_his_status.Text = "đang tìm xe";
                    break;

                case 2:
                    label_his_status.Text = "đã định vị";
                    break;

                case 3:
                    label_his_status.Text = "không có xe";
                    break;
                }
                if (user.TypeCar == 0)
                {
                    label_his_type.Text = "xe thường";
                }
                else
                {
                    label_his_type.Text = "xe vip";
                }
                btLook.Show();
                btFind.Hide();
            }
            catch (WebException Exec)
            {
                if (Exec.Status == WebExceptionStatus.ProtocolError)
                {
                    webResponse = (HttpWebResponse)Exec.Response;
                    //MessageBox.Show("Error code: " + webResponse.StatusCode.ToString());
                    var json = JsonConvert.SerializeObject(
                        new
                    {
                        phone           = tbPhone.Text,
                        address         = tbFrom.Text,
                        addressFormated = "",
                        status          = 0,
                        time            = user.Time,
                        typeCar         = user.TypeCar,
                        lat             = 0,
                        lng             = 0
                    });
                    webResquest             = WebRequest.CreateHttp("http://localhost:56081/api/managerappone/addcall");
                    webResquest.Method      = "PUT";
                    webResquest.ContentType = "application/json";
                    var buff = Encoding.UTF8.GetBytes(json);
                    webResquest.ContentLength = buff.Length;
                    webResquest.GetRequestStream().Write(buff, 0, buff.Length);
                    try
                    {
                        webResponse = webResquest.GetResponse() as HttpWebResponse;
                        MessageBox.Show("Đã thêm cuộc gọi");
                    }
                    catch (WebException Exec1)
                    {
                        webResponse = (HttpWebResponse)Exec1.Response;
                        MessageBox.Show("Error code: " + webResponse.StatusCode.ToString());
                    }
                    finally
                    {
                        if (webResponse != null)
                        {
                            webResponse.Close();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Error: " + Exec.Status.ToString());
                }
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                }
            }
            tabControl.SelectedTab = tabHistory;
        }
Esempio n. 42
0
        /// <summary>
        /// 获得http请求数据
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="method">请求方式</param>
        /// <param name="postData">发送数据</param>
        /// <param name="encoding">编码</param>
        /// <param name="timeout">超时值</param>
        /// <returns></returns>
        public static string GetRequestData(string url, string method, string postData, Encoding encoding, int timeout)
        {
            if (!(url.Contains("http://") || url.Contains("https://")))
            {
                url = "http://" + url;
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method            = method.Trim().ToLower();
            request.Timeout           = timeout;
            request.AllowAutoRedirect = true;
            request.UserAgent         = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
            try
            {
                if (!string.IsNullOrEmpty(postData) && request.Method == "post")
                {
                    byte[] buffer = encoding.GetBytes(postData);
                    request.ContentLength = buffer.Length;
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (encoding == null)
                    {
                        MemoryStream stream = new MemoryStream();
                        if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                        {
                            new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(stream, 10240);
                        }
                        else
                        {
                            response.GetResponseStream().CopyTo(stream, 10240);
                        }

                        byte[] RawResponse = stream.ToArray();
                        string temp        = Encoding.Default.GetString(RawResponse, 0, RawResponse.Length);
                        Match  meta        = metaRegex.Match(temp);
                        string charter     = (meta.Groups.Count > 2) ? meta.Groups[2].Value : string.Empty;
                        charter = charter.Replace("\"", string.Empty).Replace("'", string.Empty).Replace(";", string.Empty);
                        if (charter.Length > 0)
                        {
                            charter  = charter.ToLower().Replace("iso-8859-1", "gbk");
                            encoding = Encoding.GetEncoding(charter);
                        }
                        else
                        {
                            if (response.CharacterSet.ToLower().Trim() == "iso-8859-1")
                            {
                                encoding = Encoding.GetEncoding("gbk");
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(response.CharacterSet.Trim()))
                                {
                                    encoding = Encoding.UTF8;
                                }
                                else
                                {
                                    encoding = Encoding.GetEncoding(response.CharacterSet);
                                }
                            }
                        }
                        return(encoding.GetString(RawResponse));
                    }
                    else
                    {
                        StreamReader reader = null;
                        if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                        {
                            using (reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding))
                            {
                                return(reader.ReadToEnd());
                            }
                        }
                        else
                        {
                            using (reader = new StreamReader(response.GetResponseStream(), encoding))
                            {
                                try
                                {
                                    return(reader.ReadToEnd());
                                }
                                catch (Exception)
                                {
                                    return("close");
                                }
                            }
                        }
                    }
                }
            }
            catch (WebException)
            {
                return("error");
            }
        }
Esempio n. 43
0
        private void BtBookCar_Click(object sender, EventArgs e)
        {
            Button btnBookCar = (Button)sender;
            int    index      = int.Parse(btnBookCar.Name);
            var    json       = Newtonsoft.Json.JsonConvert.SerializeObject(
                new
            {
                id      = drivers[index].Id,
                lat     = drivers[index].Lat,
                lng     = drivers[index].Lng,
                name    = drivers[index].Name,
                status  = 1,
                typeCar = drivers[index].TypeCard
            });
            string         url        = "http://localhost:56081/api/managerappone/book/" + drivers[index].Id.ToString();
            HttpWebRequest webRequest = WebRequest.CreateHttp(url);

            webRequest.Method      = "PUT";
            webRequest.ContentType = "application/json";
            var buffer = Encoding.UTF8.GetBytes(json);

            webRequest.ContentLength = buffer.Length;
            webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse webResponse = null;

            try
            {
                webResponse = webRequest.GetResponse() as HttpWebResponse;
                if (webResponse.StatusCode != HttpStatusCode.OK)
                {
                    if (webResponse != null)
                    {
                        webResponse.Close();
                    }
                    return;
                }
                else
                {
                    tbDriverID.Text  = drivers[index].Id.ToString();
                    tbDriveName.Text = drivers[index].Name;
                    for (int i = 1; i < drivers.Count; i++)
                    {
                        if (i == index)
                        {
                            continue;
                        }
                        DriverBoxs[i].Box.Hide();
                    }
                }
            }
            catch (WebException exec)
            {
                if (exec.Status == WebExceptionStatus.ProtocolError)
                {
                    webResponse = (HttpWebResponse)exec.Response;
                    MessageBox.Show("Error code: " + webResponse.StatusCode.ToString());
                }
                else
                {
                    MessageBox.Show("Error: " + exec.Status.ToString());
                }
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                }
            }
        }
Esempio n. 44
0
        public void getResponse(HttpWebRequest request)
        {
            HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();

            responseParams(httpResponse);
        }
Esempio n. 45
0
 /// <summary>
 /// Indicates if link is broken according to supplied HTTP response 
 /// </summary>
 /// <param name="response">HTTP web response of URL</param>
 private bool LinkBroken(HttpWebResponse response)
 {
     if (response != null)
     {
         switch (response.StatusCode)
         {
             // Response OK status
             case HttpStatusCode.Accepted:
             case HttpStatusCode.Continue:
             case HttpStatusCode.Created:
             case HttpStatusCode.Found:
             case HttpStatusCode.MultipleChoices:
             case HttpStatusCode.NoContent:
             case HttpStatusCode.NonAuthoritativeInformation:
             case HttpStatusCode.NotModified:
             case HttpStatusCode.OK:
             case HttpStatusCode.PartialContent:
             case HttpStatusCode.RedirectKeepVerb:
             case HttpStatusCode.RedirectMethod:
             case HttpStatusCode.ResetContent:
             case HttpStatusCode.SwitchingProtocols:
             case HttpStatusCode.Unused:
             case HttpStatusCode.UseProxy:
                 return false;
         }
     }
     return true;
 }
Esempio n. 46
0
        public void getResponse(WebException request)
        {
            HttpWebResponse httpResponse = (HttpWebResponse)request.Response;

            responseParams(httpResponse);
        }
Esempio n. 47
0
        internal static Dictionary<string, string> WrapResponseHeaders(HttpWebResponse response)
        {
            Dictionary<string, string> headers = new Dictionary<string, string>(EqualityComparer<string>.Default);
            if (null != response)
            {
                foreach (string name in response.Headers.AllKeys)
                {
                    headers.Add(name, response.Headers[name]);
                }
            }

            return headers;
        }
Esempio n. 48
0
		public static ICrossDomainPolicy BuildSilverlightPolicy (HttpWebResponse response)
		{
			// return null if no Silverlight policy was found, since we offer a second chance with a flash policy
			if ((response.StatusCode != HttpStatusCode.OK) || !CheckContentType (response.ContentType))
				return null;

			ICrossDomainPolicy policy = null;
			try {
				policy = ClientAccessPolicy.FromStream (response.GetResponseStream ());
				if (policy != null)
					AddPolicy (response.ResponseUri, policy);
			} catch (Exception ex) {
				Console.WriteLine (String.Format ("CrossDomainAccessManager caught an exception while reading {0}: {1}", 
					response.ResponseUri, ex));
				// and ignore.
			}
			return policy;
		}
    private static void CopyResponseHeaders(HttpContext context, HttpWebResponse res)
    {
        // Copy responbse headers
        foreach (var headerKey in res.Headers.AllKeys)
        {
            var val = res.Headers[headerKey];
            switch (headerKey.ToLower())
            {
                case "content-length":
                    break;

                case "content-type":
                    context.Response.ContentType = val;
                    break;

                case "location":
                    break;

                case "cache-control":
                    break;

                case "date":
                    break;
                case "etag":
                    break;
                case "last-modified":
                    break;

                case "set-cookie":
                    foreach (var cookieString in val.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        var cookie = new Cookie(cookieString);
                        context.Response.Cookies.Add(new HttpCookie(cookie.Name, cookie.Value));
                    }
                    break;

                default:
                    try
                    {
                        context.Response.Headers.Add(headerKey, val);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    break;
            }
        }
    }
    /// <summary>
    /// Set status of URL check.
    /// </summary>
    /// <param name="response">Web response to obtain data about URL</param>
    /// <returns>URL status text</returns>
    private string SetStatusText(HttpWebResponse response)
    {
        string errorText;
        if ((response == null) || (response.StatusCode == HttpStatusCode.OK))
        {
            return SetStatusText();
        }
        else if (response.StatusCode == HttpStatusCode.Redirect)
        {
            errorText = GetErrorText("Response status code: Redirect found", ResHelper.GetString("stagingeditserver.serverurl.redirectfound"));
            return SetStatusText(errorText);
        }

        // If web response is available, obtain status from that
        errorText = GetErrorText("Response status code: " + response.StatusCode, response.StatusDescription);
        return SetStatusText(errorText);
    }
Esempio n. 51
0
 /// <summary>
 /// Constructor for the response. This method is internal since we don't want users to create instances
 /// of this class.
 /// </summary>
 /// <param name="response">The web response to wrap.</param>
 internal DataServiceStreamResponse(HttpWebResponse response)
 {
     Debug.Assert(response != null, "Can't create a stream response object from a null response.");
     this.response = response;
 }
Esempio n. 52
0
        public async Task GetWebSearchResul(string searchQueue)
        {
            string cx     = "d64fde5f3edd155bf";
            string apiKey = "AIzaSyDRHs-hDvdcdvwZsbO_n3Iwlnk2oJM94pc";

            int[] positions = new int[] { 1, 11, 21 };

            string[] splitQueue = searchQueue.Split(' ');

            List <string> finishedWords = new List <string>();

            string[] allPermutations = GetAllPermutations(splitQueue, 0, splitQueue.Length - 1, finishedWords);

            //HashSet<Result> uniqueResults = new HashSet<Result>(new ResultComparer());

            int linkNo = 1;

            for (int i = 0; i < allPermutations.Length; i++)
            {
                int index = 0;

                for (int j = 0; j < 3; j++)
                {
                    try
                    {
                        dynamic jsonData = "";
                        int     pos      = positions[j];
                        await Task.Run(() => {
                            var request = WebRequest.Create($"https://www.googleapis.com/customsearch/v1?key={apiKey}&cx={cx}&q={allPermutations[i]}&start={pos}&num=10");
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            Stream dataStream        = response.GetResponseStream();
                            StreamReader reader      = new StreamReader(dataStream);
                            string responseString    = reader.ReadToEnd();
                            jsonData = JsonConvert.DeserializeObject(responseString);
                        });



                        foreach (var item in jsonData.items)
                        {
                            string link = item.link;
                            Console.WriteLine($"Link number {linkNo}");
                            Console.WriteLine($"Link index {index}");
                            linkNo++;
                            if (isYoutube(link) == false)
                            {
                                await linkPosition.AddLink(new Result
                                {
                                    Title   = item.title,
                                    Link    = item.link,
                                    Snippet = item.snippet,
                                    Index   = index
                                }, searchQueue);//adds position and date also
                            }

                            index++;
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.InnerException);
                    }
                }
                Console.WriteLine($"Number of results: {index} -------------------------------------------------");
            }
        }
Esempio n. 53
0
 private string ReadResponse(HttpWebResponse response)
 {
     StreamReader responseReader = new StreamReader(response.GetResponseStream());
     return responseReader.ReadToEnd();
 }
Esempio n. 54
0
        /// <summary>
        /// Constructor with pararmeter.
        /// </summary>
        public MPAPIResponse(HttpMethod httpMethod, HttpWebRequest request, JObject payload, HttpWebResponse response)
        {
            this.Request  = request;
            this.Response = response;

            ParseRequest(httpMethod, request, payload);
            ParseResponse(response);

            System.Diagnostics.Trace.WriteLine("Server response: " + this.StringResponse);
        }
Esempio n. 55
0
        public HTTPPost(Uri Url, Dictionary<string, string> Parameters)
        {
            StringBuilder respBody = new StringBuilder();

            request = (HttpWebRequest)HttpWebRequest.Create(Url);
            request.UserAgent = "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1C10 Safari/419.3";
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            string content = "?";
            foreach (string k in Parameters.Keys)
            {
                content += k + "=" + Parameters[k] + "&";
            }
            content = content.TrimEnd(new char[] { '&' });
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] byte1 = encoding.GetBytes(content);
            request.ContentLength = byte1.Length;
            byte[] buf = new byte[8192];
            using (Stream rs = request.GetRequestStream())
            {
                rs.Write(byte1, 0, byte1.Length);
                rs.Close();

                response = (HttpWebResponse)request.GetResponse();
                Stream respStream = response.GetResponseStream();

                int count = 0;
                do
                {
                    count = respStream.Read(buf, 0, buf.Length);
                    if (count != 0)
                        respBody.Append(Encoding.ASCII.GetString(buf, 0, count));
                }
                while (count > 0);

                respStream.Close();
                ResponseBody = respBody.ToString();
                EscapedBody = GetEscapedBody();
                StatusCode = GetStatusLine();
                Headers = GetHeaders();

                response.Close();
            }
        }
Esempio n. 56
0
        //执行http调用
        public bool call()
        {
            StreamReader    sr = null;
            HttpWebResponse wr = null;

            HttpWebRequest hp = null;

            try
            {
                string postData = null;
                if (this.method.ToUpper() == "POST")
                {
                    string[] sArray = System.Text.RegularExpressions.Regex.Split(this.reqContent, "\\?");

                    hp = (HttpWebRequest)WebRequest.Create(sArray[0]);

                    if (sArray.Length >= 2)
                    {
                        postData = sArray[1];
                    }
                }
                else
                {
                    hp = (HttpWebRequest)WebRequest.Create(this.reqContent);
                }


                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                if (this.certFile != "")
                {
                    hp.ClientCertificates.Add(new X509Certificate2(this.certFile, this.certPasswd));
                }
                hp.Timeout = this.timeOut * 1000;

                System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(this.charset);
                if (postData != null)
                {
                    byte[] data = encoding.GetBytes(postData);

                    hp.Method = "POST";

                    hp.ContentType = "application/x-www-form-urlencoded";

                    hp.ContentLength = data.Length;

                    Stream ws = hp.GetRequestStream();

                    // 发送数据

                    ws.Write(data, 0, data.Length);
                    ws.Close();
                }


                wr = (HttpWebResponse)hp.GetResponse();
                sr = new StreamReader(wr.GetResponseStream(), encoding);



                this.resContent = sr.ReadToEnd();
                sr.Close();
                wr.Close();
            }
            catch (Exception exp)
            {
                this.errInfo += exp.Message;
                if (wr != null)
                {
                    this.responseCode = Convert.ToInt32(wr.StatusCode);
                }

                return(false);
            }

            this.responseCode = Convert.ToInt32(wr.StatusCode);

            return(true);
        }
Esempio n. 57
0
        public string Process()
        {
            postData.Clear();

            if (this.queryByHierarchy != "")
            {
                calcReportTPS();
                this.URL = "https://secure.bluepay.com/interfaces/bpdailyreport2";
                addPostParam("ACCOUNT_ID", this.accountID);
                addPostParam("MODE", this.ServiceMode);
                addPostParam("TAMPER_PROOF_SEAL", this.TPS);
                addPostParam("REPORT_START_DATE", this.reportStartDate);
                addPostParam("REPORT_END_DATE", this.reportEndDate);
                addPostParam("DO_NOT_ESCAPE", this.doNotEscape);
                addPostParam("QUERY_BY_SETTLEMENT", this.queryBySettlement);
                addPostParam("QUERY_BY_HIERARCHY", this.queryByHierarchy);
                addPostParam("EXCLUDE_ERRORS", this.excludeErrors);
            }
            else if (this.reportStartDate != "")
            {
                calcReportTPS();
                this.URL = "https://secure.bluepay.com/interfaces/stq";
                addPostParam("ACCOUNT_ID", this.accountID);
                addPostParam("MODE", this.ServiceMode);
                addPostParam("TAMPER_PROOF_SEAL", this.TPS);
                addPostParam("REPORT_START_DATE", this.reportStartDate);
                addPostParam("REPORT_END_DATE", this.reportEndDate);
                addPostParam("DO_NOT_ESCAPE", this.doNotEscape);
                addPostParam("EXCLUDE_ERRORS", this.excludeErrors);
                addPostParam("id", this.masterID, true);
                addPostParam("payment_type", this.paymentType, true);
                addPostParam("trans_type", this.transType, true);
                addPostParam("amount", this.amount, true);
                addPostParam("name1", this.name1, true);
                addPostParam("name2", this.name2, true);
            }
            else if (this.transType != "SET" && this.transType != "GET")
            {
                calcTPS();
                this.URL = "https://secure.bluepay.com/interfaces/bp10emu";
                addPostParam("MERCHANT", this.accountID);
                addPostParam("MODE", this.ServiceMode);
                addPostParam("TRANSACTION_TYPE", this.transType);
                addPostParam("TAMPER_PROOF_SEAL", this.TPS);
                addPostParam("NAME1", this.name1);
                addPostParam("NAME2", this.name2);
                addPostParam("AMOUNT", this.amount);
                addPostParam("ADDR1", this.addr1);
                addPostParam("ADDR2", this.addr2);
                addPostParam("CITY", this.city);
                addPostParam("STATE", this.state);
                addPostParam("ZIPCODE", this.zip);
                addPostParam("COMMENT", this.memo);
                addPostParam("PHONE", this.phone);
                addPostParam("EMAIL", this.email);
                addPostParam("REBILLING", this.doRebill);
                addPostParam("REB_FIRST_DATE", this.rebillFirstDate);
                addPostParam("REB_EXPR", this.rebillExpr);
                addPostParam("REB_CYCLES", this.rebillCycles);
                addPostParam("REB_AMOUNT", this.rebillAmount);
                addPostParam("RRNO", this.masterID);
                addPostParam("PAYMENT_TYPE", this.paymentType);
                addPostParam("INVOICE_ID", this.invoiceID);
                addPostParam("ORDER_ID", this.orderID);
                addPostParam("CUSTOM_ID", this.customID1);
                addPostParam("CUSTOM_ID2", this.customID2);
                addPostParam("AMOUNT_TIP", this.amountTip);
                addPostParam("AMOUNT_TAX", this.amountTax);
                addPostParam("AMOUNT_FOOD", this.amountFood);
                addPostParam("AMOUNT_MISC", this.amountMisc);
                addPostParam("REMOTE_IP", Dns.GetHostEntry("").AddressList[0].ToString());
                addPostParam("RESPONSEVERSION", "3");

                if (this.swipeData != "")
                {
                    Match matchTrack1And2 = track1And2.Match(this.swipeData);
                    Match matchTrack2     = track2Only.Match(this.swipeData);
                    if (matchTrack1And2.Success)
                    {
                        addPostParam("SWIPE", this.swipeData);
                    }
                    else if (matchTrack2.Success)
                    {
                        addPostParam("TRACK2", this.swipeData);
                    }
                }
                else if (this.paymentType == "CREDIT")
                {
                    addPostParam("CC_NUM", this.paymentAccount, true);
                    addPostParam("CC_EXPIRES", this.cardExpire, true);
                    addPostParam("CVCVV2", this.cvv2, true);
                }
                else
                {
                    addPostParam("ACH_ROUTING", this.routingNum);
                    addPostParam("ACH_ACCOUNT", this.accountNum);
                    addPostParam("ACH_ACCOUNT_TYPE", this.accountType);
                    addPostParam("DOC_TYPE", this.docType);
                }
            }
            else
            {
                calcRebillTPS();
                this.URL = "https://secure.bluepay.com/interfaces/bp20rebadmin";
                addPostParam("ACCOUNT_ID", this.accountID);
                addPostParam("TAMPER_PROOF_SEAL", this.TPS);
                addPostParam("TRANS_TYPE", this.transType);
                addPostParam("REBILL_ID", this.rebillID);
                addPostParam("TEMPLATE_ID", this.templateID);
                addPostParam("REB_EXPR", this.rebillExpr);
                addPostParam("REB_CYCLES", this.rebillCycles);
                addPostParam("REB_AMOUNT", this.rebillAmount);
                addPostParam("NEXT_AMOUNT", this.rebillNextAmount);
                addPostParam("NEXT_DATE", this.rebillNextDate);
                addPostParam("STATUS", this.rebillStatus);
            }

            //Create HTTPS POST object and send to BluePay
            ASCIIEncoding  encoding = new ASCIIEncoding();
            HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(new Uri(this.URL));

            request.AllowAutoRedirect = false;

            byte[] data = encoding.GetBytes(postData.ToString());

            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            Stream postdata = request.GetRequestStream();

            postdata.Write(data, 0, data.Length);
            postdata.Close();

            //get response
            try
            {
                HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
                getResponse(request);
                httpResponse.Close();
            }
            catch (WebException e)
            {
                HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
                getResponse(e);
                httpResponse.Close();
            }
            return(getStatus());
        }
Esempio n. 58
0
 /// <summary>
 /// 根据相传入的数据,得到相应页面数据
 /// </summary>
 /// <param name="item">参数类对象</param>
 /// <returns>返回HttpResult类型</returns>
 public HttpResult GetHtml(HttpItem item)
 {
     //返回参数
     HttpResult result = new HttpResult();
     try
     {
         //准备参数
         SetRequest(item);
     }
     catch (Exception ex)
     {
         return new HttpResult() { Cookie = string.Empty, Header = null, Html = ex.Message, StatusDescription = "配置参数时出错:" + ex.Message };
     }
     try
     {
         #region 得到请求的response
         using (response = (HttpWebResponse)request.GetResponse())
         {
             result.StatusCode = response.StatusCode;
             result.StatusDescription = response.StatusDescription;
             result.Header = response.Headers;
             if (response.Cookies != null) result.CookieCollection = response.Cookies;
             if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"];
             byte[] ResponseByte = null;
             using (MemoryStream _stream = new MemoryStream())
             {
                 //GZIIP处理
                 if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                 {
                     //开始读取流并设置编码方式
                     new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);
                 }
                 else
                 {
                     //开始读取流并设置编码方式
                     response.GetResponseStream().CopyTo(_stream, 10240);
                 }
                 //获取Byte
                 ResponseByte = _stream.ToArray();
             }
             if (ResponseByte != null & ResponseByte.Length > 0)
             {
                 //是否返回Byte类型数据
                 if (item.ResultType == ResultType.Byte) result.ResultByte = ResponseByte;
                 //从这里开始我们要无视编码了
                 if (encoding == null)
                 {
                     Match meta = Regex.Match(Encoding.Default.GetString(ResponseByte), "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
                     string c = (meta.Groups.Count > 1) ? meta.Groups[2].Value.ToLower().Trim() : string.Empty;
                     if (c.Length > 2)
                     {
                         try
                         {
                             if (c.IndexOf(" ") > 0) c = c.Substring(0, c.IndexOf(" "));
                             encoding = Encoding.GetEncoding(c.Replace("\"", "").Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim());
                         }
                         catch
                         {
                             if (string.IsNullOrEmpty(response.CharacterSet)) encoding = Encoding.UTF8;
                             else encoding = Encoding.GetEncoding(response.CharacterSet);
                         }
                     }
                     else
                     {
                         if (string.IsNullOrEmpty(response.CharacterSet)) encoding = Encoding.UTF8;
                         else encoding = Encoding.GetEncoding(response.CharacterSet);
                     }
                 }
                 //得到返回的HTML
                 result.Html = encoding.GetString(ResponseByte);
             }
             else
             {
                 //得到返回的HTML
                 result.Html = "本次请求并未返回任何数据";
             }
         }
         #endregion
     }
     catch (WebException ex)
     {
         //这里是在发生异常时返回的错误信息
         response = (HttpWebResponse)ex.Response;
         result.Html = ex.Message;
         if (response != null)
         {
             result.StatusCode = response.StatusCode;
             result.StatusDescription = response.StatusDescription;
         }
     }
     catch (Exception ex)
     {
         result.Html = ex.Message;
     }
     if (item.IsToLower) result.Html = result.Html.ToLower();
     return result;
 }
Esempio n. 59
0
		public static ICrossDomainPolicy BuildFlashPolicy (HttpWebResponse response)
		{
			ICrossDomainPolicy policy = null;
			if ((response.StatusCode == HttpStatusCode.OK) && CheckContentType (response.ContentType)) {
				try {
					policy = FlashCrossDomainPolicy.FromStream (response.GetResponseStream ());
				} catch (Exception ex) {
					Console.WriteLine (String.Format ("CrossDomainAccessManager caught an exception while reading {0}: {1}", 
						response.ResponseUri, ex));
					// and ignore.
				}
				if (policy != null) {
					// see DRT# 864 and 865
					string site_control = response.InternalHeaders ["X-Permitted-Cross-Domain-Policies"];
					if (!String.IsNullOrEmpty (site_control))
						(policy as FlashCrossDomainPolicy).SiteControl = site_control;
				}
			}

			// the flash policy was the last chance, keep a NoAccess into the cache
			if (policy == null)
				policy = no_access_policy;

			AddPolicy (response.ResponseUri, policy);
			return policy;
		}
Esempio n. 60
0
        private string QuerySharePoint(OAuthCredentials oAuthCredential)
        {
            string text = string.Empty;

            if (oAuthCredential == null)
            {
                this.LogError("[GetInlineExploreSpContent.QuerySharePoint(OAuthCredentials oAuthCredential)]", "Credentials missing");
                return(text);
            }
            if (string.IsNullOrEmpty(this.TargetUrl))
            {
                this.LogError("[GetInlineExploreSpContent.QuerySharePoint(OAuthCredentials oAuthCredential)]", "TargetUrl missing");
                return(text);
            }
            Guid value = Guid.NewGuid();

            oAuthCredential.ClientRequestId = new Guid?(value);
            oAuthCredential.Tracer          = new GetInlineExploreSpContentCommand.GetInlineExploreSpContentOauthOutboundTracer();
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(this.TargetUrl);

            httpWebRequest.Method      = "GET";
            httpWebRequest.ContentType = "text/xml";
            httpWebRequest.UserAgent   = "Exchange/15.00.0000.000/InlineExplore";
            httpWebRequest.Headers.Add("client-request-id", value.ToString());
            httpWebRequest.Headers.Add("return-client-request-id", "true");
            httpWebRequest.Credentials     = oAuthCredential;
            httpWebRequest.PreAuthenticate = true;
            httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer");
            httpWebRequest.Timeout = 3000;
            try
            {
                using (HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse)
                {
                    if (httpWebResponse != null && httpWebResponse.StatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception(string.Format("Http status code is {0}", httpWebResponse.StatusCode));
                    }
                    using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                    {
                        text = streamReader.ReadToEnd();
                    }
                }
            }
            catch (OAuthTokenRequestFailedException ex)
            {
                this.LogError("[GetInlineExploreSpContent.QuerySharePoint(OAuthCredentials oAuthCredential)]:OAuthException", oAuthCredential.Tracer.ToString() + ex.ToString(), value.ToString());
            }
            catch (WebException ex2)
            {
                this.LogError("[GetInlineExploreSpContent.QuerySharePoint(OAuthCredentials oAuthCredential)]:WebException", ex2.ToString(), value.ToString());
            }
            catch (Exception ex3)
            {
                this.LogError("[GetInlineExploreSpContent.QuerySharePoint(OAuthCredentials oAuthCredential)]:Exception", ex3.ToString(), value.ToString());
            }
            if (string.IsNullOrEmpty(text))
            {
                this.LogError("[GetInlineExploreSpContent.QuerySharePoint(OAuthCredentials oAuthCredential)]:No content in response", "Expected response from SharePoint", value.ToString());
            }
            return(text);
        }