System.Net.HttpWebRequest.GetResponse()

Here are the examples of the csharp api System.Net.HttpWebRequest.GetResponse() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1384 Examples 7

19 View Source File : GoPhishIntegration.cs
License : GNU General Public License v3.0
Project Creator : 0dteam

public static string sendReportNotificationToServer(string reportURL)
        {
            ServicePointManager.SecurityProtocol = Tls12;

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(reportURL);            
                var response = (HttpWebResponse)request.GetResponse();
                string html = new StreamReader(response.GetResponseStream()).ReadToEnd();
                return "OK";
            }
            catch (System.Exception exc)
            {
                return "ERROR"; // "GoPhish Listener is not responding or there is no Internet connection."
            }
        }

19 View Source File : HttpUtil.cs
License : Apache License 2.0
Project Creator : 214175590

public static void get(string url, DownloadStringCompletedEventHandler handler)
        {
            HttpWebRequest client = (HttpWebRequest)WebRequest.Create(url);
            client.GetResponse();
        }

19 View Source File : SpeedtestHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private string GetRealPingTime(string url, WebProxy webProxy, out int responseTime)
        {
            string msg = string.Empty;
            responseTime = -1;
            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                myHttpWebRequest.Timeout = 5000;
                myHttpWebRequest.Proxy = webProxy;//new WebProxy(Global.Loopback, Global.httpPort);

                Stopwatch timer = new Stopwatch();
                timer.Start();

                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                if (myHttpWebResponse.StatusCode != HttpStatusCode.OK
                    && myHttpWebResponse.StatusCode != HttpStatusCode.NoContent)
                {
                    msg = myHttpWebResponse.StatusDescription;
                }
                timer.Stop();
                responseTime = timer.Elapsed.Milliseconds;

                myHttpWebResponse.Close();
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                msg = ex.Message;
            }
            return msg;
        }

19 View Source File : HttpClient.cs
License : GNU Affero General Public License v3.0
Project Creator : 3drepo

protected T HttpGetJson<T>(string uri, int tries = 1)
        {
            AppendApiKey(ref uri);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Proxy = proxy;
            request.Method = "GET";
            request.Accept = "application/json";
            //request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.ReadWriteTimeout = timeout_ms;
            request.Timeout = timeout_ms;
            request.CookieContainer = cookies;
            Console.WriteLine("GET " + uri + " TRY: " + tries);

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

                Stream responseStream = response.GetResponseStream();
                StreamReader responseReader = new StreamReader(responseStream);
                string responseData = responseReader.ReadToEnd();

                JsonMapper.RegisterImporter<Double, Single>((Double value) =>
                {
                    return (Single)value;
                });
                return JsonMapper.ToObject<T>(responseData);
            }
            catch (WebException)
            {
                if (--tries == 0)
                    throw;

                return HttpGetJson<T>(uri, tries);
            }
        }

19 View Source File : HttpClient.cs
License : GNU Affero General Public License v3.0
Project Creator : 3drepo

protected T_out HttpPostJson<T_in, T_out>(string uri, T_in data)
        {
            AppendApiKey(ref uri);

            // put together the json object with the login form data
            string parameters = JsonMapper.ToJson(data);
            byte[] postDataBuffer = Encoding.UTF8.GetBytes(parameters);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Proxy = proxy;
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            request.ContentLength = postDataBuffer.Length;
            //request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.ReadWriteTimeout = timeout_ms;
            request.Timeout = timeout_ms;
            request.CookieContainer = cookies;
            Console.WriteLine("POST " + uri + " data: " + parameters);

            Stream postDataStream = request.GetRequestStream();

            postDataStream.Write(postDataBuffer, 0, postDataBuffer.Length);
            postDataStream.Close();

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

            Stream responseStream = response.GetResponseStream();

            StreamReader responseReader = new StreamReader(responseStream);
            string responseData = responseReader.ReadToEnd();

            Cookie responseCookie = response.Cookies[0];
            string responseDomain = responseCookie.Domain;

            // Only replacedume one cookie per domain
            if (!cookieDict.ContainsKey(responseDomain))
            {
                cookieDict.Add(responseCookie.Domain, responseCookie);
                responseCookie.Domain = "." + responseCookie.Domain;
            }

            Uri myUri = new Uri(uri);

            foreach (KeyValuePair<string, Cookie> entry in cookieDict)
            {
                int uriHostLength = myUri.Host.Length;

                if (myUri.Host.Substring(uriHostLength - responseDomain.Length, responseDomain.Length) == entry.Key)
                {
                    cookies.Add(myUri, entry.Value);
                }
            }

            return JsonMapper.ToObject<T_out>(responseData);
        }

19 View Source File : HttpClient.cs
License : GNU Affero General Public License v3.0
Project Creator : 3drepo

protected virtual Stream HttpGetURI(string uri, int tries = 1)
        {
            AppendApiKey(ref uri);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Proxy = proxy;
            request.Method = "GET";
            //request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.ReadWriteTimeout = timeout_ms;
            request.Timeout = timeout_ms;
            request.CookieContainer = cookies;
            Console.WriteLine("GET " + uri + " TRY: " + tries);

            try
            {
                MemoryStream memStream;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    memStream = new MemoryStream();

                    byte[] buffer = new byte[1024];
                    int byteCount;
                    int total = 0;

                    var ns = response.GetResponseStream();
                    do
                    {
                        byteCount = ns.Read(buffer, 0, buffer.Length);
                        memStream.Write(buffer, 0, byteCount);

                        total += byteCount;
                    } while (byteCount > 0);
                    request.Abort();
                }

                return memStream;
            }
            catch (WebException)
            {
                if (--tries == 0)
                    throw;

                return HttpGetURI(uri, tries);
            }
        }

19 View Source File : DownloadFile.cs
License : MIT License
Project Creator : 404Lcc

public bool ReadSize()
        {
            if (downloadData.size > 0) return true;
            HttpWebRequest httpWebRequest = null;
            WebResponse webResponse = null;
            try
            {
                httpWebRequest = (HttpWebRequest)WebRequest.Create(downloadData.url);
                httpWebRequest.ReadWriteTimeout = readWriteTimeout;
                httpWebRequest.Timeout = timeout;
                webResponse = httpWebRequest.GetResponse();
                downloadData.size = (int)webResponse.ContentLength;
                return true;
            }
            catch
            {
                state = DownloadState.Error;
                error = "获取文件失败";
            }
            finally
            {
                if (httpWebRequest != null)
                {
                    httpWebRequest.Abort();
                    httpWebRequest = null;
                }
                if (webResponse != null)
                {
                    webResponse.Dispose();
                    webResponse = null;
                }
            }
            return false;
        }

19 View Source File : DownloadFile.cs
License : MIT License
Project Creator : 404Lcc

public bool Downloading()
        {
            if (File.Exists(downloadData.path))
            {
                currentSize = downloadData.size;
                return true;
            }
            long position = 0;
            string tempPath = downloadData.path + ".temp";
            if (File.Exists(tempPath))
            {
                using (FileStream fileStream = new FileStream(tempPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                {
                    position = fileStream.Length;
                    fileStream.Seek(position, SeekOrigin.Current);
                    if (position == downloadData.size)
                    {
                        if (File.Exists(downloadData.path))
                        {
                            File.Delete(downloadData.path);
                        }
                        File.Move(tempPath, downloadData.path);
                        currentSize = position;
                        return true;
                    }
                }
            }
            else
            {
                PathUtil.GetPath(PathType.PersistentDataPath, Path.GetDirectoryName(downloadData.path));
                using (FileStream fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                {
                    HttpWebRequest httpWebRequest = null;
                    HttpWebResponse httpWebResponse = null;
                    try
                    {
                        httpWebRequest = (HttpWebRequest)WebRequest.Create(downloadData.url);
                        httpWebRequest.ReadWriteTimeout = readWriteTimeout;
                        httpWebRequest.Timeout = timeout;
                        if (position > 0)
                        {
                            httpWebRequest.AddRange((int)position);
                        }
                        httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                        using (Stream stream = httpWebResponse.GetResponseStream())
                        {
                            stream.ReadTimeout = timeout;
                            long currentSize = position;
                            byte[] bytes = new byte[fileReadLength];
                            int readSize = stream.Read(bytes, 0, fileReadLength);
                            while (readSize > 0)
                            {
                                fileStream.Write(bytes, 0, readSize);
                                currentSize += readSize;
                                if (currentSize == downloadData.size)
                                {
                                    if (File.Exists(downloadData.path))
                                    {
                                        File.Delete(downloadData.path);
                                    }
                                    File.Move(tempPath, downloadData.path);
                                }
                                this.currentSize = currentSize;
                                readSize = stream.Read(bytes, 0, fileReadLength);
                            }
                        }
                    }
                    catch
                    {
                        if (File.Exists(tempPath))
                        {
                            File.Delete(tempPath);
                        }
                        if (File.Exists(downloadData.path))
                        {
                            File.Delete(downloadData.path);
                        }
                        state = DownloadState.Error;
                        error = "文件下载失败";
                    }
                    finally
                    {
                        if (httpWebRequest != null)
                        {
                            httpWebRequest.Abort();
                            httpWebRequest = null;
                        }
                        if (httpWebResponse != null)
                        {
                            httpWebResponse.Dispose();
                            httpWebResponse = null;
                        }
                    }
                }
            }
            if (state == DownloadState.Error)
            {
                return false;
            }
            return true;
        }

19 View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static string Post(string Url, string postDataStr, CookieContainer cookieContainer = null)
            {
                cookieContainer = cookieContainer ?? new CookieContainer();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
                request.CookieContainer = cookieContainer;
                Stream myRequestStream = request.GetRequestStream();
                StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
                myStreamWriter.Write(postDataStr);
                myStreamWriter.Close();

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

                response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }

19 View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static string Get(string Url, string gettDataStr)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (gettDataStr == "" ? "" : "?") + gettDataStr);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }

19 View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio

public void StartDownload()
                {
                    try
                    {
                        HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(m_HttpDownloadInfo.Url);

                        if (0L < m_Position)
                        {
                            httpWebRequest.AddRange((int)m_Position);
                        }

                        WebResponse webResponse = httpWebRequest.GetResponse();
                        Stream webResponseStream = webResponse.GetResponseStream();

                        float progress = 0f;
                        long currentSize = m_Position;
                        long totalSize = m_Position + webResponse.ContentLength;

                        byte[] btContent = new byte[m_HttpDownloadInfo.DownloadBufferUnit];
                        int readSize = 0;
                        while (!m_Hreplacedtop && 0 < (readSize = webResponseStream.Read(btContent, 0, m_HttpDownloadInfo.DownloadBufferUnit)))
                        {
                            progress = (float)(currentSize += readSize) / totalSize;
                            if (null != OnDownloadProgress)
                            {
                                OnDownloadProgress.Invoke(this, new HttpDownloaderProgressEventArgs(progress));
                            }
                            m_FileStream.Flush();
                            m_FileStream.Write(btContent, 0, readSize);

                            System.Threading.Thread.Sleep(10);

                        }
                        m_FileStream.Close();
                        webResponseStream.Close();

                        if (!m_Hreplacedtop)
                        {
                            ReNameTempFile();

                            if (null != OnDownloadSuccess)
                            {
                                OnDownloadSuccess.Invoke(this, EventArgs.Empty);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (null != OnDownloadFailure)
                        {
                            OnDownloadFailure.Invoke(this,new HttpDownloaderFailureEventArgs(ex));
                        }
                        throw ex;
                    }
                }

19 View Source File : HTTP.cs
License : MIT License
Project Creator : 944095635

public HttpResult GetResponseUri(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
            {
                //请求数据
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    result.ResponseUri = response.ResponseUri.ToString();
                }
            }
            catch (Exception ex)
            {
                result.Html = ex.Message;
            }
            return result;
        }

19 View Source File : HTTP.cs
License : MIT License
Project Creator : 944095635

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
            {
                //请求数据
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    GetData(item, result);
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    using (response = (HttpWebResponse)ex.Response)
                    {
                        GetData(item, result);
                    }
                }
                else
                {
                    result.Html = ex.Message;
                }
            }
            catch (Exception ex)
            {
                result.Html = ex.Message;
            }
            if (item.IsToLower) result.Html = result.Html.ToLower();
            //重置request,response为空
            if (item.IsReset)
            {
                request = null;
                response = null;
            }
            return result;
        }

