Here are the examples of the csharp api System.Net.WebRequest.Create(System.Uri) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
596 Examples
19
View Source File : DownloadFile.cs
License : MIT License
Project Creator : 404Lcc
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
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 : SoapSearch.cs
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport
private HttpWebRequest BuildRequest(string soapMessage, string soapAction) {
HttpWebRequest Request;
Request = (HttpWebRequest)WebRequest.Create(AppSettings.SearchUrl(this.Style));
try {
Request.Timeout = int.Parse(AppSettings.RequestTimeoutInMilliseconds, CultureInfo.CurrentCulture);
}
catch {
Request.Timeout = 100000;
}
Request.Headers.Add("SoapAction", soapAction);
Request.ContentType = "text/xml; charset=utf-8";
Request.ContentLength = soapMessage.Length;
Request.Proxy = GetWebProxy();
Request.Method = "POST";
return (Request);
}
19
View Source File : SCaddins.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
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);
}
19
View Source File : ClientFactory.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public virtual WebRequest CreateHttpWebRequest(SharePointConnection connection, Uri uri)
{
if (connection == null) throw new ArgumentNullException("connection");
var request = WebRequest.Create(uri);
UpdateWebRequest(connection, request);
return request;
}
19
View Source File : ClientFactory.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static HttpWebRequest CreateRequest(Uri uri, int? timeout)
{
var request = WebRequest.Create(uri) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = new CookieContainer();
request.AllowAutoRedirect = false;
request.UserAgent = _userAgent;
if (timeout != null) request.Timeout = timeout.Value;
return request;
}
19
View Source File : Startup.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
private void SendJsonMessageToChat(string jsonMessage)
{
var discordChannelUrl = Configuration["DiscordChannelUrl"];
if (string.IsNullOrWhiteSpace(discordChannelUrl))
{
Console.WriteLine("DiscordChannelUrl not specified in configuration file.");
return;
}
var discordPostRequest = WebRequest.Create(discordChannelUrl);
discordPostRequest.ContentType = "application/json";
discordPostRequest.Method = WebRequestMethods.Http.Post;
var buffer = Encoding.ASCII.GetBytes(jsonMessage);
discordPostRequest.ContentLength = buffer.Length;
var stream = discordPostRequest.GetRequestStream();
stream.Write(buffer, 0, buffer.Length);
stream.Close();
try
{
var response = (HttpWebResponse) discordPostRequest.GetResponse();
if (response.StatusCode != HttpStatusCode.NoContent)
{
Console.WriteLine($"Discord returned status: {response.StatusCode}");
}
}
catch (Exception e)
{
Console.WriteLine($"Unable to send message to discord channel. Exception caught:\n\n{e}");
}
}
19
View Source File : HttpHelper.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
static HttpWebRequest Http_Core(string _type, string _url, Encoding _encoding, List<replacedem> _header, object _conmand = null)
{
#region 启动HTTP请求之前的初始化操作
bool isget = false;
if (_type == "GET")
{
isget = true;
}
if (isget)
{
if (_conmand is List<replacedem>)
{
List<replacedem> _conmand_ = (List<replacedem>)_conmand;
string param = "";
foreach (replacedem item in _conmand_)
{
if (string.IsNullOrEmpty(param))
{
if (_url.Contains("?"))
{
param += "&" + item.Name + "=" + item.Value;
}
else
{
param = "?" + item.Name + "=" + item.Value;
}
}
else
{
param += "&" + item.Name + "=" + item.Value;
}
}
_url += param;
}
}
Uri uri = null;
try
{
uri = new Uri(_url);
}
catch { }
#endregion
if (uri != null)
{
//string _scheme = uri.Scheme.ToUpper();
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Proxy = null;
req.Host = uri.Host;
req.Method = _type;
req.AllowAutoRedirect = false;
bool isContentType = true;
#region 设置请求头
if (_header != null && _header.Count > 0)
{
bool isnotHeader = true;
System.Collections.Specialized.NameValueCollection collection = null;
foreach (replacedem item in _header)
{
string _Lower_Name = item.Name.ToLower();
switch (_Lower_Name)
{
case "host":
req.Host = item.Value;
break;
case "accept":
req.Accept = item.Value;
break;
case "user-agent":
req.UserAgent = item.Value;
break;
case "referer":
req.Referer = item.Value;
break;
case "content-type":
isContentType = false;
req.ContentType = item.Value;
break;
case "cookie":
#region 设置COOKIE
string _cookie = item.Value;
CookieContainer cookie_container = new CookieContainer();
if (_cookie.IndexOf(";") >= 0)
{
string[] arrCookie = _cookie.Split(';');
//加载Cookie
//cookie_container.SetCookies(new Uri(url), cookie);
foreach (string sCookie in arrCookie)
{
if (string.IsNullOrEmpty(sCookie))
{
continue;
}
if (sCookie.IndexOf("expires") > 0)
{
continue;
}
cookie_container.SetCookies(uri, sCookie);
}
}
else
{
cookie_container.SetCookies(uri, _cookie);
}
req.CookieContainer = cookie_container;
#endregion
break;
default:
if (isnotHeader && collection == null)
{
var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (property != null)
{
collection = property.GetValue(req.Headers, null) as System.Collections.Specialized.NameValueCollection;
}
isnotHeader = false;
}
//设置对象的Header数据
if (collection != null)
{
collection[item.Name] = item.Value;
}
break;
}
}
}
#endregion
#region 设置POST数据
if (!isget)
{
if (_conmand != null)
{
if (_conmand is List<replacedem>)
{
List<replacedem> _conmand_ = (List<replacedem>)_conmand;
//POST参数
if (isContentType)
{
req.ContentType = "application/x-www-form-urlencoded";
}
string param = "";
foreach (replacedem item in _conmand_)
{
if (string.IsNullOrEmpty(param))
{
param = item.Name + "=" + item.Value;
}
else
{
param += "&" + item.Name + "=" + item.Value;
}
}
byte[] bs = _encoding.GetBytes(param);
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}
}
else if (_conmand is string[])
{
try
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
req.ContentType = "multipart/form-data; boundary=" + boundary;
using (Stream reqStream = req.GetRequestStream())
{
string[] files = (string[])_conmand;
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
byte[] buff = new byte[1024];
for (int i = 0; i < files.Length; i++)
{
string file = files[i];
reqStream.Write(boundarybytes, 0, boundarybytes.Length);
string contentType = MimeMappingProvider.Shared.GetMimeMapping(file);
//string contentType = System.Web.MimeMapping.GetMimeMapping(file);
//string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(file), contentType);
string header = string.Format(headerTemplate, "media", Path.GetFileName(file), contentType);//微信
byte[] headerbytes = _encoding.GetBytes(header);
reqStream.Write(headerbytes, 0, headerbytes.Length);
using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
int contentLen = fileStream.Read(buff, 0, buff.Length);
int Value = contentLen;
//文件上传开始
//tProgress.Invoke(new Action(() =>
//{
// tProgress.Maximum = (int)fileStream.Length;
// tProgress.Value = Value;
//}));
while (contentLen > 0)
{
//文件上传中
reqStream.Write(buff, 0, contentLen);
contentLen = fileStream.Read(buff, 0, buff.Length);
Value += contentLen;
//tProgress.Invoke(new Action(() =>
//{
// tProgress.Value = Value;
//}));
}
}
}
//文件上传结束
reqStream.Write(endbytes, 0, endbytes.Length);
}
}
catch
{
if (isContentType)
{
req.ContentType = null;
}
req.ContentLength = 0;
}
}
else
{
//POST参数
if (isContentType)
{
req.ContentType = "application/x-www-form-urlencoded";
}
string param = _conmand.ToString();
byte[] bs = _encoding.GetBytes(param);
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}
}
}
else
{
req.ContentLength = 0;
}
}
#endregion
return req;
}
catch
{
}
}
return null;
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
private void ReadData()
{
currentlyReading = true;
StreamReader sr = null;
string checkVer = c_toolVer;
bool[] read = { false, false, false, false, false, false,
false, false, false };
try
{
sr = new StreamReader(settingsFile);
while (sr.Peek() > -1)
{
StringRead(sr.ReadLine(), ref read, ref checkVer);
}
}
catch
{
//if (!read[0]) toolVer = c_toolVer;
/*if (!read[1]) pFoV = c_pFoV;
if (!read[2]) fFoV = c_FoV;
if (!read[3]) doBeep = c_doBeep;
if (!read[4]) updateChk = c_updateChk;
if (!read[5]) hotKeys = c_hotKeys;
if (!read[6]) catchKeys[0] = c_catchKeys[0];
if (!read[7]) catchKeys[1] = c_catchKeys[1];
if (!read[8]) catchKeys[2] = c_catchKeys[2];*/
}
finally
{
if (sr != null) sr.Close();
}
if (checkVer != c_toolVer)
pFoV = c_pFoV;
if (!requestSent)
{
try
{
request = (HttpWebRequest)WebRequest.Create(c_checkURL);
request.BeginGetResponse(new AsyncCallback(UpdateResponse), null);
requestSent = true;
}
catch { }
}
currentlyReading = false;
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
private void chkUpdate_CheckedChanged(object sender, EventArgs e)
{
updateChk = chkUpdate.Checked;
if (updateChk && !requestSent)
{
request = (HttpWebRequest)WebRequest.Create(c_checkURL);
request.BeginGetResponse(new AsyncCallback(UpdateResponse), null);
requestSent = true;
}
}
19
View Source File : StorageProxy.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public Dictionary<string, object> GetConfigurations()
{
try
{
if (!string.IsNullOrEmpty(Global.Config.StorageService))
{
WebRequest request = HttpWebRequest.Create(Global.Config.StorageService.Replace("{0}", "configuration"));
WebResponse response = request.GetResponse();
//response.GetResponseStream();
return null;
}
else
{
return _localStorage.GetConfigurations();
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
}
19
View Source File : StorageProxy.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public void WriteSessionInfo(Core.SessionInfo session)
{
try
{
if (!string.IsNullOrEmpty(Global.Config.StorageService))
{
WebRequest request = HttpWebRequest.Create(Global.Config.StorageService.Replace("{0}", "session"));
request.Method = "POST";
//request.GetRequestStream();
WebResponse response = request.GetResponse();
//response.GetResponseStream();
}
else
{
_localStorage.WriteSessionInfo(session);
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
}
19
View Source File : StorageProxy.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public void WriteSessionEnd(string sessionId)
{
try
{
if (!string.IsNullOrEmpty(Global.Config.StorageService))
{
WebRequest request = HttpWebRequest.Create(Global.Config.StorageService.Replace("{0}", "end"));
request.Method = "POST";
//request.GetRequestStream();
WebResponse response = request.GetResponse();
//response.GetResponseStream();
}
else
{
_localStorage.WriteSessionEnd(sessionId);
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
}
19
View Source File : StorageProxy.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public void WriteSnapshot(Core.Snapshot sshot)
{
try
{
if (!string.IsNullOrEmpty(Global.Config.StorageService))
{
WebRequest request = HttpWebRequest.Create(Global.Config.StorageService.Replace("{0}", "snapshot"));
request.Method = "POST";
//request.GetRequestStream();
WebResponse response = request.GetResponse();
//response.GetResponseStream();
}
else
{
_localStorage.WriteSnapshot(sshot);
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
}
19
View Source File : BitMaxProClient.cs
License : Apache License 2.0
Project Creator : AlexWan
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;
}
}
}
19
View Source File : BybitRestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
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 : BitfinexClient.cs
License : Apache License 2.0
Project Creator : AlexWan
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
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 : BitMaxProClient.cs
License : Apache License 2.0
Project Creator : AlexWan
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 : BybitRestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
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 : BybitRestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static JToken CreatePrivatePostQuery(Client client, string end_point, Dictionary<string, string> parameters)
{
parameters.Add("timestamp", (Utils.GetMillisecondsFromEpochStart()).ToString());
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)
{
if (param.Value == "false" || param.Value == "true")
sb.Append("\"" + param.Key + "\":" + param.Value + ",");
else
sb.Append("\"" + param.Key + "\":\"" + param.Value + "\",");
}
StringBuilder sb_signer = new StringBuilder();
foreach (var param in sorted_params)
{
sb_signer.Append(param.Key + $"=" + param.Value + $"&");
}
string str_signer = sb_signer.ToString();
str_signer = str_signer.Remove(str_signer.Length - 1);
sb.Append("\"sign\":\"" + BybitSigner.CreateSignature(client, str_signer) + "\""); // api_key=bLP2z8x0sEeFHgt14S&close_on_trigger=False&order_link_id=&order_type=Limit&price=11018.00&qty=1&side=Buy&symbol=BTCUSD&time_in_force=GoodTillCancel×tamp=1600513511844
// api_key=bLP2z8x0sEeFHgt14S&close_on_trigger=False&order_link_id=&order_type=Limit&price=10999.50&qty=1&side=Buy&symbol=BTCUSD&time_in_force=GoodTillCancel×tamp=1600514673126
// {"api_key":"bLP2z8x0sEeFHgt14S","close_on_trigger":"False","order_link_id":"","order_type":"Limit","price":"11050.50","qty":"1","side":"Buy","symbol":"BTCUSD","time_in_force":"GoodTillCancel","timestamp":"1600515164173","sign":"fb3c69fa5d30526810a4b60fe4b8f216a3baf2c81745289ff7ddc21ab8232ccc"}
string url = client.RestUrl + end_point;
string str_data = "{" + sb.ToString() + "}";
byte[] data = Encoding.UTF8.GetBytes(str_data);
Uri uri = new Uri(url);
var http_web_request = (HttpWebRequest)WebRequest.Create(uri);
http_web_request.Method = "POST";
http_web_request.ContentType = "application/json";
http_web_request.ContentLength = data.Length;
using (Stream req_tream = http_web_request.GetRequestStream())
{
req_tream.Write(data, 0, data.Length);
}
HttpWebResponse httpWebResponse = (HttpWebResponse)http_web_request.GetResponse();
string response_msg;
using (var stream = httpWebResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
response_msg = reader.ReadToEnd();
}
}
httpWebResponse.Close();
return JToken.Parse(response_msg);
}
19
View Source File : BitStampClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public void Connect()
{
if (string.IsNullOrWhiteSpace(_apiKeyPublic) ||
string.IsNullOrWhiteSpace(_apiKeySecret) ||
string.IsNullOrWhiteSpace(_clientId))
{
return;
}
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// check server availability for HTTP communication with it / проверяем доступность сервера для HTTP общения с ним
Uri uri = new Uri("https://www.bitstamp.net");
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch
{
LogMessageEvent("Сервер не доступен. Отсутствуюет интернет. ", LogMessageType.Error);
return;
}
IsConnected = true;
if (Connected != null)
{
Connected();
}
// start stream data through WebSocket / запускаем потоковые данные через WebSocket
_ws = new ClientWebSocket();
Uri wsUri = new Uri("wss://ws.bitstamp.net");
_ws.ConnectAsync(wsUri, CancellationToken.None).Wait();
if (_ws.State == WebSocketState.Open)
{
if (Connected != null)
{
Connected.Invoke();
}
IsConnected = true;
}
Thread worker = new Thread(GetRes);
worker.CurrentCulture = new CultureInfo("ru-RU");
worker.IsBackground = true;
worker.Start(_ws);
Thread converter = new Thread(Converter);
converter.CurrentCulture = new CultureInfo("ru-RU");
converter.IsBackground = true;
converter.Start();
}
19
View Source File : RestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string SendPostQuery(string method, string url, string endPoint, byte[] data, Dictionary<string, string> headers)
{
Uri uri = new Uri(url + endPoint);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Method = method;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
foreach (var header in headers)
{
httpWebRequest.Headers.Add(header.Key, header.Value);
}
httpWebRequest.ContentLength = data.Length;
using (Stream reqStream = httpWebRequest.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
string responseMsg;
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var stream = httpWebResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
responseMsg = reader.ReadToEnd();
}
}
return responseMsg;
}
19
View Source File : RestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string SendGetQuery(string method, string baseUri, string endPoint, Dictionary<string, string> headers)
{
Uri uri = new Uri(baseUri + endPoint);
if (uri.ToString().Contains("?"))
{
var t = 6;
}
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Method = method;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
foreach (var header in headers)
{
httpWebRequest.Headers.Add(header.Key, header.Value);
}
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();
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Failed request " + responseMsg);
}
return responseMsg;
}
19
View Source File : LivecoinClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public void Connect()
{
if (string.IsNullOrEmpty(_pubKey) ||
string.IsNullOrEmpty(_secKey))
{
return;
}
string endPoint = "exchange/ticker?";
string param = "currencyPair=BTC/USD";
_isDisposed = false;
// check server availability for HTTP communication with it / проверяем доступность сервера для HTTP общения с ним
Uri uri = new Uri(_baseUri + endPoint + param);
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (Exception exception)
{
SendLogMessage("Сервер не доступен. Отсутствует интернет " + exception.Message, LogMessageType.Error);
return;
}
Thread converter = new Thread(Converter);
converter.CurrentCulture = new CultureInfo("ru-RU");
converter.Name = "LivecoinConverterFread_" + _portfolioName;
converter.IsBackground = true;
converter.Start();
CreateNewWebSocket();
}
19
View Source File : RestChannel.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string SendGetQuery(string baseUri, string endPoint)
{
Uri uri = new Uri(baseUri + endPoint);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
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();
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Failed request " + responseMsg);
}
return responseMsg;
}
19
View Source File : RestChannel.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string SendPostQuery(string url, string endPoint, byte[] data, Dictionary<string, string> headers)
{
Uri uri = new Uri(url + endPoint);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Method = "post";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
foreach (var header in headers)
{
httpWebRequest.Headers.Add(header.Key, header.Value);
}
httpWebRequest.ContentLength = data.Length;
using (Stream reqStream = httpWebRequest.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
string responseMsg;
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var stream = httpWebResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
responseMsg = reader.ReadToEnd();
}
}
return responseMsg;
}
19
View Source File : ZBServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private string RequestCandlesFromExchange(string needIntervalForQuery, string security)
{
Uri uri = new Uri(UriForCandles + $"market={security}&type={needIntervalForQuery}");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Failed to get candles on the instrument " + security);
}
string responseMsg;
using (var stream = httpWebResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException()))
{
responseMsg = reader.ReadToEnd();
}
}
httpWebResponse.Close();
return responseMsg;
}
19
View Source File : WebExtensions.cs
License : MIT License
Project Creator : aljazsim
License : MIT License
Project Creator : aljazsim
private static T ExecuteRequest<T>(this Uri uri, Func<HttpWebResponse, T> getDataFunc, byte[] data = null, string requestContentType = "text/plain", int redirectCount = 0, TimeSpan? timeout = null)
{
HttpWebRequest request;
T responseContent = default(T);
int maxRedirects = 30;
string location = "Location";
uri.CannotBeNull();
getDataFunc.CannotBeNull();
requestContentType.CannotBeNullOrEmpty();
redirectCount.MustBeGreaterThanOrEqualTo(0);
// make request
request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.Method = data == null ? "GET" : "POST";
request.KeepAlive = false;
request.ContentType = requestContentType;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.CookieContainer = new CookieContainer();
request.UserAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1300.0 Iron/23.0.1300.0 Safari/537.11";
request.AllowAutoRedirect = false;
request.Timeout = (int)(timeout == null ? TimeSpan.FromSeconds(10) : (TimeSpan)timeout).TotalMilliseconds;
// setup request contents
if (data != null)
{
request.ContentLength = data.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
}
}
// get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.Redirect)
{
if (redirectCount <= maxRedirects)
{
if (response.Headers.AllKeys.Contains(location) &&
response.Headers[location].IsNotNullOrEmpty())
{
if (Uri.TryCreate(response.Headers[location], UriKind.Absolute, out uri))
{
responseContent = uri.ExecuteRequest(getDataFunc, data, requestContentType, ++redirectCount);
}
}
}
}
else
{
responseContent = getDataFunc(response);
}
}
return responseContent;
}
19
View Source File : AuthorizationPage.cs
License : GNU General Public License v3.0
Project Creator : Amebis
License : GNU General Public License v3.0
Project Creator : Amebis
public void OnRequestAuthorization(object sender, RequestAuthorizationEventArgs e)
{
if (!(sender is Server authenticatingServer))
return;
e.TokenOrigin = RequestAuthorizationEventArgs.TokenOriginType.None;
e.AccessToken = null;
lock (Properties.Settings.Default.AccessTokenCache)
{
if (e.SourcePolicy != RequestAuthorizationEventArgs.SourcePolicyType.ForceAuthorization)
{
var key = authenticatingServer.Base.AbsoluteUri;
if (Properties.Settings.Default.AccessTokenCache.TryGetValue(key, out var accessToken))
{
if (!e.ForceRefresh && DateTime.Now < accessToken.Expires)
{
e.TokenOrigin = RequestAuthorizationEventArgs.TokenOriginType.Saved;
e.AccessToken = accessToken;
return;
}
// Token refresh was explicitly requested or the token expired. Refresh it.
if (accessToken is InvalidToken)
{
// Invalid token is not refreshable.
Properties.Settings.Default.AccessTokenCache.Remove(key);
}
else
{
// Get API endpoints. (Not called from the UI thread or already cached by now. Otherwise it would need to be spawned as a background task to avoid deadlock.)
var api = authenticatingServer.GetEndpoints(Window.Abort.Token);
// Prepare web request.
var request = WebRequest.Create(api.TokenEndpoint);
request.CachePolicy = Xml.Response.CachePolicy;
request.Proxy = null;
if (request is HttpWebRequest requestHTTP)
requestHTTP.UserAgent = Xml.Response.UserAgent;
try
{
accessToken = accessToken.RefreshToken(request, null, Window.Abort.Token);
// Update access token cache.
Properties.Settings.Default.AccessTokenCache[key] = accessToken;
// If we got here, return the token.
e.TokenOrigin = RequestAuthorizationEventArgs.TokenOriginType.Refreshed;
e.AccessToken = accessToken;
return;
}
catch (AccessTokenException ex)
{
if (ex.ErrorCode == AccessTokenException.ErrorCodeType.InvalidGrant)
{
// The grant has been revoked. Drop the access token.
Properties.Settings.Default.AccessTokenCache.Remove(key);
}
else
throw;
}
}
}
}
if (e.SourcePolicy != RequestAuthorizationEventArgs.SourcePolicyType.SavedOnly)
{
// We're in the background thread - notify via dispatcher.
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
Wizard.TaskCount++;
ReturnPage = Wizard.CurrentPage;
Wizard.CurrentPage = this;
AuthorizationInProgress = new CancellationTokenSource();
}));
try
{
// Get API endpoints. (Not called from the UI thread. Otherwise it would need to be spawned as a background task to avoid deadlock.)
var api = authenticatingServer.GetEndpoints(Window.Abort.Token);
// Prepare new authorization grant.
AuthorizationGrant authorizationGrant = null;
Uri callbackUri = null;
var httpListener = new eduOAuth.HttpListener(IPAddress.Loopback, 0);
httpListener.HttpCallback += (object _, HttpCallbackEventArgs eHTTPCallback) =>
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
callbackUri = eHTTPCallback.Uri;
AuthorizationInProgress.Cancel();
Wizard.CurrentPage = ReturnPage;
}));
};
httpListener.HttpRequest += (object _, HttpRequestEventArgs eHTTPRequest) =>
{
if (eHTTPRequest.Uri.AbsolutePath.ToLowerInvariant() == "/favicon.ico")
{
var res = System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/Resources/App.ico"));
eHTTPRequest.Type = res.ContentType;
eHTTPRequest.Content = res.Stream;
}
};
httpListener.Start();
try
{
// Make the authorization URI.
authorizationGrant = new AuthorizationGrant(
api.AuthorizationEndpoint,
new Uri(string.Format("http://{0}:{1}/callback", ((IPEndPoint)httpListener.LocalEndpoint).Address, ((IPEndPoint)httpListener.LocalEndpoint).Port)),
Properties.Settings.Default.ClientId + ".windows",
new HashSet<string>() { e.Scope },
AuthorizationGrant.CodeChallengeAlgorithmType.S256);
var authorizationUri = authorizationGrant.AuthorizationUri;
if (authenticatingServer is SecureInternetServer srv &&
srv.AuthenticationUriTemplate != null)
{
// Envelope authorization URI and organization identifier.
authorizationUri = new Uri(srv.AuthenticationUriTemplate
.Replace("@RETURN_TO@", HttpUtility.UrlEncode(authorizationUri.ToString()))
.Replace("@ORG_ID@", HttpUtility.UrlEncode(srv.OrganizationId)));
}
// Trigger authorization.
Process.Start(authorizationUri.ToString());
// Wait for a change: either callback is invoked, either user cancels.
CancellationTokenSource.CreateLinkedTokenSource(AuthorizationInProgress.Token, Window.Abort.Token).Token.WaitHandle.WaitOne();
}
finally
{
// Delay HTTP server shutdown allowing browser to finish loading content.
new Thread(new ThreadStart(() =>
{
Window.Abort.Token.WaitHandle.WaitOne(5 * 1000);
httpListener.Stop();
})).Start();
}
if (callbackUri == null)
throw new OperationCanceledException();
// Get access token from authorization grant.
var request = WebRequest.Create(api.TokenEndpoint);
request.CachePolicy = Xml.Response.CachePolicy;
request.Proxy = null;
if (request is HttpWebRequest requestHTTP)
requestHTTP.UserAgent = Xml.Response.UserAgent;
e.AccessToken = authorizationGrant.ProcessResponse(
HttpUtility.ParseQueryString(callbackUri.Query),
request,
null,
Window.Abort.Token);
Window.Abort.Token.ThrowIfCancellationRequested();
// Save access token to the cache.
e.TokenOrigin = RequestAuthorizationEventArgs.TokenOriginType.Authorized;
Properties.Settings.Default.AccessTokenCache[authenticatingServer.Base.AbsoluteUri] = e.AccessToken;
}
finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--)); }
}
}
}
19
View Source File : SelfUpdateProgressPage.cs
License : GNU General Public License v3.0
Project Creator : Amebis
License : GNU General Public License v3.0
Project Creator : Amebis
public override void OnActivate()
{
base.OnActivate();
// Setup self-update.
var selfUpdate = new BackgroundWorker() { WorkerReportsProgress = true };
selfUpdate.DoWork += (object sender, DoWorkEventArgs e) =>
{
selfUpdate.ReportProgress(0);
var random = new Random();
var tempFolder = Path.GetTempPath();
var workingFolder = tempFolder + Path.GetRandomFileName() + "\\";
Directory.CreateDirectory(workingFolder);
try
{
string installerFilename = null;
FileStream installerFile = null;
// Download installer.
while (DownloadUris.Count > 0)
{
Window.Abort.Token.ThrowIfCancellationRequested();
var uriIndex = random.Next(DownloadUris.Count);
try
{
var binaryUri = DownloadUris[uriIndex];
Trace.TraceInformation("Downloading installer file from {0}...", binaryUri.AbsoluteUri);
var request = WebRequest.Create(binaryUri);
request.Proxy = null;
using (var response = request.GetResponse())
{
// 1. Get installer filename from Content-Disposition header.
// 2. Get installer filename from the last segment of URI path.
// 3. Fallback to a predefined installer filename.
try { installerFilename = Path.GetFullPath(workingFolder + new ContentDisposition(request.Headers["Content-Disposition"]).FileName); }
catch
{
try { installerFilename = Path.GetFullPath(workingFolder + binaryUri.Segments[binaryUri.Segments.Length - 1]); }
catch { installerFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup.exe"); }
}
// Save response data to file.
installerFile = File.Open(installerFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
try
{
using (var stream = response.GetResponseStream())
{
installerFile.Seek(0, SeekOrigin.Begin);
var hash = new eduEd25519.SHA256();
var buffer = new byte[1048576];
long offset = 0, total = response.ContentLength;
for (; ; )
{
// Wait for the data to arrive.
Window.Abort.Token.ThrowIfCancellationRequested();
var bufferLength = stream.Read(buffer, 0, buffer.Length);
if (bufferLength == 0)
break;
//Window.Abort.Token.WaitHandle.WaitOne(100); // Mock a slow link for testing.
// Append it to the file and hash it.
Window.Abort.Token.ThrowIfCancellationRequested();
installerFile.Write(buffer, 0, bufferLength);
hash.TransformBlock(buffer, 0, bufferLength, buffer, 0);
// Report progress.
offset += bufferLength;
selfUpdate.ReportProgress((int)(offset * 100 / total));
}
hash.TransformFinalBlock(buffer, 0, 0);
if (!hash.Hash.SequenceEqual(Hash))
throw new DownloadedFileCorruptException(string.Format(Resources.Strings.ErrorDownloadedFileCorrupt, binaryUri.AbsoluteUri));
installerFile.SetLength(installerFile.Position);
break;
}
}
catch
{
// Close installer file.
installerFile.Close();
installerFile = null;
// Delete installer file. If possible.
Trace.TraceInformation("Deleting file {0}...", installerFilename);
try { File.Delete(installerFilename); }
catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }
installerFilename = null;
throw;
}
}
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
Trace.TraceWarning("Error: {0}", ex.ToString());
DownloadUris.RemoveAt(uriIndex);
}
}
if (installerFilename == null || installerFile == null)
{
// The installer file is not ready.
throw new InstallerFileUnavailableException();
}
try
{
var updaterFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup and Relaunch.wsf");
var updaterFile = File.Open(updaterFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
try
{
// Prepare WSF file.
var writer = new XmlTextWriter(updaterFile, null);
writer.WriteStartDoreplacedent();
writer.WriteStartElement("package");
writer.WriteStartElement("job");
writer.WriteStartElement("reference");
writer.WriteAttributeString("object", "WScript.Shell");
writer.WriteEndElement(); // reference
writer.WriteStartElement("reference");
writer.WriteAttributeString("object", "Scripting.FileSystemObject");
writer.WriteEndElement(); // reference
writer.WriteStartElement("script");
writer.WriteAttributeString("language", "JScript");
var installerArgumentsEsc = string.IsNullOrEmpty(Arguments) ? "" : " " + HttpUtility.JavaScriptStringEncode(Arguments);
var argv = Environment.GetCommandLineArgs();
var arguments = new StringBuilder();
for (long i = 1, n = argv.LongLength; i < n; i++)
{
if (i > 1) arguments.Append(" ");
arguments.Append("\"");
arguments.Append(argv[i].Replace("\"", "\"\""));
arguments.Append("\"");
}
var script = new StringBuilder();
script.AppendLine("var wsh = WScript.CreateObject(\"WScript.Shell\");");
script.AppendLine("wsh.Run(\"\\\"" + HttpUtility.JavaScriptStringEncode(installerFilename.Replace("\"", "\"\"")) + "\\\"" + installerArgumentsEsc + "\", 0, true);");
script.AppendLine("var fso = WScript.CreateObject(\"Scripting.FileSystemObject\");");
script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(installerFilename) + "\", true); } catch (err) {}");
script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(updaterFilename) + "\", true); } catch (err) {}");
script.AppendLine("try { fso.DeleteFolder(\"" + HttpUtility.JavaScriptStringEncode(workingFolder.TrimEnd(Path.DirectorySeparatorChar)) + "\", true); } catch (err) {}");
writer.WriteCData(script.ToString());
writer.WriteEndElement(); // script
writer.WriteEndElement(); // job
writer.WriteEndElement(); // package
writer.WriteEndDoreplacedent();
writer.Flush();
// Prepare WSF launch parameters.
Trace.TraceInformation("Launching update script file {0}...", updaterFilename);
var process = new Process();
process.StartInfo.FileName = "wscript.exe";
process.StartInfo.Arguments = "\"" + updaterFilename + "\"";
process.StartInfo.WorkingDirectory = workingFolder;
// Close WSF and installer files as late as possible to narrow the attack window.
// If Windows supported executing files that are locked for writing, we could leave those files open.
updaterFile.Close();
installerFile.Close();
process.Start();
}
catch
{
// Close WSF file.
updaterFile.Close();
// Delete WSF file. If possible.
Trace.TraceInformation("Deleting file {0}...", updaterFilename);
try { File.Delete(updaterFilename); }
catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", updaterFilename, ex2.ToString()); }
throw;
}
}
catch
{
// Close installer file.
installerFile.Close();
// Delete installer file. If possible.
Trace.TraceInformation("Deleting file {0}...", installerFilename);
try { File.Delete(installerFilename); }
catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }
throw;
}
}
catch
{
// Delete working folder. If possible.
try { Directory.Delete(workingFolder); }
catch (Exception ex2) { Trace.TraceWarning("Deleting {0} folder failed: {1}", workingFolder, ex2.ToString()); }
throw;
}
};
// Self-update progress.
selfUpdate.ProgressChanged += (object sender, ProgressChangedEventArgs e) =>
{
Progress.Value = e.ProgressPercentage;
};
// Self-update complereplacedion.
selfUpdate.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
{
if (e.Error == null)
{
// Self-updating successfuly launched. Quit to release open files.
Wizard.OnQuitApplication(this);
}
else
Wizard.Error = e.Error;
// Self-dispose.
(sender as BackgroundWorker)?.Dispose();
};
selfUpdate.RunWorkerAsync();
}
19
View Source File : Response.cs
License : GNU General Public License v3.0
Project Creator : Amebis
License : GNU General Public License v3.0
Project Creator : Amebis
public static Response Get(ResourceRef res, NameValueCollection param = null, AccessToken token = null, string responseType = "application/json", Response previous = null, CancellationToken ct = default)
{
// Create request.
var request = WebRequest.Create(res.Uri);
request.CachePolicy = CachePolicy;
request.Proxy = null;
if (token != null)
token.AddToRequest(request);
if (request is HttpWebRequest httpRequest)
{
httpRequest.UserAgent = UserAgent;
httpRequest.Accept = responseType;
if (previous != null && param != null)
{
httpRequest.IfModifiedSince = previous.Timestamp;
if (previous.ETag != null)
httpRequest.Headers.Add("If-None-Match", previous.ETag);
}
}
if (param != null)
{
// Send data.
UTF8Encoding utf8 = new UTF8Encoding();
var binBody = Encoding.ASCII.GetBytes(string.Join("&", param.Cast<string>().Select(e => string.Format("{0}={1}", HttpUtility.UrlEncode(e, utf8), HttpUtility.UrlEncode(param[e], utf8)))));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = binBody.Length;
try
{
using (var requestStream = request.GetRequestStream())
requestStream.Write(binBody, 0, binBody.Length, ct);
}
catch (WebException ex) { throw new AggregateException(Resources.Strings.ErrorUploading, ex.Response is HttpWebResponse ? new WebExceptionEx(ex, ct) : ex); }
}
ct.ThrowIfCancellationRequested();
// Wait for data to start comming in.
WebResponse response;
try { response = request.GetResponse(); }
catch (WebException ex)
{
// When the content was not modified, return the previous one.
if (ex.Response is HttpWebResponse httpResponse)
{
if (httpResponse.StatusCode == HttpStatusCode.NotModified)
{
previous.IsFresh = false;
return previous;
}
throw new WebExceptionEx(ex, ct);
}
throw new AggregateException(Resources.Strings.ErrorDownloading, ex);
}
ct.ThrowIfCancellationRequested();
using (response)
{
// Read the data.
var data = new byte[0];
using (var stream = response.GetResponseStream())
{
var buffer = new byte[1048576];
for (; ; )
{
// Read data chunk.
var count = stream.Read(buffer, 0, buffer.Length, ct);
if (count == 0)
break;
// Append it to the data.
var newData = new byte[data.LongLength + count];
Array.Copy(data, newData, data.LongLength);
Array.Copy(buffer, 0, newData, data.LongLength, count);
data = newData;
}
}
if (res.PublicKeys != null)
{
// Generate signature URI.
var uriBuilderSig = new UriBuilder(res.Uri);
uriBuilderSig.Path += ".minisig";
// Create signature request.
request = WebRequest.Create(uriBuilderSig.Uri);
request.CachePolicy = CachePolicy;
request.Proxy = null;
if (token != null)
token.AddToRequest(request);
if (request is HttpWebRequest httpRequestSig)
{
httpRequestSig.UserAgent = UserAgent;
httpRequestSig.Accept = "text/plain";
}
// Read the Minisign signature.
byte[] signature = null;
try
{
using (var responseSig = request.GetResponse())
using (var streamSig = responseSig.GetResponseStream())
{
ct.ThrowIfCancellationRequested();
using (var readerSig = new StreamReader(streamSig))
{
foreach (var l in readerSig.ReadToEnd(ct).Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries))
{
if (l.Trim().StartsWith($"untrusted comment:"))
continue;
signature = Convert.FromBase64String(l);
break;
}
if (signature == null)
throw new SecurityException(string.Format(Resources.Strings.ErrorInvalidSignature, res.Uri));
}
}
}
catch (WebException ex) { throw new AggregateException(Resources.Strings.ErrorDownloadingSignature, ex.Response is HttpWebResponse ? new WebExceptionEx(ex, ct) : ex); }
ct.ThrowIfCancellationRequested();
// Verify Minisign signature.
using (var s = new MemoryStream(signature, false))
using (var r = new BinaryReader(s))
{
if (r.ReadChar() != 'E')
throw new ArgumentException(Resources.Strings.ErrorUnsupportedMinisignSignature);
byte[] payload;
switch (r.ReadChar())
{
case 'd': // PureEdDSA
payload = data;
break;
case 'D': // HashedEdDSA
payload = new eduEd25519.BLAKE2b(512).ComputeHash(data);
break;
default:
throw new ArgumentException(Resources.Strings.ErrorUnsupportedMinisignSignature);
}
ulong keyId = r.ReadUInt64();
if (!res.PublicKeys.ContainsKey(keyId))
throw new SecurityException(Resources.Strings.ErrorUntrustedMinisignPublicKey);
var sig = new byte[64];
if (r.Read(sig, 0, 64) != 64)
throw new ArgumentException(Resources.Strings.ErrorInvalidMinisignSignature);
using (eduEd25519.ED25519 key = new eduEd25519.ED25519(res.PublicKeys[keyId]))
if (!key.VerifyDetached(payload, sig))
throw new SecurityException(string.Format(Resources.Strings.ErrorInvalidSignature, res.Uri));
}
}
return
response is HttpWebResponse webResponse ?
new Response()
{
Value = Encoding.UTF8.GetString(data),
Timestamp = DateTime.TryParse(webResponse.GetResponseHeader("Last-Modified"), out var timestamp) ? timestamp : default,
ETag = webResponse.GetResponseHeader("ETag"),
IsFresh = true
} :
new Response()
{
Value = Encoding.UTF8.GetString(data),
IsFresh = true
};
}
}
19
View Source File : Response.cs
License : GNU General Public License v3.0
Project Creator : Amebis
License : GNU General Public License v3.0
Project Creator : Amebis
public static Response Get(ResourceRef res, NameValueCollection param = null, AccessToken token = null, string responseType = "application/json", Response previous = null, CancellationToken ct = default)
{
// Create request.
var request = WebRequest.Create(res.Uri);
request.CachePolicy = CachePolicy;
request.Proxy = null;
if (token != null)
token.AddToRequest(request);
if (request is HttpWebRequest httpRequest)
{
httpRequest.UserAgent = UserAgent;
httpRequest.Accept = responseType;
if (previous != null && param != null)
{
httpRequest.IfModifiedSince = previous.Timestamp;
if (previous.ETag != null)
httpRequest.Headers.Add("If-None-Match", previous.ETag);
}
}
if (param != null)
{
// Send data.
UTF8Encoding utf8 = new UTF8Encoding();
var binBody = Encoding.ASCII.GetBytes(string.Join("&", param.Cast<string>().Select(e => string.Format("{0}={1}", HttpUtility.UrlEncode(e, utf8), HttpUtility.UrlEncode(param[e], utf8)))));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = binBody.Length;
try
{
using (var requestStream = request.GetRequestStream())
requestStream.Write(binBody, 0, binBody.Length, ct);
}
catch (WebException ex) { throw new AggregateException(Resources.Strings.ErrorUploading, ex.Response is HttpWebResponse ? new WebExceptionEx(ex, ct) : ex); }
}
ct.ThrowIfCancellationRequested();
// Wait for data to start comming in.
WebResponse response;
try { response = request.GetResponse(); }
catch (WebException ex)
{
// When the content was not modified, return the previous one.
if (ex.Response is HttpWebResponse httpResponse)
{
if (httpResponse.StatusCode == HttpStatusCode.NotModified)
{
previous.IsFresh = false;
return previous;
}
throw new WebExceptionEx(ex, ct);
}
throw new AggregateException(Resources.Strings.ErrorDownloading, ex);
}
ct.ThrowIfCancellationRequested();
using (response)
{
// Read the data.
var data = new byte[0];
using (var stream = response.GetResponseStream())
{
var buffer = new byte[1048576];
for (; ; )
{
// Read data chunk.
var count = stream.Read(buffer, 0, buffer.Length, ct);
if (count == 0)
break;
// Append it to the data.
var newData = new byte[data.LongLength + count];
Array.Copy(data, newData, data.LongLength);
Array.Copy(buffer, 0, newData, data.LongLength, count);
data = newData;
}
}
if (res.PublicKeys != null)
{
// Generate signature URI.
var uriBuilderSig = new UriBuilder(res.Uri);
uriBuilderSig.Path += ".minisig";
// Create signature request.
request = WebRequest.Create(uriBuilderSig.Uri);
request.CachePolicy = CachePolicy;
request.Proxy = null;
if (token != null)
token.AddToRequest(request);
if (request is HttpWebRequest httpRequestSig)
{
httpRequestSig.UserAgent = UserAgent;
httpRequestSig.Accept = "text/plain";
}
// Read the Minisign signature.
byte[] signature = null;
try
{
using (var responseSig = request.GetResponse())
using (var streamSig = responseSig.GetResponseStream())
{
ct.ThrowIfCancellationRequested();
using (var readerSig = new StreamReader(streamSig))
{
foreach (var l in readerSig.ReadToEnd(ct).Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries))
{
if (l.Trim().StartsWith($"untrusted comment:"))
continue;
signature = Convert.FromBase64String(l);
break;
}
if (signature == null)
throw new SecurityException(string.Format(Resources.Strings.ErrorInvalidSignature, res.Uri));
}
}
}
catch (WebException ex) { throw new AggregateException(Resources.Strings.ErrorDownloadingSignature, ex.Response is HttpWebResponse ? new WebExceptionEx(ex, ct) : ex); }
ct.ThrowIfCancellationRequested();
// Verify Minisign signature.
using (var s = new MemoryStream(signature, false))
using (var r = new BinaryReader(s))
{
if (r.ReadChar() != 'E')
throw new ArgumentException(Resources.Strings.ErrorUnsupportedMinisignSignature);
byte[] payload;
switch (r.ReadChar())
{
case 'd': // PureEdDSA
payload = data;
break;
case 'D': // HashedEdDSA
payload = new eduEd25519.BLAKE2b(512).ComputeHash(data);
break;
default:
throw new ArgumentException(Resources.Strings.ErrorUnsupportedMinisignSignature);
}
ulong keyId = r.ReadUInt64();
if (!res.PublicKeys.ContainsKey(keyId))
throw new SecurityException(Resources.Strings.ErrorUntrustedMinisignPublicKey);
var sig = new byte[64];
if (r.Read(sig, 0, 64) != 64)
throw new ArgumentException(Resources.Strings.ErrorInvalidMinisignSignature);
using (eduEd25519.ED25519 key = new eduEd25519.ED25519(res.PublicKeys[keyId]))
if (!key.VerifyDetached(payload, sig))
throw new SecurityException(string.Format(Resources.Strings.ErrorInvalidSignature, res.Uri));
}
}
return
response is HttpWebResponse webResponse ?
new Response()
{
Value = Encoding.UTF8.GetString(data),
Timestamp = DateTime.TryParse(webResponse.GetResponseHeader("Last-Modified"), out var timestamp) ? timestamp : default,
ETag = webResponse.GetResponseHeader("ETag"),
IsFresh = true
} :
new Response()
{
Value = Encoding.UTF8.GetString(data),
IsFresh = true
};
}
}
19
View Source File : CheckForUpdates.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public override void OnExecute(CommandEventArgs e)
{
if (e.Argument != null)
{
ShowUpdate(e);
return;
}
int interval = 24 * 6; // 6 days
IAnkhConfigurationService config = e.GetService<IAnkhConfigurationService>();
if (config.Instance.DisableUpdateCheck)
return;
using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
{
object value = rk.GetValue("Interval");
if (value is int)
{
interval = (int)value;
if (interval <= 0)
return;
}
}
Version version = GetCurrentVersion(e.Context);
Version osVersion = Environment.OSVersion.Version;
StringBuilder sb = new StringBuilder();
sb.Append("http://svc.ankhsvn.net/svc/");
if (IsDevVersion())
sb.Append("dev/");
sb.Append("update-info/");
sb.Append(version.ToString(2));
sb.Append(".xml");
sb.Append("?av=");
sb.Append(version);
sb.Append("&vs=");
sb.Append(VSVersion.FullVersion);
sb.Append("&os=");
sb.Append(osVersion);
if (IsDevVersion())
sb.Append("&dev=1");
sb.AppendFormat(CultureInfo.InvariantCulture, "&iv={0}", interval);
int x = 0;
// Create some hashcode that is probably constant and unique for all users
// using the same IP address, but not translatable to a single user
try
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
string type = ni.NetworkInterfaceType.ToString();
if (type.Contains("Ethernet") || type.Contains("Wireless"))
x ^= ni.GetPhysicalAddress().GetHashCode();
}
}
catch { }
sb.AppendFormat(CultureInfo.InvariantCulture, "&xx={0}&pc={1}", x, Environment.ProcessorCount);
try
{
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP"))
{
if (rk != null)
{
sb.Append("&dn=");
Regex re = new Regex("^[vV]([0-9]+\\.[0-9]+)(\\.[0-9]+)*", RegexOptions.Singleline);
bool first = true;
HybridCollection<string> vers = new HybridCollection<string>();
foreach (string s in rk.GetSubKeyNames())
{
Match m = re.Match(s);
if (m.Success)
{
string v = m.Groups[1].Value;
if (vers.Contains(v))
continue;
vers.Add(v);
if (first)
first = false;
else
sb.Append(',');
sb.Append(v);
}
}
}
}
}
catch
{ }
WebRequest wr;
try
{
wr = WebRequest.Create(new Uri(sb.ToString()));
}
catch (System.Configuration.ConfigurationException)
{
// The global .Net or Visual Studio configuration probably contains an invalid (proxy) configuration
return; // Not our problem
}
HttpWebRequest hwr = wr as HttpWebRequest;
if (hwr != null)
{
hwr.AllowAutoRedirect = true;
hwr.AllowWriteStreamBuffering = true;
hwr.UserAgent = string.Format("AnkhSVN/{0} VisualStudio/{1} Windows/{2}", version, VSVersion.FullVersion, osVersion);
}
try
{
wr.BeginGetResponse(OnResponse, wr);
}
catch (NotSupportedException)
{ /* Raised when an invalid proxy server setting is set */ }
}
19
View Source File : Resourcing.cs
License : GNU General Public License v3.0
Project Creator : anderson-joyle
License : GNU General Public License v3.0
Project Creator : anderson-joyle
private string getXmlContent()
{
string content = string.Empty;
var request = HttpWebRequest.Create(Addin.AddinResources.XmlURL);
request.Method = "GET";
request.ContentLength = 0;
using (var response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(responseStream))
{
content = streamReader.ReadToEnd();
}
}
}
return content;
}
19
View Source File : RefreshCurrencyExchangeRates.cs
License : MIT License
Project Creator : AndrewButenko
License : MIT License
Project Creator : AndrewButenko
protected override void ExecuteWorkflowLogic()
{
#region Get All Currencies From Endpoint and check that call was successfull
string jsonResult = null;
var url = "http://apilayer.net/api/live?access_key=" + Context.Settings.CurrencylayerKey;
var request = (HttpWebRequest)WebRequest.Create(url);
using (var resStream = new StreamReader(request.GetResponse().GetResponseStream()))
{
jsonResult = resStream.ReadToEnd();
}
var jobject = JObject.Parse(jsonResult);
var success = jobject.SelectToken("$.success").Value<bool>();
if (!success)
{
var errorToken = jobject.SelectToken("$.error");
var errorMessage = $@"Can't obtain currency exchange rates:
Code: {errorToken.SelectToken("code").Value<int>()}
Type: {errorToken.SelectToken("type").Value<string>()}
Info: {errorToken.SelectToken("info").Value<string>()}";
throw new InvalidPluginExecutionException(errorMessage);
}
#endregion Get All Currencies From Endpoint and check that call was successfull
#region Get Base Currency
QueryExpression query = new QueryExpression("transactioncurrency")
{
ColumnSet = new ColumnSet("isocurrencycode", "currencyname")
};
query.AddLink("organization", "transactioncurrencyid", "basecurrencyid", JoinOperator.Inner);
var baseCurrency = Context.SystemService.RetrieveMultiple(query).Enreplacedies.FirstOrDefault();
if (baseCurrency == null)
return;
var baseCurrencyCode = baseCurrency.GetAttributeValue<string>("isocurrencycode").ToUpper();
var baseCurrencyId = baseCurrency.Id;
var baseCurrencyName = baseCurrency.GetAttributeValue<string>("currencyname");
var baseCurrencyNode = jobject.SelectToken($"$.quotes.USD{baseCurrencyCode}");
if (baseCurrencyNode == null)
{
throw new InvalidPluginExecutionException($"Exchange Rates for your Base Currency ({baseCurrencyName}) are not available");
}
var usdToBaseCurrencyRate = baseCurrencyNode.Value<decimal>();
#endregion Get Base Currency
#region Getting All Currencies Except Base Currency
query = new QueryExpression("transactioncurrency")
{
ColumnSet = new ColumnSet("isocurrencycode", "currencyname")
};
query.Criteria.AddCondition("transactioncurrencyid", ConditionOperator.NotEqual, baseCurrencyId);
List<Enreplacedy> allCurrencies = Context.SystemService.RetrieveMultiple(query).Enreplacedies.ToList();
#endregion Getting All Currencies Except Base Currency
#region Looping through currencies and updating Exhange Rates
foreach (Enreplacedy currency in allCurrencies)
{
var currencyCode = currency.GetAttributeValue<string>("isocurrencycode").ToUpper();
var currencyName = currency.GetAttributeValue<string>("currencyname");
var currencyNode = jobject.SelectToken($"$.quotes.USD{currencyCode}");
if (currencyNode == null)
{
Context.TracingService.Trace($"Can't refresh exchange rate for {currencyName} currency");
continue;
}
var usdToCurrencyRate = currencyNode.Value<decimal>();
decimal rate = usdToCurrencyRate / usdToBaseCurrencyRate;
currency.Attributes.Clear();
currency["exchangerate"] = rate;
Context.SystemService.Update(currency);
}
#endregion Looping through currencies and updating Exhange Rates
}
19
View Source File : UpdateMonitor.cs
License : GNU General Public License v3.0
Project Creator : Angelinsky7
License : GNU General Public License v3.0
Project Creator : Angelinsky7
private Tuple<String, Boolean> GetFileVersion() {
String r = String.Empty;
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format(UPDATE_URL, m_Rnd.Next(4000030, 504230420)));
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
using (Stream stream = response.GetResponseStream()) {
using (StreamReader reader = new StreamReader(stream)) {
r = reader.ReadToEnd();
}
}
}
} catch (Exception ex) {
r = ex.Message;
}
return new Tuple<String, Boolean>(r, true);
}
19
View Source File : ImageLoader.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
public System.Drawing.Image LoadImage(string imageURL, bool saveImage)
{
System.Drawing.Image image = null;
// Check if image is defined in the chart image collection
if (_serviceContainer != null)
{
Chart chart = (Chart)_serviceContainer.GetService(typeof(Chart));
if(chart != null)
{
foreach(NamedImage namedImage in chart.Images)
{
if(namedImage.Name == imageURL)
{
return namedImage.Image;
}
}
}
}
// Create new hashtable
if (_imageData == null)
{
_imageData = new Hashtable(StringComparer.OrdinalIgnoreCase);
}
// First check if image with this name already loaded
if (_imageData.Contains(imageURL))
{
image = (System.Drawing.Image)_imageData[imageURL];
}
// Try to load image from resource
if(image == null)
{
try
{
// Check if resource clreplaced type was specified
int columnIndex = imageURL.IndexOf("::", StringComparison.Ordinal);
if (columnIndex > 0)
{
string resourceRootName = imageURL.Substring(0, columnIndex);
string resourceName = imageURL.Substring(columnIndex + 2);
System.Resources.ResourceManager resourceManager = new System.Resources.ResourceManager(resourceRootName, replacedembly.GetExecutingreplacedembly());
image = (System.Drawing.Image)(resourceManager.GetObject(resourceName));
}
else if (replacedembly.GetEntryreplacedembly() != null)
{
// Check if resource clreplaced type was specified
columnIndex = imageURL.IndexOf(':');
if (columnIndex > 0)
{
string resourceRootName = imageURL.Substring(0, columnIndex);
string resourceName = imageURL.Substring(columnIndex + 1);
System.Resources.ResourceManager resourceManager = new System.Resources.ResourceManager(resourceRootName, replacedembly.GetEntryreplacedembly());
image = (Image)(resourceManager.GetObject(resourceName));
}
else
{
// Try to load resource from every type defined in entry replacedembly
replacedembly entryreplacedembly = replacedembly.GetEntryreplacedembly();
if (entryreplacedembly != null)
{
foreach (Type type in entryreplacedembly.GetTypes())
{
System.Resources.ResourceManager resourceManager = new System.Resources.ResourceManager(type);
try
{
image = (Image)(resourceManager.GetObject(imageURL));
}
catch (ArgumentNullException)
{
}
catch (MissingManifestResourceException)
{
}
// Check if image was loaded
if (image != null)
{
break;
}
}
}
}
}
}
catch (MissingManifestResourceException)
{
}
}
// Try to load image using the Web Request
if(image == null)
{
Uri imageUri = null;
try
{
// Try to create URI directly from image URL (will work in case of absolute URL)
imageUri = new Uri(imageURL);
}
catch(UriFormatException)
{}
// Load image from file or web resource
if(imageUri != null)
{
try
{
WebRequest request = WebRequest.Create(imageUri);
image = System.Drawing.Image.FromStream(request.GetResponse().GetResponseStream());
}
catch (ArgumentException)
{
}
catch (NotSupportedException)
{
}
catch (SecurityException)
{
}
}
}
// absolute uri(without Server.MapPath)in web is not allowed. Loading from replative uri Server[Page].MapPath is done above.
// Try to load as file
if(image == null)
{
image = LoadFromFile(imageURL);
}
// Error loading image
if(image == null)
{
throw(new ArgumentException( SR.ExceptionImageLoaderIncorrectImageLocation( imageURL ) ) );
}
// Save new image in cache
if(saveImage)
{
_imageData[imageURL] = image;
}
return image;
}
19
View Source File : XmlConfigurator.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
private static void InternalConfigure(ILoggerRepository repository, Uri configUri)
{
LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using URI ["+configUri+"]");
if (configUri == null)
{
LogLog.Error(declaringType, "Configure called with null 'configUri' parameter");
}
else
{
if (configUri.IsFile)
{
// If URI is local file then call Configure with FileInfo
InternalConfigure(repository, new FileInfo(configUri.LocalPath));
}
else
{
// NETCF dose not support WebClient
WebRequest configRequest = null;
try
{
configRequest = WebRequest.Create(configUri);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to create WebRequest for URI ["+configUri+"]", ex);
}
if (configRequest != null)
{
#if !NETCF_1_0
// authentication may be required, set client to use default credentials
try
{
configRequest.Credentials = CredentialCache.DefaultCredentials;
}
catch
{
// ignore security exception
}
#endif
try
{
#if NETSTANDARD
using WebResponse response = configRequest.GetResponseAsync().GetAwaiter().GetResult();
#else
using WebResponse response = configRequest.GetResponse();
#endif
if (response != null)
{
using var configStream = response.GetResponseStream();
InternalConfigure(repository, configStream);
}
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Failed to request config from URI ["+configUri+"]", ex);
}
}
}
}
}
19
View Source File : EventSource.cs
License : MIT License
Project Creator : AshV
License : MIT License
Project Creator : AshV
private void ConnectAsync()
{
Trace.TraceInformation("ConnectAsync ({0})", Url);
ReadyState = EventSourceState.Connecting;
_httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);
ConfigureWebRequest(_httpWebRequest);
try
{
var handle = _httpWebRequest.BeginGetResponse(EndGetResponse, null);
ThreadPool.RegisterWaitForSingleObject(
handle.AsyncWaitHandle,
(state, timedOut) =>
{
if (!timedOut || _httpWebRequest == null || _shutdownToken) return;
Trace.TraceInformation("ConnectAsync (Timed Out)", Url);
OnErrorEvent(new ServerSentErrorEventArgs { Exception = new TimeoutException() });
CloseConnection();
RetryAfterDelay();
},
_httpWebRequest,
Timeout,
true);
}
catch (WebException ex)
{
OnErrorEvent(new ServerSentErrorEventArgs { Exception = ex });
CloseConnection();
RetryAfterDelay();
}
}
19
View Source File : AwsMeta.cs
License : Apache License 2.0
Project Creator : asynkron
License : Apache License 2.0
Project Creator : asynkron
private string GetResponseString(Uri requestUri)
{
try
{
var request = WebRequest.Create(requestUri);
using var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
_logger.LogError("Failed to execute HTTP request. Request URI: {RequestUri}, Status code: {StatusCode}", requestUri, response.StatusCode);
return default;
}
using var stream = response.GetResponseStream();
using var reader = new StreamReader(stream!);
return reader.ReadToEnd();
}
catch (WebException ex) when (ex.Status == WebExceptionStatus.UnknownError)
{
_logger.LogError(ex, "Network is unreachable");
// Network is unreachable
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get AWS metadata response");
}
return default;
}
19
View Source File : ApiWrapper.cs
License : MIT License
Project Creator : Avanade
License : MIT License
Project Creator : Avanade
public override T Get<T>(string serviceRoute, [Optional] Dictionary<string, string> header)
{
serviceRoute = serviceRoute.Replace(Environment.NewLine, string.Empty).Replace("\"", "'");
///Calls the service following the route
HttpWebRequest request = null;
dynamic response = null;
///Building the Request
request = (HttpWebRequest)WebRequest.Create(MakeUri(serviceRoute));
request.Method = "GET";
request.ContentType = "application/json; encoding='utf-8'";
///Sends the authentication token if exisists,
if (!String.IsNullOrEmpty(_token))
request.Headers.Add("Authorization", _token);
if (header != null)
foreach (var item in header)
{
request.Headers.Add(item.Key, item.Value);
}
///Gets the Response from API
response = (HttpWebResponse)request.GetResponse();
if (typeof(T) == typeof(HttpWebResponse))
{
return response;
}
else
{
///Converts te Response in text to return
string responseText;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
responseText = reader.ReadToEnd();
}
///Now load the JSON Doreplacedent
return JToken.Parse(responseText).ToObject<T>();
}
}
19
View Source File : ApiWrapper.cs
License : MIT License
Project Creator : Avanade
License : MIT License
Project Creator : Avanade
public override DomainResponse Delete(string serviceRoute, [Optional]Dictionary<string, string> headers)
{
serviceRoute = serviceRoute.Replace(Environment.NewLine, string.Empty)
.Replace("\"", "'");
///Calls the service following the route
HttpWebRequest request = null;
HttpWebResponse response = null;
request = (HttpWebRequest)WebRequest.Create(MakeUri(serviceRoute));
request.Method = "DELETE";
request.ContentType = "application/json";
///Send the authentication token if exisists
if (!String.IsNullOrEmpty(_token))
request.Headers.Add("Authorization", _token);
///Get the Response
response = (HttpWebResponse)request.GetResponse();
string responseText;
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
responseText = reader.ReadToEnd();
}
///return new DomainResponse(true, responseText);
return new DomainResponse()
{
PayLoad = responseText
};
}
19
View Source File : ApiWrapper.cs
License : MIT License
Project Creator : Avanade
License : MIT License
Project Creator : Avanade
public override JToken Get(string serviceRoute, [Optional] Dictionary<string, string> header)
{
serviceRoute = serviceRoute.Replace(Environment.NewLine, string.Empty).Replace("\"", "'");
///Calls the service following the route
HttpWebRequest request = null;
HttpWebResponse response = null;
request = (HttpWebRequest)WebRequest.Create(MakeUri(serviceRoute));
request.Method = "GET";
request.ContentType = "application/json; encoding='utf-8'";
///Sends the authorization token if exisists
if (!String.IsNullOrEmpty(_token))
request.Headers.Add("Authorization", _token);
if (header != null)
foreach (var item in header)
{
request.Headers.Add(item.Key, item.Value);
}
///Get the Response from the API
response = (HttpWebResponse)request.GetResponse();
///Converts te Response in text to return
string responseText;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
responseText = reader.ReadToEnd();
}
///Now load the JSON Doreplacedent
return JToken.Parse(responseText);
}
19
View Source File : ApiWrapper.cs
License : MIT License
Project Creator : Avanade
License : MIT License
Project Creator : Avanade
public override T Delete<T>(string serviceRoute, [Optional]Dictionary<string, string> headers)
{
serviceRoute = serviceRoute.Replace(Environment.NewLine, string.Empty).Replace("\"", "'");
//Calls the service following the route
HttpWebRequest request = null;
dynamic response = null;
request = (HttpWebRequest)WebRequest.Create(MakeUri(serviceRoute));
request.Method = "DELETE";
request.ContentType = "application/json";
///Send the authentication token if exisists
if (!String.IsNullOrEmpty(_token))
request.Headers.Add("Authorization", _token);
if (headers != null)
foreach (var item in headers)
{
request.Headers.Add(item.Key, item.Value);
}
///Get the Response
response = (HttpWebResponse)request.GetResponse();
if (typeof(T) == typeof(HttpWebResponse))
{
return response;
}
else
{
string responseText;
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
responseText = reader.ReadToEnd();
}
///return new DomainResponse;
return JToken.Parse(responseText).ToObject<T>();
}
}
19
View Source File : HttpHelpers.cs
License : Apache License 2.0
Project Creator : aws-samples
License : Apache License 2.0
Project Creator : aws-samples
public static HttpWebRequest ConstructWebRequest(Uri endpointUri,
string httpMethod,
IDictionary<string, string> headers)
{
var request = (HttpWebRequest)WebRequest.Create(endpointUri);
request.Method = httpMethod;
foreach (var header in headers.Keys)
{
// not all headers can be set via the dictionary
if (header.Equals("host", StringComparison.OrdinalIgnoreCase))
request.Host = headers[header];
else if (header.Equals("content-length", StringComparison.OrdinalIgnoreCase))
request.ContentLength = long.Parse(headers[header]);
else if (header.Equals("content-type", StringComparison.OrdinalIgnoreCase))
request.ContentType = headers[header];
else
request.Headers.Add(header, headers[header]);
}
return request;
}
19
View Source File : GoogleOAuth2Provider.cs
License : Apache License 2.0
Project Creator : azanov
License : Apache License 2.0
Project Creator : azanov
public static GoogleAccessToken GetAccessToken(string code)
{
string postData = string.Format("client_id={0}&client_secret={1}&grant_type=authorization_code&code={2}&redirect_uri={3}", CLIENT_ID, CLIENT_SECRET, code, REDIRECT_URI);
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(GET_ACCESS_TOKEN_URI); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
byte[] postBytes = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using(var responseReader = new StreamReader(response.GetResponseStream()))
{
var tmp = responseReader.ReadToEnd();
return JsonHelper.From<GoogleAccessToken>(tmp);
}
}
19
View Source File : OutlookOAuth2Provider.cs
License : Apache License 2.0
Project Creator : azanov
License : Apache License 2.0
Project Creator : azanov
public static OutlookAccessToken GetAccessToken(string code)
{
string postData = string.Format("client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code", CLIENT_ID, REDIRECT_URI, CLIENT_SECRET, code);
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(GET_ACCESS_TOKEN_URI); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
byte[] postBytes = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var responseReader = new StreamReader(response.GetResponseStream()))
{
var tmp = responseReader.ReadToEnd();
return JsonHelper.From<OutlookAccessToken>(tmp);
}
}
19
View Source File : YahooOAuth2Provider.cs
License : Apache License 2.0
Project Creator : azanov
License : Apache License 2.0
Project Creator : azanov
public static YahooAccessToken GetAccessToken(string code)
{
string postData = string.Format("client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code", CLIENT_ID, REDIRECT_URI, CLIENT_SECRET, code);
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(GET_ACCESS_TOKEN_URI); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(CLIENT_ID + ":" + CLIENT_SECRET)));
byte[] postBytes = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var responseReader = new StreamReader(response.GetResponseStream()))
{
var tmp = responseReader.ReadToEnd();
return JsonHelper.From<YahooAccessToken>(tmp);
}
}
19
View Source File : WebDAV.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
private static HttpWebRequest makeRequest(Uri uri, string uName, string uPwd, int timeout = 0, string method = "GET")
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = method;
var t = timeout > 0 ? timeout : DEFAULT_TIMEOUT_MS;
if (t > 0) request.Timeout = t;
NetworkCredential credentials = new NetworkCredential(uName, uPwd);
request.Credentials = credentials;
request.PreAuthenticate = true;
request.Pipelined = false;
return request;
}
See More Examples