19 View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov

private string DoMethod(NameValueCollection jParams)
	    {
		    const int RequestTimeoutMilliseconds = 2*1000; // 2 sec 

		    string tempResult = "";

		    try
		    {
			    lock (m_tonceLock)
			    {
				    //get tonce
				    TimeSpan timeSpan = DateTime.UtcNow - genesis;
				    long milliSeconds = Convert.ToInt64(timeSpan.TotalMilliseconds*1000);
				    jParams[pTonce] = Convert.ToString(milliSeconds, CultureInfo.InvariantCulture);
				    //mock json request id
				    jParams[pId] = jsonRequestID.Next().ToString(CultureInfo.InvariantCulture);
				    //build http head
				    string paramsHash = GetHMACSHA1Hash(jParams);
				    string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes(accessKey + ':' + paramsHash));
				    string postData = "{\"method\": \"" + jParams[pMethod] + "\", \"params\": [" + jParams[pParams] + "], \"id\": " +
				                      jParams[pId] + "}";

				    //get webrequest,respawn new object per call for multiple connections
				    var webRequest = (HttpWebRequest) WebRequest.Create(url);
				    webRequest.Timeout = RequestTimeoutMilliseconds;

				    var bytes = Encoding.ASCII.GetBytes(postData);

				    webRequest.Method = jParams[pRequestMethod];
				    webRequest.ContentType = "application/json-rpc";
				    webRequest.ContentLength = bytes.Length;
				    webRequest.Headers["Authorization"] = "Basic " + base64String;
				    webRequest.Headers["Json-Rpc-Tonce"] = jParams[pTonce];

				    // Send the json authentication post request
				    using (var dataStream = webRequest.GetRequestStream())
				    {
					    dataStream.Write(bytes, 0, bytes.Length);
				    }

				    // Get authentication response
				    using (var response = webRequest.GetResponse())
				    {
					    using (var stream = response.GetResponseStream())
					    {
// ReSharper disable once replacedignNullToNotNullAttribute
						    using (var reader = new StreamReader(stream))
						    {
							    tempResult = reader.ReadToEnd();
						    }
					    }
				    }
			    }
		    }
		    catch (WebException ex)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], ex.Message, ex);
		    }

		    //there are two kinds of API response, result or error.
		    if (tempResult.IndexOf("result", StringComparison.Ordinal) < 0)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], "API error:\n" + tempResult);
		    }

		    //compare response id with request id and remove it from result
		    try
		    {
			    int cutoff = tempResult.LastIndexOf(':') + 2;//"id":"1"} so (last index of ':')+2=length of cutoff=start of id-string
			    string idString = tempResult.Substring(cutoff, tempResult.Length - cutoff - 2);//2=last "}
			    if (idString != jParams[pId])
			    {
				    throw new BTCChinaException(jParams[pMethod], jParams[pId], "JSON-request id is not equal with JSON-response id.");
			    }
			    else
			    {
				    //remove json request id from response json string
				    int fromComma = tempResult.LastIndexOf(',');
				    int toLastBrace = tempResult.Length - 1;
				    tempResult = tempResult.Remove(fromComma, toLastBrace - fromComma);
			    }
		    }
		    catch (ArgumentOutOfRangeException ex)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], "Argument out of range in parsing JSON response id:" + ex.Message, ex);
		    }

		    return tempResult;
	    }

19 View Source File : HttpGetSearch.cs
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport

private static string ReadResponse(HttpWebRequest webRequest) {
         StreamReader Reader;
         HttpWebResponse Response;
         String ResponseContents = "";
         try {
            Response = ((HttpWebResponse)(webRequest.GetResponse()));
            Reader = new StreamReader(Response.GetResponseStream());
            ResponseContents = Reader.ReadToEnd();
            Reader.Close();
         }
         catch (ObjectDisposedException) {
            throw;
         }
         catch (IOException) {
            throw;
         }
         catch (SystemException) {
            throw;
         }
         return ResponseContents;
      }

19 View Source File : ViaCepWebservice.cs
License : MIT License
Project Creator : ACBrNet

private static List<ACBrEndereco> ConsultaCEP(string url)
		{
			try
			{
				var webRequest = (HttpWebRequest)WebRequest.Create(url);
				webRequest.ProtocolVersion = HttpVersion.Version10;
				webRequest.UserAgent = "Mozilla/4.0 (compatible; Synapse)";

				webRequest.KeepAlive = true;
				webRequest.Headers.Add(HttpRequestHeader.KeepAlive, "300");

				var response = webRequest.GetResponse();
				var xmlStream = response.GetResponseStream();
				var doc = XDoreplacedent.Load(xmlStream);

				var ret = new List<ACBrEndereco>();

				var rootElement = doc.Element("xmlcep");
				if (rootElement == null) return ret;

				if (rootElement.Element("enderecos") != null)
				{
					var element = rootElement.Element("enderecos");
					if (element == null) return ret;

					var elements = element.Elements("endereco");
					ret.AddRange(elements.Select(ProcessElement));
				}
				else
				{
					var endereco = ProcessElement(rootElement);
					ret.Add(endereco);
				}

				return ret;
			}
			catch (Exception e)
			{
				throw new ACBrException(e, "Erro ao consutar CEP.");
			}
		}

19 View Source File : CorreiosWebservice.cs
License : MIT License
Project Creator : ACBrNet

public override ACBrEndereco[] BuscarPorCEP(string cep)
		{
			try
			{
				var request = (HttpWebRequest)WebRequest.Create(CORREIOS_URL);
				request.ProtocolVersion = HttpVersion.Version10;
				request.UserAgent = "Mozilla/4.0 (compatible; Synapse)";
				request.Method = "POST";

				var postData = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
							   "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
							   "xmlns:cli=\"http://cliente.bean.master.sigep.bsb.correios.com.br/\"> " +
							   " <soapenv:Header/>" +
							   " <soapenv:Body>" +
							   " <cli:consultaCEP>" +
							   " <cep>" + cep.OnlyNumbers() + "</cep>" +
							   " </cli:consultaCEP>" +
							   " </soapenv:Body>" +
							   " </soapenv:Envelope>";

				var byteArray = Encoding.UTF8.GetBytes(postData);
				var dataStream = request.GetRequestStream();
				dataStream.Write(byteArray, 0, byteArray.Length);
				dataStream.Close();

				string retorno;

				// ReSharper disable once replacedignNullToNotNullAttribute
				using (var stHtml = new StreamReader(request.GetResponse().GetResponseStream(), ACBrEncoding.ISO88591))
					retorno = stHtml.ReadToEnd();

				var doc = XDoreplacedent.Parse(retorno);
				var element = doc.ElementAnyNs("Envelope").ElementAnyNs("Body").ElementAnyNs("consultaCEPResponse").ElementAnyNs("return");

				var endereco = new ACBrEndereco();
				endereco.CEP = element.Element("cep").GetValue<string>();
				endereco.Bairro = element.Element("bairro").GetValue<string>();
				endereco.Municipio = element.Element("cidade").GetValue<string>();
				endereco.Complemento = $"{element.Element("complemento").GetValue<string>()}{Environment.NewLine}{element.Element("complemento2").GetValue<string>()}";
				endereco.Logradouro = element.Element("end").GetValue<string>();
				endereco.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), element.Element("uf").GetValue<string>());

				endereco.TipoLogradouro = endereco.Logradouro.Split(' ')[0];
				endereco.Logradouro = endereco.Logradouro.SafeReplace(endereco.TipoLogradouro, string.Empty);

				return new[] { endereco };
			}
			catch (Exception exception)
			{
				throw new ACBrException(exception, "Erro ao consulta CEP.");
			}
		}

19 View Source File : ConsultaExtensions.cs
License : MIT License
Project Creator : ACBrNet

internal static string SendPost(this HttpWebRequest request, Dictionary<string, string> postData, Encoding enconde)
        {
            request.Method = "POST";

            var post = new StringBuilder();
            var lastKey = postData.Last().Key;
            foreach (var postValue in postData)
            {
                post.Append($"{postValue.Key}={postValue.Value}");
                if (postValue.Key != lastKey) post.Append("&");
            }

            var byteArray = enconde.GetBytes(post.ToString());
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;

            var dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            var response = request.GetResponse();
            var responseStream = response.GetResponseStream();
            Guard.Against<ACBrException>(responseStream == null, "Erro ao acessar o site.");

            string retorno;
            using (var stHtml = new StreamReader(responseStream, enconde))
                retorno = stHtml.ReadToEnd();

            return retorno;
        }

19 View Source File : Program_DbUpdates.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void CheckForWorldDatabaseUpdate()
        {
            log.Info($"Automatic World Database Update started...");
            try
            {
                var worldDb = new Database.WorldDatabase();
                var currentVersion = worldDb.GetVersion();
                log.Info($"Current World Database version: Base - {currentVersion.BaseVersion} | Patch - {currentVersion.PatchVersion}");

                var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "ACE.Server";

                var response = request.GetResponse();
                var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                var html = reader.ReadToEnd();
                reader.Close();
                response.Close();

                dynamic json = JsonConvert.DeserializeObject(html);
                string tag = json[0].tag_name;
                string dbURL = json[0].replacedets[0].browser_download_url;
                string dbFileName = json[0].replacedets[0].name;

                if (currentVersion.PatchVersion != tag)
                {
                    var patchVersionSplit = currentVersion.PatchVersion.Split(".");
                    var tagSplit = tag.Split(".");

                    int.TryParse(patchVersionSplit[0], out var patchMajor);
                    int.TryParse(patchVersionSplit[1], out var patchMinor);
                    int.TryParse(patchVersionSplit[2], out var patchBuild);

                    int.TryParse(tagSplit[0], out var tagMajor);
                    int.TryParse(tagSplit[1], out var tagMinor);
                    int.TryParse(tagSplit[2], out var tagBuild);

                    if (tagMajor > patchMajor || tagMinor > patchMinor || (tagBuild > patchBuild && patchBuild != 0))
                    {
                        log.Info($"Latest patch version is {tag} -- Update Required!");
                        UpdateToLatestWorldDatabase(dbURL, dbFileName);
                        var newVersion = worldDb.GetVersion();
                        log.Info($"Updated World Database version: Base - {newVersion.BaseVersion} | Patch - {newVersion.PatchVersion}");
                    }
                    else
                    {
                        log.Info($"Latest patch version is {tag} -- No Update Required!");
                    }
                }
                else
                {
                    log.Info($"Latest patch version is {tag} -- No Update Required!");
                }
            }
            catch (Exception ex)
            {
                log.Info($"Unable to continue with Automatic World Database Update due to the following error: {ex}");
            }
            log.Info($"Automatic World Database Update complete.");
        }

19 View Source File : Program_Setup.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void DoOutOfBoxSetup(string configFile)
        {
            var exeLocation = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location);
            var configJsExample = Path.Combine(exeLocation, "Config.js.example");
            var exampleFile = new FileInfo(configJsExample);
            if (!exampleFile.Exists)
            {
                log.Error("config.js.example Configuration file is missing.  Please copy the file config.js.example to config.js and edit it to match your needs before running ACE.");
                throw new Exception("missing config.js configuration file");
            }
            else
            {
                if (!IsRunningInContainer)
                {
                    Console.WriteLine("config.js Configuration file is missing,  cloning from example file.");
                    File.Copy(configJsExample, configFile, true);
                }
                else
                {
                    Console.WriteLine("config.js Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                    var configJsDocker = Path.Combine(exeLocation, "Config.js.docker");
                    File.Copy(configJsDocker, configFile, true);
                }
            }

            var fileText = File.ReadAllText(configFile);
            var config = JsonConvert.DeserializeObject<MasterConfiguration>(new JsMinifier().Minify(fileText));

            Console.WriteLine("Performing setup for ACEmulator...");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Welcome to ACEmulator! To configure your world for first use, please follow the instructions below. Press enter at each prompt to accept default values.");
            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the name for your World (default: \"{config.Server.WorldName}\"): ");
            var variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_WORLD_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.WorldName = variable.Trim();
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("The next two entries should use defaults, unless you have specific network environments...");
            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"Enter the Host address for your World (default: \"{config.Server.Network.Host}\"): ");
            variable = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.Network.Host = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the Port for your World (default: \"{config.Server.Network.Port}\"): ");
            variable = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.Network.Port = Convert.ToUInt32(variable.Trim());
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the directory location for your DAT files (default: \"{config.Server.DatFilesDirectory}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_DAT_FILES_DIRECTORY");
            if (!string.IsNullOrWhiteSpace(variable))
            {
                var path = Path.GetFullPath(variable.Trim());
                if (!Path.EndsInDirectorySeparator(path))
                    path += Path.DirectorySeparatorChar;
                //path = path.Replace($"{Path.DirectorySeparatorChar}", $"{Path.DirectorySeparatorChar}{Path.DirectorySeparatorChar}");

                config.Server.DatFilesDirectory = path;
            }
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Next we will configure your SQL server connections. You will need to know your database name, username and preplacedword for each.");
            Console.WriteLine("Default names for the databases are recommended, and it is also recommended you not use root for login to database. The preplacedword must not be blank.");
            Console.WriteLine("It is also recommended the SQL server be hosted on the same machine as this server, so defaults for Host and Port would be ideal as well.");
            Console.WriteLine("As before, pressing enter will use default value.");
            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the database name for your authentication database (default: \"{config.MySql.Authentication.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.Authentication.Database = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the database name for your shard database (default: \"{config.MySql.Shard.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.Shard.Database = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the database name for your world database (default: \"{config.MySql.World.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.World.Database = variable.Trim();
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Typically, all three databases will be on the same SQL server, is this how you want to proceed? (Y/n) ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.Write($"Enter the Host address for your SQL server (default: \"{config.MySql.World.Host}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Host = variable.Trim();
                    config.MySql.Shard.Host = variable.Trim();
                    config.MySql.World.Host = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the Port for your SQL server (default: \"{config.MySql.World.Port}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
                    config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
                    config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
                }
                Console.WriteLine();
            }
            else
            {
                Console.Write($"Enter the Host address for your authentication database (default: \"{config.MySql.Authentication.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your authentication database (default: \"{config.MySql.Authentication.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();

                Console.Write($"Enter the Host address for your shard database (default: \"{config.MySql.Shard.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your shard database (default: \"{config.MySql.Shard.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();

                Console.Write($"Enter the Host address for your world database (default: \"{config.MySql.World.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your world database (default: \"{config.MySql.World.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Typically, all three databases will be on the using the same SQL server credentials, is this how you want to proceed? (Y/n) ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = "y";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.Write($"Enter the username for your SQL server (default: \"{config.MySql.World.Username}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_USER");
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Username = variable.Trim();
                    config.MySql.Shard.Username = variable.Trim();
                    config.MySql.World.Username = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your SQL server (default: \"{config.MySql.World.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_PreplacedWORD");
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Preplacedword = variable.Trim();
                    config.MySql.Shard.Preplacedword = variable.Trim();
                    config.MySql.World.Preplacedword = variable.Trim();
                }
            }
            else
            {
                Console.Write($"Enter the username for your authentication database (default: \"{config.MySql.Authentication.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your authentication database (default: \"{config.MySql.Authentication.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Preplacedword = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the username for your shard database (default: \"{config.MySql.Shard.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your shard database (default: \"{config.MySql.Shard.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Preplacedword = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the username for your world database (default: \"{config.MySql.World.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your world database (default: \"{config.MySql.World.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Preplacedword = variable.Trim();
            }

            Console.WriteLine("commiting configuration to memory...");
            using (StreamWriter file = File.CreateText(configFile))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Formatting = Formatting.Indented;
                //serializer.NullValueHandling = NullValueHandling.Ignore;
                //serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
                serializer.Serialize(file, config);
            }


            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Do you want to ACEmulator to attempt to initilize your SQL databases? This will erase any existing ACEmulator specific databases that may already exist on the server (Y/n): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_INITIALIZE_DATABASES")) ? "y" : "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine();

                Console.Write($"Waiting for connection to SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                for (; ; )
                {
                    try
                    {
                        using (var sqlTestConnection = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120"))
                        {
                            Console.Write(".");
                            sqlTestConnection.Open();
                        }

                        break;
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {
                        Console.Write(".");
                        Thread.Sleep(5000);
                    }
                }
                Console.WriteLine(" connected!");

                if (IsRunningInContainer)
                {
                    Console.Write("Clearing out temporary ace% database .... ");
                    var sqlDBFile = "DROP DATABASE `ace%`;";
                    var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
                    var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {

                    }
                    Console.WriteLine(" done!");
                }

                Console.WriteLine("Searching for base SQL scripts .... ");
                foreach (var file in new DirectoryInfo($"DatabaseSetupScripts{Path.DirectorySeparatorChar}Base").GetFiles("*.sql").OrderBy(f => f.Name))
                {
                    Console.Write($"Found {file.Name} .... ");
                    var sqlDBFile = File.ReadAllText(file.FullName);
                    var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
                    switch (file.Name)
                    {
                        case "AuthenticationBase":
                            sqlConnectInfo = $"server={config.MySql.Authentication.Host};port={config.MySql.Authentication.Port};user={config.MySql.Authentication.Username};preplacedword={config.MySql.Authentication.Preplacedword};DefaultCommandTimeout=120";
                            break;
                        case "ShardBase":
                            sqlConnectInfo = $"server={config.MySql.Shard.Host};port={config.MySql.Shard.Port};user={config.MySql.Shard.Username};preplacedword={config.MySql.Shard.Preplacedword};DefaultCommandTimeout=120";
                            break;
                    }
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
                    var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {

                    }
                    Console.WriteLine(" complete!");
                }
                Console.WriteLine("Base SQL scripts import complete!");

                Console.WriteLine("Searching for Update SQL scripts .... ");

                PatchDatabase("Authentication", config.MySql.Authentication.Host, config.MySql.Authentication.Port, config.MySql.Authentication.Username, config.MySql.Authentication.Preplacedword, config.MySql.Authentication.Database);

                PatchDatabase("Shard", config.MySql.Shard.Host, config.MySql.Shard.Port, config.MySql.Shard.Username, config.MySql.Shard.Preplacedword, config.MySql.Shard.Database);

                PatchDatabase("World", config.MySql.World.Host, config.MySql.World.Port, config.MySql.World.Username, config.MySql.World.Preplacedword, config.MySql.World.Database);
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Do you want to download the latest world database and import it? (Y/n): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_DOWNLOAD_LATEST_WORLD_RELEASE")) ? "y" : "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine();

                if (IsRunningInContainer)
                {
                    Console.WriteLine(" ");
                    Console.WriteLine("This process will take a while, depending on many factors, and may look stuck while reading and importing the world database, please be patient! ");
                    Console.WriteLine(" ");
                }

                Console.Write("Looking up latest release from ACEmulator/ACE-World-16PY-Patches .... ");

                // webrequest code provided by OptimShi
                var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "Mozilla//5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko//20100101 Firefox//72.0";
                request.UserAgent = "ACE.Server";

                var response = request.GetResponse();
                var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                var html = reader.ReadToEnd();
                reader.Close();
                response.Close();

                dynamic json = JsonConvert.DeserializeObject(html);
                string tag = json[0].tag_name;
                string dbURL = json[0].replacedets[0].browser_download_url;
                string dbFileName = json[0].replacedets[0].name;
                // webrequest code provided by OptimShi

                Console.WriteLine($"Found {tag} !");

                Console.Write($"Downloading {dbFileName} .... ");
                using (var client = new WebClient())
                {
                    client.DownloadFile(dbURL, dbFileName);
                }
                Console.WriteLine("download complete!");

                Console.Write($"Extracting {dbFileName} .... ");
                ZipFile.ExtractToDirectory(dbFileName, ".", true);
                Console.WriteLine("extraction complete!");
                Console.Write($"Deleting {dbFileName} .... ");
                File.Delete(dbFileName);
                Console.WriteLine("Deleted!");

                var sqlFile = dbFileName.Substring(0, dbFileName.Length - 4);
                Console.Write($"Importing {sqlFile} into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} (This will take a while, please be patient) .... ");
                using (var sr = File.OpenText(sqlFile))
                {
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120");

                    var line = string.Empty;
                    var completeSQLline = string.Empty;
                    while ((line = sr.ReadLine()) != null)
                    {
                        //do minimal amount of work here
                        if (line.EndsWith(";"))
                        {
                            completeSQLline += line + Environment.NewLine;

                            var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, completeSQLline);
                            try
                            {
                                script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                                var count = script.Execute();
                            }
                            catch (MySql.Data.MySqlClient.MySqlException)
                            {

                            }
                            completeSQLline = string.Empty;
                        }
                        else
                            completeSQLline += line + Environment.NewLine;
                    }
                }
                Console.WriteLine(" complete!");

                Console.Write($"Deleting {sqlFile} .... ");
                File.Delete(sqlFile);
                Console.WriteLine("Deleted!");
            }

            Console.WriteLine("exiting setup for ACEmulator.");
        }

19 View Source File : SCaddins.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public static void CheckForUpdates(bool newOnly)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var uri = new Uri("https://api.github.com/repos/acnicholas/scaddins/releases/latest");
            var webRequest = WebRequest.Create(uri) as HttpWebRequest;
            if (webRequest == null)
            {
                return;
            }

            webRequest.ContentType = "application/json";
            webRequest.UserAgent = "Nothing";
            var latestAsJson = "nothing to see here";

            using (var s = webRequest.GetResponse().GetResponseStream())
            using (var sr = new StreamReader(s))
            {
                latestAsJson = sr.ReadToEnd();
            }

            var latestVersion = JsonConvert.DeserializeObject<LatestVersion>(latestAsJson);

            var installedVersion = Version;
            var latestAvailableVersion = new Version(latestVersion.tag_name.Replace("v", string.Empty).Trim());
            var info = latestVersion.body;

            var downloadLink = latestVersion.replacedets.FirstOrDefault().browser_download_url;
            if (string.IsNullOrEmpty(downloadLink))
            {
                downloadLink = Constants.DownloadLink;
            }

            if (latestAvailableVersion <= installedVersion && newOnly) {
                return;
            }
            dynamic settings = new ExpandoObject();
            settings.Height = 640;
            settings.Width = 480;
            settings.replacedle = "SCaddins Version Information";
            settings.ShowInTaskbar = false;
            settings.ResizeMode = System.Windows.ResizeMode.NoResize;
            settings.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
            var upgradeViewModel = new Common.ViewModels.UpgradeViewModel(installedVersion, latestAvailableVersion, info, downloadLink);
            WindowManager.ShowDialog(upgradeViewModel, null, settings);
        }

public static ReturnType ReceiveHTTPObjectPointer<ParameterType,ReturnType>
            (ParameterType parameterLObject, 
            string url,
            RESTMethodType methodType)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest
                     .Create(url);
            request.Method = methodType.ToString();
            request.ContentType = "application/json";
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            using (var sw = new StreamWriter(request.GetRequestStream()))
            {
                string json = serializer.Serialize(parameterLObject);
                sw.Write(json);
                sw.Flush();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            string strP = ReadResponseStream(receiveStream);
            var result = JsonConvert.DeserializeObject<ReturnType>(strP);
            return result;
        }

19 View Source File : Requestor.cs
License : MIT License
Project Creator : adoprog

public void PostRequest(string url, string json)
    {
      try
      {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
          streamWriter.Write(json);
          streamWriter.Flush();
          streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
          var result = streamReader.ReadToEnd();
        }
      }
      catch (Exception ex)
      {
        Log.Error("PostToFlow: Action failed to execute", ex);
      }
    }

19 View Source File : SendToFlow.cs
License : MIT License
Project Creator : adoprog

public void PostRequest(string url, string json)
    {
      try
      {
        var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
          streamWriter.Write(json);
          streamWriter.Flush();
          streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
          var result = streamReader.ReadToEnd();
        }
      }
      catch
      {
        // TODO: Use MA logging API to log error 
      }
    }

19 View Source File : PaypalHelper.cs
License : MIT License
Project Creator : Adoxio

public WebResponse GetPaymentWebResponse(string incomingReqStr)
		{
			var newReq = (HttpWebRequest)WebRequest.Create(PayPalBaseUrl);

			//Set values for the request back
			newReq.Method = "POST";
			newReq.ContentType = "application/x-www-form-urlencoded";

			var newRequestStr = incomingReqStr + "&cmd=_notify-validate";
			newReq.ContentLength = newRequestStr.Length;

			//write out the full parameters into the request
			var streamOut = new StreamWriter(newReq.GetRequestStream(), System.Text.Encoding.ASCII);
			streamOut.Write(newRequestStr);
			streamOut.Close();

			//Send request back to Paypal and receive response
			var response = newReq.GetResponse();
			return response;
		}

19 View Source File : PaypalHelper.cs
License : MIT License
Project Creator : Adoxio

public IPayPalPaymentDataTransferResponse GetPaymentDataTransferResponse(string idenreplacedyToken, string transactionId)
		{
			var query = string.Format("cmd=_notify-synch&tx={0}&at={1}", transactionId, idenreplacedyToken);

			var request = (HttpWebRequest)WebRequest.Create(PayPalBaseUrl);

			request.Method = WebRequestMethods.Http.Post;
			request.ContentType = "application/x-www-form-urlencoded";
			request.ContentLength = query.Length;

			var streamOut = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
			streamOut.Write(query);
			streamOut.Close();
			var streamIn = new StreamReader(request.GetResponse().GetResponseStream());
			var response = streamIn.ReadToEnd();
			streamIn.Close();
			
			return new PayPalPaymentDataTransferResponse(response);
		}

19 View Source File : BingMapLookup.cs
License : MIT License
Project Creator : Adoxio

public BingLocationResponse GetGeocodeLocationByQuery(string query)
		{
			BingLocationResponse result = null;

			var request = WebRequest.Create(string.Format("{0}?Key={1}&query={2}&userLocation={3}&inclnb={4}", BingMapRestUrl, BingMapKey, query, UserLocation, IncludeNeighborhood ?? 0)) as HttpWebRequest;

			
				if (request != null)
				{
					using (var response = (HttpWebResponse)request.GetResponse())
					{
						result = GetResult(response);
					}
				}
			

			return result;
		}

19 View Source File : SharePointFileHandler.cs
License : MIT License
Project Creator : Adoxio

public void ProcessRequest(HttpContext context)
		{
			if (!string.Equals(context.Request.HttpMethod, "GET", StringComparison.InvariantCultureIgnoreCase)
				|| SharePointFileUrl == null
				|| string.IsNullOrWhiteSpace(FileName))
			{
				context.Response.StatusCode = (int)HttpStatusCode.NotFound;
				return;
			}

			try
			{
				var spConnection = new SharePointConnection("SharePoint");
				var factory = new ClientFactory();
				var request = factory.CreateHttpWebRequest(spConnection, SharePointFileUrl) as HttpWebRequest;

				// make sure SharePoint receives the cache control headers from the browser

				var requestHeaders = _headersToRequest
					.Select(name => new { Name = name, Value = context.Request.Headers[name] })
					.Where(header => !string.IsNullOrWhiteSpace(header.Value))
					.ToList();

				foreach (var header in requestHeaders)
				{
					request.Headers[header.Name] = header.Value;
				}

				request.Accept = context.Request.Headers["Accept"];
				request.UserAgent = context.Request.Headers["User-Agent"];

				DateTime ifModifiedSince;
				if (DateTime.TryParse(context.Request.Headers["If-Modified-Since"], out ifModifiedSince))
				{
					request.IfModifiedSince = ifModifiedSince;
				}

				WebResponse response;

				try
				{
					response = request.GetResponse();
				}
				catch (WebException we)
				{
					// handle non-200 response from SharePoint

					var hwr = we.Response as HttpWebResponse;

					if (hwr != null && hwr.StatusCode == HttpStatusCode.NotModified)
					{
						context.Response.StatusCode = (int)HttpStatusCode.NotModified;
						return;
					}

                    ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Exception thrown trying to download {0}", SharePointFileUrl));
					ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("ProcessRequest", "Exception details: {0}", we.ToString()));

                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;

					return;
				}

				using (var stream = response.GetResponseStream())
				{
					// forward SharePoint response headers back to the browser

					var responseHeaders = _headersToRespond
						.Select(name => new { Name = name, Value = response.Headers[name] })
						.Where(header => !string.IsNullOrWhiteSpace(header.Value))
						.ToList();

					foreach (var header in responseHeaders)
					{
						context.Response.AppendHeader(header.Name, header.Value);
					}

					context.Response.AppendHeader("Content-Disposition", @"attachment; filename=""{0}""".FormatWith(FileName));

					int contentLength;

					if (!int.TryParse(response.Headers["Content-Length"], out contentLength))
					{
						// indeterminant length
						contentLength = -1;
					}

					if (contentLength == 0)
					{
						context.Response.StatusCode = (int)HttpStatusCode.NoContent;
						return;
					}

					// start streaming file

					context.Response.StatusCode = (int)HttpStatusCode.OK;

					const int bufferSize = 65536;
					var buffer = new byte[bufferSize];
					int bytesRead;

					do
					{
						bytesRead = stream.Read(buffer, 0, bufferSize);
						context.Response.OutputStream.Write(buffer, 0, bytesRead);
					} while (bytesRead > 0);
				}
			}
			catch (Exception e)
			{
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Exception thrown trying to download {0}", SharePointFileUrl));
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Exception details: {0}", e.ToString()));

                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
			}
		}

19 View Source File : ClientFactory.cs
License : MIT License
Project Creator : Adoxio

private static CookieContainer CreateCookieContainer(Uri uri, DateTime expires, byte[] data, int? timeout)
		{
			var request = CreateRequest(uri, timeout);

			using (var reqStream = request.GetRequestStream())
			{
				reqStream.Write(data, 0, data.Length);
				reqStream.Close();

				using (var response = request.GetResponse() as HttpWebResponse)
				{
					if (response.StatusCode == HttpStatusCode.MovedPermanently)
					{
						var location = response.Headers["Location"];

						if (!string.IsNullOrWhiteSpace(location))
						{
							var check = new Uri(location, UriKind.RelativeOrAbsolute);
							var locationUrl = check.IsAbsoluteUri ? check : new Uri(uri, check);

							return CreateCookieContainer(locationUrl, expires, data, timeout);
						}
					}

					return CreateCookieContainer(expires, request.RequestUri, response.Cookies);
				}
			}
		}

19 View Source File : RemotePost.cs
License : MIT License
Project Creator : Adoxio

private static string PostAndGetResponseString(string url, NameValueCollection parameters)
		{
			if (string.IsNullOrWhiteSpace(url) || (parameters == null || !parameters.HasKeys()))
			{
				return string.Empty;
			}

			var httpRequest = (HttpWebRequest)WebRequest.Create(url);
	
			httpRequest.Method = "POST"; 

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

			var postString = ConstructStringFromParameters(parameters);

			var bytedata = Encoding.UTF8.GetBytes(postString);

			httpRequest.ContentLength = bytedata.Length;

			var requestStream = httpRequest.GetRequestStream();

			requestStream.Write(bytedata, 0, bytedata.Length);

			requestStream.Close();
			
			var httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
			var responseStream =  httpWebResponse.GetResponseStream();

			var sb = new StringBuilder();

			if (responseStream != null)
			{
				using (var reader = new StreamReader(responseStream, Encoding.UTF8))
				{
					string line;
					while ((line = reader.ReadLine()) != null)
					{
						sb.Append(line);
					}
				}
			}

			return sb.ToString();
		}

19 View Source File : HttpHelper.cs
License : GNU General Public License v3.0
Project Creator : aduskin

static WebList Http(string _type, string _url, List<replacedem> _header, object _conmand, Encode _Encode)
      {
         Encoding _encoding = Get_Encoding(_Encode);
         HttpWebRequest req = Http_Core(_type, _url, _encoding, _header, _conmand);
         if (req != null)
         {
            try
            {
               using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
               {
                  return Http_DownSteam(response, _encoding);
               }
            }
            catch (WebException err)
            {
               var rsp = err.Response as HttpWebResponse;
               if (rsp != null)
               {
                  WebList _web = Http_DownSteam(rsp, _encoding);
                  _web.Err = err.Message;
                  rsp.Close(); rsp.Dispose();
                  return _web;
               }
            }
         }
         return null;
      }

19 View Source File : HttpHelper.cs
License : GNU General Public License v3.0
Project Creator : aduskin

public static WebList Http_NoData(string _type, string _url, List<replacedem> _header, object _conmand, Encode _Encode)
      {
         Encoding _encoding = Get_Encoding(_Encode);
         HttpWebRequest req = Http_Core(_type, _url, _encoding, _header, _conmand);
         if (req != null)
         {
            try
            {
               using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
               {
                  WebList _web = new WebList
                  {
                     StatusCode = (int)response.StatusCode,
                     Type = response.ContentType,
                     AbsoluteUri = response.ResponseUri.AbsoluteUri
                  };
                  string header = "";
                  foreach (string str in response.Headers.AllKeys)
                  {
                     if (str == "Set-Cookie")
                     {
                        _web.SetCookie = response.Headers[str];
                     }
                     else if (str == "Location")
                     {
                        _web.Location = response.Headers[str];
                     }
                     header = header + str + ":" + response.Headers[str] + "\r\n";
                  }
                  string cookie = "";
                  foreach (Cookie str in response.Cookies)
                  {
                     cookie = cookie + str.Name + "=" + str.Value + ";";
                  }

                  _web.Header = header;
                  _web.Cookie = cookie;
                  return _web;
               }
            }
            catch (WebException err)
            {
               var rsp = err.Response as HttpWebResponse;
               if (rsp != null)
               {
                  WebList _web = new WebList
                  {
                     StatusCode = (int)rsp.StatusCode,
                     Type = rsp.ContentType,
                     AbsoluteUri = rsp.ResponseUri.AbsoluteUri
                  };
                  string header = "";
                  foreach (string str in rsp.Headers.AllKeys)
                  {
                     if (str == "Set-Cookie")
                     {
                        _web.SetCookie = rsp.Headers[str];
                     }
                     else if (str == "Location")
                     {
                        _web.Location = rsp.Headers[str];
                     }
                     header = header + str + ":" + rsp.Headers[str] + "\r\n";
                  }
                  string cookie = "";
                  foreach (Cookie str in rsp.Cookies)
                  {
                     cookie = cookie + str.Name + "=" + str.Value + ";";
                  }

                  _web.Header = header;
                  _web.Cookie = cookie;
                  return _web;
               }
            }
         }
         return null;
      }

19 View Source File : HttpURLConnectionClient.cs
License : MIT License
Project Creator : Adyen

public string Request(string endpoint, string json, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null )
        {
            string responseText = null;
            _environment = config.Environment;
            var httpWebRequest = GetHttpWebRequest(endpoint, config, isApiKeyRequired, requestOptions );
            if (config.HttpRequestTimeout > 0)
            {
                httpWebRequest.Timeout = config.HttpRequestTimeout;
            }
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            try
            {
                using (var response = (HttpWebResponse) httpWebRequest.GetResponse())
                {
                    using (var reader = new StreamReader(response.GetResponseStream(), _encoding))
                    {
                        responseText = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException e)
            {
                HandleWebException(e);
            }
            return responseText;
        }

19 View Source File : HttpURLConnectionClient.cs
License : MIT License
Project Creator : Adyen

public string Post(string endpoint, Dictionary<string, string> postParameters, Config config)
        {
            var dictToString = QueryString(postParameters);
            byte[] postBytes = Encoding.UTF8.GetBytes(dictToString);
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.ContentLength = postBytes.Length;
            if (config.Proxy != null)
            {
                httpWebRequest.Proxy = config.Proxy;
            }
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            using (var stream = httpWebRequest.GetRequestStream())
            {
                stream.Write(postBytes, 0, postBytes.Length);
            }
            var response = (HttpWebResponse)httpWebRequest.GetResponse();
            return new StreamReader(response.GetResponseStream()).ReadToEnd();
        }

19 View Source File : WebApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public ApiValueResult GetResult(HttpWebRequest req)
		{
			string jsonResult;
			try
			{
				using (var response = req.GetResponse())
				{
					var receivedStream2 = response.GetResponseStream();
					if (receivedStream2 == null)
					{
						LogRecorderX.EndStepMonitor();
						return ErrorResult(-1, "服务器无返回值");
					}
					jsonResult = new StreamReader(receivedStream2).ReadToEnd();
					receivedStream2.Dispose();
					response.Close();
				}
			}
			catch (WebException e3)
			{
			    try
			    {
                    if (e3.Status != WebExceptionStatus.ProtocolError)
                    {
                        LogRecorderX.EndStepMonitor();
                        switch (e3.Status)
                        {
                            case WebExceptionStatus.CacheEntryNotFound:
                                return ErrorResult(-3, "找不到指定的缓存项");
                            case WebExceptionStatus.ConnectFailure:
                                return ErrorResult(-3, "在传输级别无法联系远程服务点");
                            case WebExceptionStatus.ConnectionClosed:
                                return ErrorResult(-3, "过早关闭连接");
                            case WebExceptionStatus.KeepAliveFailure:
                                return ErrorResult(-3, "指定保持活动状态的标头的请求的连接意外关闭");
                            case WebExceptionStatus.MessageLengthLimitExceeded:
                                return ErrorResult(-3, "已收到一条消息的发送请求时超出指定的限制或从服务器接收响应");
                            case WebExceptionStatus.NameResolutionFailure:
                                return ErrorResult(-3, "名称解析程序服务或无法解析主机名");
                            case WebExceptionStatus.Pending:
                                return ErrorResult(-3, "内部异步请求处于挂起状态");
                            case WebExceptionStatus.PipelineFailure:
                                return ErrorResult(-3, "该请求是管线请求和连接被关闭之前收到响应");
                            case WebExceptionStatus.ProxyNameResolutionFailure:
                                return ErrorResult(-3, "名称解析程序服务无法解析代理服务器主机名");
                            case WebExceptionStatus.ReceiveFailure:
                                return ErrorResult(-3, "从远程服务器未收到完整的响应");
                            case WebExceptionStatus.RequestCanceled:
                                return ErrorResult(-3, "请求已取消");
                            case WebExceptionStatus.RequestProhibitedByCachePolicy:
                                return ErrorResult(-3, "缓存策略不允许该请求");
                            case WebExceptionStatus.RequestProhibitedByProxy:
                                return ErrorResult(-3, "由该代理不允许此请求");
                            case WebExceptionStatus.SecureChannelFailure:
                                return ErrorResult(-3, "使用 SSL 建立连接时出错");
                            case WebExceptionStatus.SendFailure:
                                return ErrorResult(-3, "无法与远程服务器发送一个完整的请求");
                            case WebExceptionStatus.ServerProtocolViolation:
                                return ErrorResult(-3, "服务器响应不是有效的 HTTP 响应");
                            case WebExceptionStatus.Timeout:
                                return ErrorResult(-3, "请求的超时期限内未不收到任何响应");
                            case WebExceptionStatus.TrustFailure:
                                LogRecorderX.EndStepMonitor();
                                return ErrorResult(-3, "无法验证服务器证书");
                            default:
                                return ErrorResult(-3, "发生未知类型的异常");
                        }
                    }
                    var codes = e3.Message.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries);

                    if (codes.Length == 3 && int.TryParse(codes[1], out var s) && s == 404)
                    {
                        return ErrorResult(-3, "服务器内部错误", "页面不存在");
                    }
                    using (var webResponse = e3.Response)
                    {
                        var receivedStream = webResponse.GetResponseStream();
                        if (receivedStream == null)
                        {
                            LogRecorderX.EndStepMonitor();
                            return ErrorResult(-1, "服务器无返回值");
                        }
                        jsonResult = new StreamReader(receivedStream).ReadToEnd();
                        receivedStream.Dispose();
                        webResponse.Close();
                    }
                }
			    catch (Exception e)
			    {
			        LogRecorderX.Exception(e);
			        LogRecorderX.EndStepMonitor();
			        return ErrorResult(-1, "未知错误", e.Message);
                }
			}
			catch (Exception e2)
			{
				LogRecorderX.Exception(e2);
				LogRecorderX.EndStepMonitor();
				return ErrorResult(-1, "未知错误", e2.Message);
			}
			LogRecorderX.MonitorTrace(jsonResult);
			try
			{
			    if (string.IsNullOrWhiteSpace(jsonResult))
			        return ErrorResult(-1);
			    var baseResult = JsonConvert.DeserializeObject<ApiResult>(jsonResult);
			    return (!baseResult.Success) ? ErrorResult(baseResult.Status.ErrorCode, baseResult.Status.ClientMessage) : ApiValueResult.Succees(ReadResultData(jsonResult, "ResultData"));
			}
			catch (Exception e)
			{
				LogRecorderX.Exception(e);
				return ErrorResult(-1, "未知错误", e.Message);
			}
		}

19 View Source File : WebApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public ApiResult<TResult> GetResult<TResult>(HttpWebRequest req) 
		{
			string jsonResult;
			try
			{
				using (var webResponse = req.GetResponse())
				{
					var receivedStream2 = webResponse.GetResponseStream();
					if (receivedStream2 == null)
					{
						LogRecorderX.EndStepMonitor();
						return ApiResult.Error<TResult>(-1, "服务器无返回值");
					}
					jsonResult = new StreamReader(receivedStream2).ReadToEnd();
					receivedStream2.Dispose();
					webResponse.Close();
				}
			}
			catch (WebException e)
			{
				if (e.Status != WebExceptionStatus.ProtocolError)
				{
					LogRecorderX.EndStepMonitor();
					switch (e.Status)
					{
					case WebExceptionStatus.CacheEntryNotFound:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "找不到指定的缓存项");
					case WebExceptionStatus.ConnectFailure:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "在传输级别无法联系远程服务点");
					case WebExceptionStatus.ConnectionClosed:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "过早关闭连接");
					case WebExceptionStatus.KeepAliveFailure:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "指定保持活动状态的标头的请求的连接意外关闭");
					case WebExceptionStatus.MessageLengthLimitExceeded:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "已收到一条消息的发送请求时超出指定的限制或从服务器接收响应");
					case WebExceptionStatus.NameResolutionFailure:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "名称解析程序服务或无法解析主机名");
					case WebExceptionStatus.Pending:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "内部异步请求处于挂起状态");
					case WebExceptionStatus.PipelineFailure:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "该请求是管线请求和连接被关闭之前收到响应");
					case WebExceptionStatus.ProxyNameResolutionFailure:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "名称解析程序服务无法解析代理服务器主机名");
					case WebExceptionStatus.ReceiveFailure:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "从远程服务器未收到完整的响应");
					case WebExceptionStatus.RequestCanceled:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "请求已取消");
					case WebExceptionStatus.RequestProhibitedByCachePolicy:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "缓存策略不允许该请求");
					case WebExceptionStatus.RequestProhibitedByProxy:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "由该代理不允许此请求");
					case WebExceptionStatus.SecureChannelFailure:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "使用 SSL 建立连接时出错");
					case WebExceptionStatus.SendFailure:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "无法与远程服务器发送一个完整的请求");
					case WebExceptionStatus.ServerProtocolViolation:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "服务器响应不是有效的 HTTP 响应");
					case WebExceptionStatus.Timeout:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "请求的超时期限内未不收到任何响应");
					case WebExceptionStatus.TrustFailure:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "无法验证服务器证书");
					default:
						return ApiResult.Error<TResult>(ErrorCode.RemoteError, "发生未知类型的异常");
					}
				}
				using (var response = e.Response)
				{
					var receivedStream = response.GetResponseStream();
					if (receivedStream == null)
					{
						LogRecorderX.EndStepMonitor();
						return ApiResult.Error<TResult>(-1, "服务器无返回值");
					}
					jsonResult = new StreamReader(receivedStream).ReadToEnd();
					receivedStream.Dispose();
					response.Close();
				}
			}
			catch (Exception ex)
			{
				LogRecorderX.Exception(ex);
				LogRecorderX.EndStepMonitor();
				return ApiResult.Error<TResult>(ErrorCode.RemoteError);
			}
			LogRecorderX.MonitorTrace(jsonResult);
			try
			{
			    return string.IsNullOrWhiteSpace(jsonResult) 
			        ? ApiResult.Error<TResult>(-1) 
			        : JsonConvert.DeserializeObject<ApiResult<TResult>>(jsonResult);
			}
			catch (Exception ex2)
			{
				LogRecorderX.Exception(ex2);
				return ApiResult.Error<TResult>(-1);
			}
			finally
			{
				LogRecorderX.EndStepMonitor();
			}
		}

19 View Source File : mainForm.cs
License : MIT License
Project Creator : ajohns6

private void pullJSON(object sender, EventArgs e)
        {
            string url = "https://api.jsonbin.io/b/5f05f3e0a62f9b4b27613c5a/latest";

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                File.WriteAllText(onlineJSON, reader.ReadToEnd());
            }

            populateGrid(onlineJSON);
            MessageBox.Show("Your PAK list has been successfully updated.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

19 View Source File : mainForm.cs
License : MIT License
Project Creator : ajohns6

private void pullJSON()
        {
            string url = "https://api.jsonbin.io/b/5f05f3e0a62f9b4b27613c5a/latest";

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                File.WriteAllText(onlineJSON, reader.ReadToEnd());
            }
            MessageBox.Show("Your PAK List has been successfully updated.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

19 View Source File : updateForm.cs
License : MIT License
Project Creator : ajohns6

private void checkUpdate(object sender, EventArgs e)
        {
            if (!progressForm.IsConnectedToInternet())
            {
                this.Dispose();
                return;
            }

            string url = "https://api.github.com/repos/ajohns6/SM64-NX-Launcher/releases";
            string releaseString = "";

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Accept = "application/json";
            request.Method = "GET";
            request.UserAgent = "Foo";
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    releaseString = reader.ReadToEnd();
                }
            }
            catch
            {
                this.Dispose();
                return;
            }

            Application.DoEvents();

            var releaseList = JsonConvert.DeserializeObject<List<release>>(releaseString);

            if (releaseList[0].tag_name != ("v" + version))
            {
                this.statusLabel.Text = "Downloading " + releaseList[0].tag_name + "...";
                this.progBar.Visible = true;
                string tempPath = Path.Combine(Path.GetTempPath(),
                             "sm64nxlauncherinstaller",
                             version);
                string zipPath = Path.Combine(tempPath, "installer.zip");
                mainForm.DeleteDirectory(tempPath);

                Task.Run(() =>
                {
                    using (var client = new WebClient())
                    {
                        if (!Directory.Exists(tempPath))
                        {
                            Directory.CreateDirectory(tempPath);
                        }

                        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadProgress);
                        client.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadComplete);
                        Uri installerLink = new Uri(releaseList[0].replacedets[0].browser_download_url);
                        client.DownloadFileAsync(installerLink, zipPath);
                    }
                });

                progBar.Maximum = 100;

                Application.DoEvents();

                do
                {
                    progBar.Value = progress;
                } while (progress < 100);

                do
                {
                    Application.DoEvents();
                } while (!complete);

                this.statusLabel.Text = "Extracting installer...";

                Task.Run(() =>
                {
                    bool unzipped = false;
                    do
                    {
                        try
                        {
                            ZipFile.ExtractToDirectory(zipPath, tempPath);
                            unzipped = true;
                        }
                        catch { }
                    } while (!unzipped);
                }).Wait();

                ProcessStartInfo installStart = new ProcessStartInfo();
                installStart.FileName = Path.Combine(tempPath, "setup.exe");

                Process installer = new Process();
                installer.StartInfo = installStart;

                installer.Start();

                Application.Exit();
            }

            this.Close();
        }

19 View Source File : SoftwareUpdater.cs
License : MIT License
Project Creator : AlbertMN

public static bool RemoteFileExists(string url) {
            try {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "HEAD";
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                response.Close();
                return (response.StatusCode == HttpStatusCode.OK);
            } catch {
                return false;
            }
        }

19 View Source File : HTTPRequestNonThreaded.cs
License : MIT License
Project Creator : alen-smajic

private void getResponseNonThreaded(HttpWebRequest request, Action<HttpWebResponse, Exception> gotResponse) {

			HttpWebResponse response = null;
			try {
				response = (HttpWebResponse)request.GetResponse();
				gotResponse(response, null);
			}
			catch (WebException wex) {
				//another place to watchout for HttpWebRequest.Abort to occur
				if (wex.Status == WebExceptionStatus.RequestCanceled) {
					gotResponse(null, wex);
				} else {
					HttpWebResponse hwr = wex.Response as HttpWebResponse;
					if (null == hwr) {
						gotResponse(null, wex);
					} else {
						gotResponse(hwr, wex);
					}
				}
			}
			catch (Exception ex) {
				gotResponse(response, ex);
			}
		}

19 View Source File : MKMInteract.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

public static XmlDoreplacedent MakeRequest(string url, string method, string body = null)
      {
        // throw the exception ourselves to prevent sending requests to MKM that would end with this error 
        // because MKM tends to revoke the user's app token if it gets too many requests above the limit
        // the 429 code is the same MKM uses for this error
        if (denyAdditionalRequests)
        {
          // MKM resets the counter at 0:00 CET. CET is two hours ahead of UCT, so if it is after 22:00 of the same day
          // the denial was triggered, that means the 0:00 CET has preplaceded and we can reset the deny
          if (DateTime.UtcNow.Date == denyTime.Date && DateTime.UtcNow.Hour < 22)
            throw new HttpListenerException(429, "Too many requests. Wait for 0:00 CET for request counter to reset.");
          else
            denyAdditionalRequests = false;
        }
        // enforce the maxRequestsPerMinute limit - technically it's just an approximation as the requests
        // can arrive to MKM with some delay, but it should be close enough
        var now = DateTime.Now;
        while (requestTimes.Count > 0 && (now - requestTimes.Peek()).TotalSeconds > 60)
        {
          requestTimes.Dequeue();// keep only times of requests in the past 60 seconds
        }
        if (requestTimes.Count >= maxRequestsPerMinute)
        {
          // wait until 60.01 seconds preplaceded since the oldest request
          // we know (now - peek) is <= 60, otherwise it would get dequeued above,
          // so we are preplaceding a positive number to sleep
          System.Threading.Thread.Sleep(
              60010 - (int)(now - requestTimes.Peek()).TotalMilliseconds);
          requestTimes.Dequeue();
        }

        requestTimes.Enqueue(DateTime.Now);
        XmlDoreplacedent doc = new XmlDoreplacedent();
        for (int numAttempts = 0; numAttempts < MainView.Instance.Config.MaxTimeoutRepeat; numAttempts++)
        {
          try
          {
            var request = WebRequest.CreateHttp(url);
            request.Method = method;

            request.Headers.Add(HttpRequestHeader.Authorization, header.GetAuthorizationHeader(method, url));
            request.Method = method;

            if (body != null)
            {
              request.ServicePoint.Expect100Continue = false;
              request.ContentLength = System.Text.Encoding.UTF8.GetByteCount(body);
              request.ContentType = "text/xml";

              var writer = new StreamWriter(request.GetRequestStream());

              writer.Write(body);
              writer.Close();
            }

            var response = request.GetResponse() as HttpWebResponse;

            // just for checking EoF, it is not accessible directly from the Stream object
            // Empty streams can be returned for example for article fetches that result in 0 matches (happens regularly when e.g. seeking nonfoils in foil-only promo sets). 
            // Preplaceding empty stream to doc.Load causes exception and also sometimes seems to screw up the XML parser 
            // even when the exception is handled and it then causes problems for subsequent calls => first check if the stream is empty
            StreamReader s = new StreamReader(response.GetResponseStream());
            if (!s.EndOfStream)
              doc.Load(s);
            s.Close();
            int requestCount = int.Parse(response.Headers.Get("X-Request-Limit-Count"));
            int requestLimit = int.Parse(response.Headers.Get("X-Request-Limit-Max"));
            if (requestCount >= requestLimit)
            {
              denyAdditionalRequests = true;
              denyTime = DateTime.UtcNow;
            }
            MainView.Instance.Invoke(new MainView.UpdateRequestCountCallback(MainView.Instance.UpdateRequestCount), requestCount, requestLimit);
            break;
          }
          catch (WebException webEx)
          {
            // timeout can be either on our side (Timeout) or on server
            bool isTimeout = webEx.Status == WebExceptionStatus.Timeout;
            if (webEx.Status == WebExceptionStatus.ProtocolError)
            {
              if (webEx.Response is HttpWebResponse response)
              {
                isTimeout = response.StatusCode == HttpStatusCode.GatewayTimeout
                    || response.StatusCode == HttpStatusCode.ServiceUnavailable;
              }
            }
            // handle only timeouts, client handles other exceptions
            if (isTimeout && numAttempts + 1 < MainView.Instance.Config.MaxTimeoutRepeat)
              System.Threading.Thread.Sleep(1500); // wait and try again
            else
              throw webEx;
          }
        }
        return doc;
      }

19 View Source File : BybitRestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan

public static JToken CreatePrivateGetQuery(Client client, string end_point, Dictionary<string, string> parameters)
        {
            //int time_factor = 1;

            //if (client.NetMode == "Main")
            //    time_factor = 0;

            Dictionary<string, string> sorted_params = parameters.OrderBy(pair => pair.Key).ToDictionary(pair => pair.Key, pair => pair.Value);

            StringBuilder sb = new StringBuilder();

            foreach (var param in sorted_params)
            {
                sb.Append(param.Key + $"=" + param.Value + $"&");
            }

            long nonce = Utils.GetMillisecondsFromEpochStart();

            string str_params = sb.ToString() + "timestamp=" + (nonce).ToString();

            string url = client.RestUrl + end_point + $"?" + str_params;

            Uri uri = new Uri(url + $"&sign=" + BybitSigner.CreateSignature(client, str_params));

            var http_web_request = (HttpWebRequest)WebRequest.Create(uri);

            http_web_request.Method = "Get";

            http_web_request.Host = client.RestUrl.Replace($"https://", "");

            HttpWebResponse http_web_response = (HttpWebResponse)http_web_request.GetResponse();

            string response_msg;

            using (var stream = http_web_response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
                {
                    response_msg = reader.ReadToEnd();
                }
            }

            http_web_response.Close();

            if (http_web_response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("Failed request " + response_msg);
            }

            return JToken.Parse(response_msg);
        }

19 View Source File : BybitRestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan

public static JToken CreatePublicGetQuery(Client client, string end_point)
        {
            string url = client.RestUrl + end_point;

            Uri uri = new Uri(url);

            var http_web_request = (HttpWebRequest)WebRequest.Create(uri);

            HttpWebResponse http_web_response = (HttpWebResponse)http_web_request.GetResponse();

            string response_msg;

            using (var stream = http_web_response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
                {
                    response_msg = reader.ReadToEnd();
                }
            }

            http_web_response.Close();

            if (http_web_response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("Failed request " + response_msg);
            }

            return JToken.Parse(response_msg);
        }

19 View Source File : BitfinexClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Connect(string pubKey, string secKey)
        {
            _apiKey = pubKey;
            _secretKey = secKey;

            if (string.IsNullOrWhiteSpace(_apiKey) ||
                string.IsNullOrWhiteSpace(_secretKey))
            {
                return;
            }

            // check server availability for HTTP communication with it / проверяем доступность сервера для HTTP общения с ним
            Uri uri = new Uri(_baseUrlV1 + "/symbols");

            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            }
            catch (Exception exception)
            {
                SendLogMessage("Сервер не доступен. Отсутствует интернет. ", LogMessageType.Error);
                return;
            }

            IsConnected = true;

            CreateNewWebSocket();
        }

19 View Source File : HitbtcClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Connect()
        {
            if (string.IsNullOrEmpty(_pubKey)||
                string.IsNullOrEmpty(_secKey))
            {
                return;
            }

            // check server availability for HTTP communication with it / проверяем доступность сервера для HTTP общения с ним
            Uri uri = new Uri(_baseUrl+"/api/2");

            try
            {
                ServicePointManager.SecurityProtocol =
                    SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

                var httpWebRequest = (HttpWebRequest) WebRequest.Create(uri);

                var httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse();

            }
            catch (Exception exception)
            {
                SendLogMessage("Server is not available. Check internet connection." + exception.Message, LogMessageType.Error);
                return;
            }

            IsConnected = true;

            //if (Connected != null)
            //{
            //    Connected();
            //}

            Task converter = new Task(Converter);
            converter.Start();

            CreateNewWebSocket();
        }

19 View Source File : HitbtcClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public string CreateQuery(string method, string endpoint, string pubKey = "", string secKey = "", bool isAuth = false)
        {
            lock (_queryHttpLocker)
            {

                try
                {

                    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(_baseUrl + endpoint);
                    request.Method = method.ToUpper();
                    request.Accept = "application/json; charset=utf-8";

                    if (isAuth)
                    {
                        //For Basic Authentication
                        string authInfo = pubKey + ":" + secKey;
                        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                        request.Headers["Authorization"] = "Basic " + authInfo;

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

                        string strResponse = "";
                        using (var sr = new StreamReader(response.GetResponseStream()))
                        {
                            strResponse = sr.ReadToEnd();
                        }

                        return strResponse;
                    }
                    else
                    {
                        var response = (HttpWebResponse) request.GetResponse();

                        string strResponse = "";
                        using (var sr = new StreamReader(response.GetResponseStream()))
                        {
                            strResponse = sr.ReadToEnd();
                        }

                        return strResponse;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return null;
                }
            }
        }

19 View Source File : ServerSms.cs
License : Apache License 2.0
Project Creator : AlexWan

private string[] _smsc_send_cmd(string cmd, string arg, string[] files = null)
        {
            arg = "login=" + _urlencode(SmscLogin) + "&psw=" + _urlencode(SmscPreplacedword) + "&fmt=1&charset=" + SmscCharset + "&" + arg;

            string url = (SmscHttps ? "https" : "http") + "://smsc.ru/sys/" + cmd + ".php" + (SmscPost ? "" : "?" + arg);

            string ret;
            int i = 0;
            HttpWebRequest request;
            StreamReader sr;
            HttpWebResponse response;

            do
            {
                if (i > 0)
                    System.Threading.Thread.Sleep(2000 + 1000 * i);

                if (i == 2)
                    url = url.Replace("://smsc.ru/", "://www2.smsc.ru/");

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

                if (SmscPost) {
                    request.Method = "POST";

                    string postHeader, boundary = "----------" + DateTime.Now.Ticks.ToString("x");
                    byte[] postHeaderBytes, boundaryBytes = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"), tbuf;
                    StringBuilder sb = new StringBuilder();
                    int bytesRead;

                    byte[] output = new byte[0];

                    if (files == null) {
                        request.ContentType = "application/x-www-form-urlencoded";
                        output = Encoding.UTF8.GetBytes(arg);
                        request.ContentLength = output.Length;
                    }
                    else {
                        request.ContentType = "multipart/form-data; boundary=" + boundary;

                        string[] par = arg.Split('&');
                        int fl = files.Length;

                        for (int pcnt = 0; pcnt < par.Length + fl; pcnt++)
                        {
                            sb.Clear();

                            sb.Append("--");
                            sb.Append(boundary);
                            sb.Append("\r\n");
                            sb.Append("Content-Disposition: form-data; name=\"");

                            bool pof = pcnt < fl;
                            String[] nv = new String[0];

                            if (pof)
                            {
                                sb.Append("File" + (pcnt + 1));
                                sb.Append("\"; filename=\"");
                                sb.Append(Path.GetFileName(files[pcnt]));
                            }
                            else {
                                nv = par[pcnt - fl].Split('=');
                                sb.Append(nv[0]);
                            }

                            sb.Append("\"");
                            sb.Append("\r\n");
                            sb.Append("Content-Type: ");
                            sb.Append(pof ? "application/octet-stream" : "text/plain; charset=\"" + SmscCharset + "\"");
                            sb.Append("\r\n");
                            sb.Append("Content-Transfer-Encoding: binary");
                            sb.Append("\r\n");
                            sb.Append("\r\n");

                            postHeader = sb.ToString();
                            postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

                            output = _concatb(output, postHeaderBytes);

                            if (pof)
                            {
                                FileStream fileStream = new FileStream(files[pcnt], FileMode.Open, FileAccess.Read);

                                // Write out the file contents
                                byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];

                                bytesRead = 0;
                                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    tbuf = buffer;
                                    Array.Resize(ref tbuf, bytesRead);

                                    output = _concatb(output, tbuf);
                                }
                            }
                            else {
                                byte[] vl = Encoding.UTF8.GetBytes(nv[1]);
                                output = _concatb(output, vl);
                            }

                            output = _concatb(output, Encoding.UTF8.GetBytes("\r\n"));
                        }
                        output = _concatb(output, boundaryBytes);

                        request.ContentLength = output.Length;
                    }

                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(output, 0, output.Length);
                }

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

                    sr = new StreamReader(response.GetResponseStream());
                    ret = sr.ReadToEnd();
                }
                catch (WebException) {
                    ret = "";
                }
            }
            while (ret == "" && ++i < 4);

            if (ret == "") {
                if (SmscDebug)
                    _print_debug("Ошибка чтения адреса: " + url);

                ret = ","; // bogus response / фиктивный ответ
            }

            char delim = ',';

            if (cmd == "status")
            {
                string[] par = arg.Split('&');

                for (i = 0; i < par.Length; i++)
                {
                    string[] lr = par[i].Split("=".ToCharArray(), 2);

                    if (lr[0] == "id" && lr[1].IndexOf("%2c") > 0) // comma in id - multiple request / запятая в id - множественный запрос
                        delim = '\n';
                }
            }

            return ret.Split(delim);
        }

19 View Source File : BitMaxProClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public void Connect()
        {
            if (string.IsNullOrEmpty(_apiKey) ||
                string.IsNullOrEmpty(_secretKey))
            {
                return;
            }

            // check server availability for HTTP communication with it / проверяем доступность сервера для HTTP общения с ним
            Uri uri = new Uri(_baseUrl + "api/pro/v1/replacedets");
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            }
            catch (Exception)
            {
                SendLogMessage("Server is not available. No internet available. ", LogMessageType.Error);
                return;
            }

            _accountGroup = GetAccountGroup().Account.AccountGroup;

            IsConnected = true;

            if (Connected != null)
            {
                Connected();
            }

            Thread converter = new Thread(Converter);
            converter.CurrentCulture = new CultureInfo("ru-RU");
            converter.IsBackground = true;
            converter.Start();

            Thread publicConverter = new Thread(PublicDataConverter);
            publicConverter.CurrentCulture = new CultureInfo("ru-RU");
            publicConverter.IsBackground = true;
            publicConverter.Start();

            CreateDataStream();
            Thread.Sleep(1000);
            CreateUserDataStream();
        }

19 View Source File : BitMaxProClient.cs
License : Apache License 2.0
Project Creator : AlexWan

private string GetData(string apiPath, bool auth = false, string accGroup = null, string jsonContent = null,
            string orderId = null, string time = null, Method method = Method.GET, bool need = false)
        {
            lock (_queryLocker)
            {
                try
                {
                    Uri uri;

                    HttpWebRequest httpWebRequest;

                    if (!auth)
                    {
                        uri = new Uri(_baseUrl + "api/pro/v1/" + apiPath);

                        httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                    }
                    else
                    {
                        if (accGroup == null)
                        {
                            uri = new Uri(_baseUrl + "api/pro/v1/" + apiPath);
                        }
                        else
                        {
                            var str = _baseUrl + accGroup + "/" + "api/pro/v1/" + apiPath;

                            if (need)
                            {
                                str += "?n=10&executedOnly=True";
                            }

                            uri = new Uri(str);
                        }

                        string timestamp;

                        if (time == null)
                        {
                            timestamp = TimeManager.GetUnixTimeStampMilliseconds().ToString();
                        }
                        else
                        {
                            timestamp = time;
                        }

                        string signatureMsg;

                        if (orderId == null)
                        {
                            signatureMsg = timestamp + "+" + apiPath;
                        }
                        else
                        {
                            //signatureMsg = timestamp + "+" + apiPath + "+" + orderId;
                            signatureMsg = timestamp + "+" + "order";
                        }

                        if (signatureMsg.EndsWith("cash/balance"))
                        {
                            signatureMsg = signatureMsg.Replace("cash/", "");
                            //signatureMsg = signatureMsg.Remove(signatureMsg.Length - 11, 4);
                        }

                        if (signatureMsg.EndsWith("margin/balance"))
                        {
                            signatureMsg = signatureMsg.Replace("margin/", "");
                            //signatureMsg = signatureMsg.Remove(signatureMsg.Length - 13, 6);
                        }


                        var codedSignature = CreateSignature(signatureMsg);

                        httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

                        httpWebRequest.Headers.Add("x-auth-key", _apiKey);
                        httpWebRequest.Headers.Add("x-auth-signature", codedSignature);
                        httpWebRequest.Headers.Add("x-auth-timestamp", timestamp.ToString());

                        if (orderId != null)
                        {
                            httpWebRequest.Headers.Add("x-auth-coid", orderId);
                        }
                    }

                    httpWebRequest.Method = method.ToString();

                    if (jsonContent != null)
                    {
                        var data = Encoding.UTF8.GetBytes(jsonContent);

                        httpWebRequest.ContentType = "application/json";

                        httpWebRequest.ContentLength = data.Length;

                        using (Stream requestStream = httpWebRequest.GetRequestStream())
                        {
                            requestStream.Write(data, 0, data.Length);
                        }
                    }

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

                    string responseMsg;

                    using (var stream = httpWebResponse.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
                        {
                            responseMsg = reader.ReadToEnd();
                        }
                    }

                    httpWebResponse.Close();

                    return responseMsg;
                }
                catch (InvalidOperationException invalidOperationException)
                {
                    SendLogMessage("Failed to get stream to read response from server..   " + invalidOperationException.Message, LogMessageType.Error);
                    return null;
                }
                catch (Exception exception)
                {
                    SendLogMessage(exception.Message, LogMessageType.Error);
                    return null;
                }
            }
        }

See More Examples