Here are the examples of the csharp api System.Net.WebRequest.Create(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1446 Examples
19
View Source File : GoPhishIntegration.cs
License : GNU General Public License v3.0
Project Creator : 0dteam
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
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
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
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
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
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 : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio
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
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
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
License : MIT License
Project Creator : 944095635
private void SetCer(HttpItem item)
{
if (!string.IsNullOrWhiteSpace(item.CerPath))
{
//这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
//初始化对像,并设置请求的URL地址
request = (HttpWebRequest)WebRequest.Create(item.URL);
SetCerList(item);
//将证书添加到请求里
request.ClientCertificates.Add(new X509Certificate(item.CerPath));
}
else
{
//初始化对像,并设置请求的URL地址
request = (HttpWebRequest)WebRequest.Create(item.URL);
SetCerList(item);
}
}
19
View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov
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
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport
private static HttpWebRequest BuildRequest(string queryString) {
HttpWebRequest Request;
Request = (HttpWebRequest)WebRequest.Create(queryString);
try {
Request.Timeout = int.Parse(AppSettings.RequestTimeoutInMilliseconds, CultureInfo.CurrentCulture);
}
catch {
Request.Timeout = 100000;
}
Request.ContentType = "text/xml; charset=utf-8";
Request.Proxy = GetWebProxy();
Request.Method = "GET";
return (Request);
}
19
View Source File : ViaCepWebservice.cs
License : MIT License
Project Creator : ACBrNet
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 : ConsultaSintegraBase.cs
License : MIT License
Project Creator : ACBrNet
License : MIT License
Project Creator : ACBrNet
protected HttpWebRequest GetClient(string url)
{
var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.CookieContainer = cookies;
webRequest.ProtocolVersion = HttpVersion.Version11;
webRequest.UserAgent = "Mozilla/4.0 (compatible; Synapse)";
webRequest.KeepAlive = true;
webRequest.Headers.Add(HttpRequestHeader.KeepAlive, "300");
return webRequest;
}
19
View Source File : CorreiosWebservice.cs
License : MIT License
Project Creator : ACBrNet
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 : ACBrComponentConsulta.cs
License : MIT License
Project Creator : ACBrNet
License : MIT License
Project Creator : ACBrNet
protected virtual HttpWebRequest GetClient(string url)
{
var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.CookieContainer = cookies;
webRequest.ProtocolVersion = HttpVersion.Version11;
webRequest.UserAgent = "Mozilla/4.0 (compatible; Synapse)";
webRequest.KeepAlive = true;
webRequest.Headers.Add(HttpRequestHeader.KeepAlive, "300");
return webRequest;
}
19
View Source File : Program_DbUpdates.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
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
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 : APIConsumerHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
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
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
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
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
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
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 : RemotePost.cs
License : MIT License
Project Creator : Adoxio
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 : deviceidmanager.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static DeviceRegistrationResponse ExecuteRegistrationRequest(string url, DeviceRegistrationRequest registrationRequest)
{
//Create the request that will submit the request to the server
WebRequest request = WebRequest.Create(url);
request.ContentType = "application/soap+xml; charset=UTF-8";
request.Method = "POST";
request.Timeout = 180000;
//Write the envelope to the RequestStream
using (Stream stream = request.GetRequestStream())
{
Serialize(stream, registrationRequest);
}
// Read the response into an XmlDoreplacedent and return that doc
try
{
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
return Deserialize<DeviceRegistrationResponse>(stream);
}
}
}
catch (WebException ex)
{
if (null != ex.Response)
{
using (Stream stream = ex.Response.GetResponseStream())
{
return Deserialize<DeviceRegistrationResponse>(stream);
}
}
throw;
}
}
19
View Source File : HttpURLConnectionClient.cs
License : MIT License
Project Creator : Adyen
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 : HttpURLConnectionClient.cs
License : MIT License
Project Creator : Adyen
License : MIT License
Project Creator : Adyen
public HttpWebRequest GetHttpWebRequest(string endpoint, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null)
{
//Add default headers
var httpWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Accept-Charset", "UTF-8");
httpWebRequest.Headers.Add("Cache-Control", "no-cache");
httpWebRequest.UserAgent = $"{config.ApplicationName} {ClientConfig.UserAgentSuffix}{ClientConfig.LibVersion}";
if (!string.IsNullOrWhiteSpace(requestOptions?.IdempotencyKey))
{
httpWebRequest.Headers.Add("Idempotency-Key", requestOptions?.IdempotencyKey);
}
//Use one of two authentication method.
if (isApiKeyRequired || !string.IsNullOrEmpty(config.XApiKey))
{
httpWebRequest.Headers.Add("x-api-key", config.XApiKey);
}
else if (!string.IsNullOrEmpty(config.Preplacedword))
{
var authString = config.Username + ":" + config.Preplacedword;
var bytes = Encoding.UTF8.GetBytes(authString);
var credentials = Convert.ToBase64String(bytes);
httpWebRequest.Headers.Add("Authorization", "Basic " + credentials);
httpWebRequest.UseDefaultCredentials = true;
}
if (config.Proxy != null)
{
httpWebRequest.Proxy = config.Proxy;
}
httpWebRequest.ServerCertificateValidationCallback = ServerCertificateValidationCallback;
return httpWebRequest;
}
19
View Source File : HttpApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public void CreateRequest()
{
var url = new StringBuilder();
url.Append($"{Host?.TrimEnd('/') + "/"}{ApiName?.TrimStart('/')}");
if (Query != null && Query.Count > 0)
{
bool first = true;
foreach (var kvp in Query)
{
if (string.IsNullOrEmpty(kvp.Key) || kvp.Value == null)
continue;
if (first)
{
first = false;
url.Append('?');
}
else
url.Append('&');
url.Append($"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value, Encoding.UTF8)}");
}
}
RemoteUrl = url.ToString();
RemoteRequest = (HttpWebRequest)WebRequest.Create(RemoteUrl);
RemoteRequest.Headers.Add(HttpRequestHeader.Authorization, Authorization);
RemoteRequest.Timeout = ConfigurationManager.AppSettings.GetInt("httpTimeout", 30);
RemoteRequest.Method = Method;
RemoteRequest.KeepAlive = true;
if (Form != null && Form.Count > 0)
{
RemoteRequest.ContentType = "application/x-www-form-urlencoded";
var builder = new StringBuilder();
bool first = true;
foreach (var kvp in Form)
{
if (string.IsNullOrEmpty(kvp.Key) || kvp.Value == null)
continue;
if (first)
first = false;
else
url.Append('&');
builder.Append($"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value, Encoding.UTF8)}");
}
using (var rs = RemoteRequest.GetRequestStream())
{
var formData = Encoding.UTF8.GetBytes(builder.ToString());
rs.Write(formData, 0, formData.Length);
}
}
else if (!string.IsNullOrWhiteSpace(Json))
{
RemoteRequest.ContentType = "application/json;charset=utf-8";
var buffer = Json.ToUtf8Bytes();
using (var rs = RemoteRequest.GetRequestStream())
{
rs.Write(buffer, 0, buffer.Length);
}
}
else
{
RemoteRequest.ContentType = "application/x-www-form-urlencoded";
}
}
19
View Source File : WebApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public ApiResult<TResult> Get<TResult>(string apiName, string arguments)
{
LogRecorderX.BeginStepMonitor("内部API调用" + ToUrl(apiName));
var ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";
LogRecorderX.MonitorTrace(ctx);
LogRecorderX.MonitorTrace("Arguments:" + arguments);
if (!string.IsNullOrWhiteSpace(arguments))
{
apiName = $"{apiName}?{arguments}";
}
var req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));
req.Method = "GET";
req.ContentType = "application/x-www-form-urlencoded";
req.Headers.Add(HttpRequestHeader.Authorization, ctx);
return GetResult<TResult>(req);
}
19
View Source File : WebApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public ApiResult<TResult> Post<TResult>(string apiName, string form)
{
LogRecorderX.BeginStepMonitor("内部API调用" + ToUrl(apiName));
var ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";
LogRecorderX.MonitorTrace(ctx);
LogRecorderX.MonitorTrace("Arguments:" + form);
var req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.Headers.Add(HttpRequestHeader.Authorization, ctx);
try
{
using (var rs = req.GetRequestStream())
{
var formData = Encoding.UTF8.GetBytes(form);
rs.Write(formData, 0, formData.Length);
}
}
catch (Exception ex)
{
LogRecorderX.Exception(ex);
LogRecorderX.EndStepMonitor();
return ApiResult.Error<TResult>(ErrorCode.RemoteError);
}
return GetResult<TResult>(req);
}
19
View Source File : WebApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public ApiValueResult Post(string apiName, string form)
{
LogRecorderX.BeginStepMonitor("内部API调用" + ToUrl(apiName));
var ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";
LogRecorderX.MonitorTrace(ctx);
LogRecorderX.MonitorTrace("Arguments:" + form);
var req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.Headers.Add(HttpRequestHeader.Authorization, ctx);
try
{
using (var rs = req.GetRequestStream())
{
var formData = Encoding.UTF8.GetBytes(form);
rs.Write(formData, 0, formData.Length);
}
}
catch (Exception ex)
{
LogRecorderX.Exception(ex);
LogRecorderX.EndStepMonitor();
return ErrorResult(-3);
}
using (MonitorScope.CreateScope("Caller Remote"))
{
return GetResult(req);
}
}
19
View Source File : WebApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public ApiValueResult Get(string apiName, string arguments)
{
LogRecorderX.BeginStepMonitor("内部API调用" + ToUrl(apiName));
var ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";
LogRecorderX.MonitorTrace(ctx);
LogRecorderX.MonitorTrace("Arguments:" + arguments);
if (!string.IsNullOrWhiteSpace(arguments))
{
apiName = $"{apiName}?{arguments}";
}
var req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));
req.Method = "GET";
req.ContentType = "application/x-www-form-urlencoded";
req.Headers.Add(HttpRequestHeader.Authorization, ctx);
using (MonitorScope.CreateScope("Caller Remote"))
{
return GetResult(req);
}
}
19
View Source File : HttpApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public void CreateRequest(string apiName, string method = "GET", string context = null)
{
ApiName = apiName;
var auth = Bearer;
_url = $"{Host?.TrimEnd('/') + "/"}{apiName?.TrimStart('/')}";
_webRequest = (HttpWebRequest)WebRequest.Create(_url);
_webRequest.Timeout = 30000;
_webRequest.KeepAlive = false;
_webRequest.Method = method;
if (!string.IsNullOrEmpty(context))
{
_webRequest.ContentType = "application/json";
_webRequest.Headers.Add(HttpRequestHeader.Authorization, auth);
using (var rs = _webRequest.GetRequestStream())
{
var formData = Encoding.UTF8.GetBytes(context);
rs.Write(formData, 0, formData.Length);
}
}
}
19
View Source File : HttpApiCaller.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public void CreateRequest(string apiName, string method, HttpRequest localRequest, RouteData data)
{
ApiName = apiName;
var url = new StringBuilder();
url.Append($"{Host?.TrimEnd('/') + "/"}{apiName?.TrimStart('/')}");
if (localRequest.QueryString.HasValue)
{
url.Append('?');
url.Append(data.Uri.Query);
}
RemoteUrl = url.ToString();
RemoteRequest = (HttpWebRequest) WebRequest.Create(RemoteUrl);
RemoteRequest.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {data.Token}");
RemoteRequest.Timeout = RouteOption.Option.SystemConfig.HttpTimeOut;
RemoteRequest.Method = method;
RemoteRequest.KeepAlive = true;
if (localRequest.HasFormContentType)
{
RemoteRequest.ContentType = "application/x-www-form-urlencoded";
var builder = new StringBuilder();
builder.Append($"_api_context_={HttpUtility.UrlEncode(JsonConvert.SerializeObject(GlobalContext.Current), Encoding.UTF8)}");
foreach (var kvp in localRequest.Form)
{
builder.Append('&');
builder.Append($"{kvp.Key}=");
if (!string.IsNullOrEmpty(kvp.Value))
builder.Append($"{HttpUtility.UrlEncode(kvp.Value, Encoding.UTF8)}");
}
data.Form = builder.ToString();
using (var rs = RemoteRequest.GetRequestStream())
{
var formData = Encoding.UTF8.GetBytes(data.Form);
rs.Write(formData, 0, formData.Length);
}
}
else if (localRequest.ContentLength != null)
{
using (var texter = new StreamReader(localRequest.Body))
{
data.Context = texter.ReadToEnd();
texter.Close();
}
if (string.IsNullOrWhiteSpace(data.Context))
return;
RemoteRequest.ContentType = "application/json;charset=utf-8";
var buffer = data.Context.ToUtf8Bytes();
using (var rs = RemoteRequest.GetRequestStream())
{
rs.Write(buffer, 0, buffer.Length);
}
}
else
{
RemoteRequest.ContentType = localRequest.ContentType;
}
}
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 UpdateCheck()
{
#if !DEBUG
try
{
#endif
if (!requestSent)
{
request = (HttpWebRequest)WebRequest.Create(c_checkURL);
request.BeginGetResponse(new AsyncCallback(UpdateResponse), null);
requestSent = true;
}
else
{
if (updateNotify && updateAvailable)
{
lblUpdateAvail.Visible = true;
}
else
{
lblUpdateAvail.Visible = false;
}
}
#if !DEBUG
}
catch { }
#endif
}
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
void ReadSettings()
{
currentlyReading = true;
StreamReader sr = null;
string checkVer = c_toolVer;
try
{
using (sr = new StreamReader(settingsFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
try
{
int equalsign = line.IndexOf('=');
if (equalsign > 0)
{
string varName = line.Substring(0, equalsign);
string varValue = line.Substring(equalsign + 1);
if (varName == "ToolVersion" || varName == "GameVersion")
{
checkVer = varValue;
}
else if (varName == "GameMode")
{
rbSingleplayer.Checked = (varValue == "sp");
}
else if (varName == "Beep")
{
chkBeep.Checked = bool.Parse(varValue);
}
else if (varName == "FoV")
{
SetFoV(float.Parse(varValue));
}
else if (varName == "FoVOffset" || varName == "RelativeFoVOffset")
{
int tmp = int.Parse(varValue, NumberStyles.AllowHexSpecifier);
if (tmp > (int)gameMode.GetValue("c_baseAddr") && tmp < 0x40000000)
pFoV = (varName == "RelativeFoVOffset" ? (int)gameMode.GetValue("c_baseAddr") : 0) + tmp;
}
else if (varName == "UpdatePopup" || varName == "UpdateCheck")
{
chkUpdate.Checked = bool.Parse(varValue);
}
else if (varName == "DisableHotkeys")
{
chkHotkeys.Checked = bool.Parse(varValue);
}
else if (varName == "HotkeyIncrease")
{
catchKeys[0] = (Keys)int.Parse(varValue);
btnKeyZoomOut.Text = VirtualKeyName(catchKeys[0]);
}
else if (varName == "HotkeyDecrease")
{
catchKeys[1] = (Keys)int.Parse(varValue);
btnKeyZoomIn.Text = VirtualKeyName(catchKeys[1]);
}
else if (varName == "HotkeyReset")
{
catchKeys[2] = (Keys)int.Parse(varValue);
btnKeyReset.Text = VirtualKeyName(catchKeys[2]);
}
}
}
catch { }
}
}
}
finally
{
if (sr != null)
sr.Close();
}
if (checkVer != c_toolVer)
pFoV = (int)gameMode.GetValue("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 : mainForm.cs
License : MIT License
Project Creator : ajohns6
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 : mainForm.cs
License : MIT License
Project Creator : ajohns6
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 : updateForm.cs
License : MIT License
Project Creator : ajohns6
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 : MainProgram.cs
License : MIT License
Project Creator : AlbertMN
License : MIT License
Project Creator : AlbertMN
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[STAThread]
static void Main(string[] args) {
Console.WriteLine("Log location; " + logFilePath);
CheckSettings();
var config = new NLog.Config.LoggingConfiguration();
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = logFilePath };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
NLog.LogManager.Configuration = config;
void ActualMain() {
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
//Upgrade settings
if (Properties.Settings.Default.UpdateSettings) {
/* Copy old setting-files in case the Evidence type and Evidence Hash has changed (which it does sometimes) - easier than creating a whole new settings system */
try {
Configuration accConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
string currentFolder = new DirectoryInfo(accConfiguration.FilePath).Parent.Parent.FullName;
string[] directories = Directory.GetDirectories(new DirectoryInfo(currentFolder).Parent.FullName);
foreach (string dir in directories) {
if (dir != currentFolder.ToString()) {
var directoriesInDir = Directory.GetDirectories(dir);
foreach (string childDir in directoriesInDir) {
string checkPath = Path.Combine(currentFolder, Path.GetFileName(childDir));
if (!Directory.Exists(checkPath)) {
string checkFile = Path.Combine(childDir, "user.config");
if (File.Exists(checkFile)) {
bool xmlHasError = false;
try {
XmlDoreplacedent xml = new XmlDoreplacedent();
xml.Load(checkFile);
xml.Validate(null);
} catch {
xmlHasError = true;
DoDebug("XML doreplacedent validation failed (is invalid): " + checkFile);
}
if (!xmlHasError) {
Directory.CreateDirectory(checkPath);
File.Copy(checkFile, Path.Combine(checkPath, "user.config"), true);
}
}
}
}
}
}
} catch (Exception e) {
Console.WriteLine("Error getting settings from older versions of ACC; " + e.Message);
}
/* End "copy settings" */
try {
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.UpdateSettings = false;
Properties.Settings.Default.Save();
} catch {
DoDebug("Failed to upgrade from old settings file.");
}
Console.WriteLine("Upgraded settings to match last version");
}
if (Properties.Settings.Default.LastUpdated == DateTime.MinValue) {
Properties.Settings.Default.LastUpdated = DateTime.Now;
}
//Create action mod path
if (!Directory.Exists(actionModsPath)) {
Directory.CreateDirectory(actionModsPath);
}
//Translator
string tempDir = Path.Combine(currentLocation, "Translations");
if (Directory.Exists(tempDir)) {
Translator.translationFolder = Path.Combine(currentLocation, "Translations");
Translator.languagesArray = Translator.GetLanguages();
} else {
MessageBox.Show("Missing the translations folder. Reinstall the software to fix this issue.", messageBoxreplacedle);
}
string lang = Properties.Settings.Default.ActiveLanguage;
if (Array.Exists(Translator.languagesArray, element => element == lang)) {
DoDebug("ACC running with language \"" + lang + "\"");
Translator.SetLanguage(lang);
} else {
DoDebug("Invalid language chosen (" + lang + ")");
Properties.Settings.Default.ActiveLanguage = "English";
Translator.SetLanguage("English");
}
//End translator
sysIcon = new SysTrayIcon();
Properties.Settings.Default.TimesOpened += 1;
Properties.Settings.Default.Save();
SetupDataFolder();
if (File.Exists(logFilePath)) {
try {
File.WriteAllText(logFilePath, string.Empty);
} catch {
// Don't let this being DENIED crash the software
Console.WriteLine("Failed to empty the log");
}
} else {
Console.WriteLine("Trying to create log");
CreateLogFile();
}
//Check if software already runs, if so kill this instance
var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));
if (otherACCs.Length > 1) {
//Try kill the _other_ process instead
foreach (Process p in otherACCs) {
if (p.Id != Process.GetCurrentProcess().Id) {
try {
p.Kill();
DoDebug("Other ACC instance was running. Killed it.");
} catch {
DoDebug("Could not kill other process of ACC; access denied");
}
}
}
}
Application.EnableVisualStyles();
DoDebug("[ACC begun (v" + softwareVersion + ")]");
if (Properties.Settings.Default.CheckForUpdates) {
if (HasInternet()) {
new Thread(() => {
new SoftwareUpdater().Check();
}).Start();
} else {
DoDebug("Couldn't check for new update as PC does not have access to the internet");
}
}
//On console close: hide NotifyIcon
Application.ApplicationExit += new EventHandler(OnApplicationExit);
handler = new ConsoleEventDelegate(ConsoleEventCallback);
SetConsoleCtrlHandler(handler, true);
//Create shortcut folder if doesn't exist
if (!Directory.Exists(shortcutLocation)) {
Directory.CreateDirectory(shortcutLocation);
}
if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt"))) {
//Create example-file
try {
using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
sw.WriteLine("This is an example file.");
sw.WriteLine("If you haven't already, make your replacedistant open this file!");
}
} catch {
DoDebug("Could not create or write to example file");
}
}
//Delete all old action files
if (Directory.Exists(CheckPath())) {
DoDebug("Deleting all files in action folder");
foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension)) {
int timeout = 0;
if (File.Exists(file)) {
while (ActionChecker.FileInUse(file) && timeout < 5) {
timeout++;
Thread.Sleep(500);
}
if (timeout >= 5) {
DoDebug("Failed to delete file at " + file + " as file appears to be in use (and has been for 2.5 seconds)");
} else {
try {
File.Delete(file);
} catch (Exception e) {
DoDebug("Failed to delete file at " + file + "; " + e.Message);
}
}
}
}
DoDebug("Old action files removed - moving on...");
}
//SetupListener();
watcher = new FileSystemWatcher() {
Path = CheckPath(),
NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName,
Filter = "*." + Properties.Settings.Default.ActionFileExtension,
EnableRaisingEvents = true
};
watcher.Changed += new FileSystemEventHandler(new ActionChecker().FileFound);
watcher.Created += new FileSystemEventHandler(new ActionChecker().FileFound);
watcher.Renamed += new RenamedEventHandler(new ActionChecker().FileFound);
watcher.Deleted += new FileSystemEventHandler(new ActionChecker().FileFound);
watcher.Error += delegate { DoDebug("Something wen't wrong"); };
DoDebug("\n[" + messageBoxreplacedle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");
sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon_light;
RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
if (Registry.GetValue(key.Name + @"\replacedistantComputerControl", "FirstTime", null) == null) {
SetStartup(true);
key.CreateSubKey("replacedistantComputerControl");
key = key.OpenSubKey("replacedistantComputerControl", true);
key.SetValue("FirstTime", false);
ShowGettingStarted();
DoDebug("Starting setup guide (first time opening ACC - wuhu!)");
} else {
if (!Properties.Settings.Default.HasCompletedTutorial) {
ShowGettingStarted();
DoDebug("Didn't finish setup guide last time, opening again");
}
}
SetRegKey("ActionFolder", CheckPath());
SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);
testActionWindow = new TestActionWindow();
//If newly updated
if (Properties.Settings.Default.LastKnownVersion != softwareVersion) {
//Up(or down)-grade, display version notes
DoDebug("ACC has been updated");
if (Properties.Settings.Default.LastKnownVersion != "" && new System.Version(Properties.Settings.Default.LastKnownVersion) < new System.Version("1.4.3")) {
//Had issues before; fixed now
DoDebug("Upgraded to 1.4.3, fixed startup - now starting with Windows");
try {
RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rk.DeleteValue(appName, false);
} catch {
DoDebug("Failed to remove old start with win run");
}
SetStartup(true);
} else {
if (ACCStartsWithWindows()) {
SetStartup(true);
}
}
Properties.Settings.Default.LastUpdated = DateTime.Now;
if (gettingStarted != null) {
DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing");
aboutVersionAwaiting = true;
} else {
Properties.Settings.Default.LastKnownVersion = softwareVersion;
new NewVersion().Show();
}
Properties.Settings.Default.Save();
}
//Check if software starts with Windows
if (!ACCStartsWithWindows())
sysIcon.AddOpenOnStartupMenu();
/* 'Evalufied' user feedback implementation */
if ((DateTime.Now - Properties.Settings.Default.LastUpdated).TotalDays >= 7 && Properties.Settings.Default.TimesOpened >= 7
&& gettingStarted == null
&& !Properties.Settings.Default.HasPromptedFeedback) {
//User has had the software/update for at least 7 days, and has opened the software more than 7 times - time to ask for feedback
//(also the "getting started" window is not showing)
if (HasInternet()) {
try {
WebRequest request = WebRequest.Create("https://evalufied.dk/");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response == null || response.StatusCode != HttpStatusCode.OK) {
DoDebug("'Evalufied' is down - won't show faulty feedback window");
} else {
DoDebug("Showing 'User Feedback' window");
Properties.Settings.Default.HasPromptedFeedback = true;
Properties.Settings.Default.Save();
new UserFeedback().Show();
}
} catch {
DoDebug("Failed to check for 'Evalufied'-availability");
}
} else {
DoDebug("No internet connection, not showing user feedback window");
}
}
//Action mods implementation
ActionMods.CheckMods();
TaskSchedulerSetup();
hreplacedtarted = true;
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep
Application.Run();
}
if (sentryToken != "super_secret") {
//Tracking issues with Sentry.IO - not forked from GitHub (official version)
bool sentryOK = false;
try {
if (Properties.Settings.Default.UID != "") {
Properties.Settings.Default.UID = Guid.NewGuid().ToString();
Properties.Settings.Default.Save();
}
if (Properties.Settings.Default.UID != "") {
SentrySdk.ConfigureScope(scope => {
scope.User = new Sentry.Protocol.User {
Id = Properties.Settings.Default.UID
};
});
}
using (SentrySdk.Init(sentryToken)) {
sentryOK = true;
}
} catch {
//Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running
DoDebug("Sentry initiation failed");
ActualMain();
}
if (sentryOK) {
try {
using (SentrySdk.Init(sentryToken)) {
DoDebug("Sentry initiated");
ActualMain();
}
} catch {
ActualMain();
}
}
} else {
//Code is (most likely) forked - skip issue tracking
ActualMain();
}
}
19
View Source File : SoftwareUpdater.cs
License : MIT License
Project Creator : AlbertMN
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
License : MIT License
Project Creator : alen-smajic
private void setupRequest() {
#if !NETFX_CORE
_request = WebRequest.Create(_requestUrl) as HttpWebRequest;
_request.UserAgent = _userAgent;
//_hwr.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36";
//_hwr.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
_request.Credentials = CredentialCache.DefaultCredentials;
_request.KeepAlive = true;
_request.ProtocolVersion = HttpVersion.Version11; // improved performance
// improved performance.
// ServicePointManager.DefaultConnectionLimit doesn't seem to change anything
// set ConnectionLimit per request
// https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v=vs.90).aspx#Remarks
// use a value that is 12 times the number of CPUs on the local computer
_request.ServicePoint.ConnectionLimit = Environment.ProcessorCount * 6;
_request.ServicePoint.UseNagleAlgorithm = true;
_request.ServicePoint.Expect100Continue = false;
_request.ServicePoint.MaxIdleTime = 2000;
_request.Method = "GET";
_request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
_request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
//_hwr.Timeout = timeOut * 1000; doesn't work in async calls, see below
#else
HttpClientHandler handler = new HttpClientHandler() {
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
AllowAutoRedirect = true,
UseDefaultCredentials = true
};
_request = new HttpClient(handler);
_request.DefaultRequestHeaders.Add("User-Agent", _userAgent);
_request.Timeout = TimeSpan.FromSeconds(_timeOut);
// TODO: how to set ConnectionLimit? ServicePoint.ConnectionLimit doesn't seem to be available.
#endif
#if !UNITY && !NETFX_CORE
// 'NoCacheNoStore' greatly reduced the number of faulty request
// seems that .Net caching and Mapbox API don't play well together
_request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
#endif
}
19
View Source File : HTTPRequestThreaded.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
private void setupRequest() {
#if !NETFX_CORE
_request = WebRequest.Create(_requestUrl) as HttpWebRequest;
_request.UserAgent = _userAgent;
//_hwr.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36";
//_hwr.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
_request.Credentials = CredentialCache.DefaultCredentials;
_request.KeepAlive = true;
_request.ProtocolVersion = HttpVersion.Version11; // improved performance
// improved performance.
// ServicePointManager.DefaultConnectionLimit doesn't seem to change anything
// set ConnectionLimit per request
// https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v=vs.90).aspx#Remarks
// use a value that is 12 times the number of CPUs on the local computer
_request.ServicePoint.ConnectionLimit = Environment.ProcessorCount * 6;
_request.ServicePoint.UseNagleAlgorithm = true;
_request.ServicePoint.Expect100Continue = false;
_request.ServicePoint.MaxIdleTime = 2000;
_request.Method = "GET";
_request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
_request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
//_hwr.Timeout = timeOut * 1000; doesn't work in async calls, see below
#else
HttpClientHandler handler = new HttpClientHandler() {
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
AllowAutoRedirect = true,
UseDefaultCredentials = true
};
_request = new HttpClient(handler);
_request.DefaultRequestHeaders.Add("User-Agent", _userAgent);
_request.Timeout = TimeSpan.FromSeconds(_timeOut);
// TODO: how to set ConnectionLimit? ServicePoint.ConnectionLimit doesn't seem to be available.
#endif
#if !UNITY && !NETFX_CORE
// 'NoCacheNoStore' greatly reduced the number of faulty request
// seems that .Net caching and Mapbox API don't play well together
_request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
#endif
}
19
View Source File : Embedder.cs
License : MIT License
Project Creator : alexanderkyte
License : MIT License
Project Creator : alexanderkyte
public static WebreplacedemblyEmbedder
FromUrl (string URL)
{
using (var source = WebRequest.Create(URL).GetResponse().GetResponseStream ()) {
return new WebreplacedemblyEmbedder (source);
}
}
19
View Source File : CrashForm.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
private void sendButton_Click(object sender, EventArgs e) {
try {
Version version = typeof(CrashForm).replacedembly.GetName().Version;
WebRequest request = WebRequest.Create(
"http://openhardwaremonitor.org/report.php");
request.Method = "POST";
request.Timeout = 5000;
request.ContentType = "application/x-www-form-urlencoded";
string report =
"type=crash&" +
"version=" + Uri.EscapeDataString(version.ToString()) + "&" +
"report=" + Uri.EscapeDataString(reportTextBox.Text) + "&" +
"comment=" + Uri.EscapeDataString(commentTextBox.Text) + "&" +
"email=" + Uri.EscapeDataString(emailTextBox.Text);
byte[] byteArray = Encoding.UTF8.GetBytes(report);
request.ContentLength = byteArray.Length;
try {
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
Close();
} catch (WebException) {
MessageBox.Show("Sending the crash report failed.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} catch {
}
}
19
View Source File : ReportForm.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
private void sendButton_Click(object sender, EventArgs e) {
Version version = typeof(CrashForm).replacedembly.GetName().Version;
WebRequest request = WebRequest.Create(
"http://openhardwaremonitor.org/report.php");
request.Method = "POST";
request.Timeout = 5000;
request.ContentType = "application/x-www-form-urlencoded";
string report =
"type=hardware&" +
"version=" + Uri.EscapeDataString(version.ToString()) + "&" +
"report=" + Uri.EscapeDataString(reportTextBox.Text) + "&" +
"comment=" + Uri.EscapeDataString(commentTextBox.Text) + "&" +
"email=" + Uri.EscapeDataString(emailTextBox.Text);
byte[] byteArray = Encoding.UTF8.GetBytes(report);
request.ContentLength = byteArray.Length;
try {
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
Close();
} catch (WebException) {
MessageBox.Show("Sending the hardware report failed.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
19
View Source File : TileMapAnnotation.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
private OxyImage Download(string uri)
{
OxyImage img = null;
var mre = new ManualResetEvent(false);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.BeginGetResponse(
r =>
{
try
{
if (request.HaveResponse)
{
var response = request.EndGetResponse(r);
var stream = response.GetResponseStream();
var ms = new MemoryStream();
stream.CopyTo(ms);
var buffer = ms.ToArray();
img = new OxyImage(buffer);
this.images[uri] = img;
}
}
catch (Exception e)
{
var ie = e;
while (ie != null)
{
System.Diagnostics.Debug.WriteLine(ie.Message);
ie = ie.InnerException;
}
}
finally
{
mre.Set();
}
},
request);
mre.WaitOne();
return img;
}
19
View Source File : TileMapAnnotation.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
private void BeginDownload()
{
if (this.numberOfDownloads >= this.MaxNumberOfDownloads)
{
return;
}
string uri = this.queue.Dequeue();
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
Interlocked.Increment(ref this.numberOfDownloads);
request.BeginGetResponse(
r =>
{
Interlocked.Decrement(ref this.numberOfDownloads);
try
{
if (request.HaveResponse)
{
var response = request.EndGetResponse(r);
var stream = response.GetResponseStream();
this.DownloadCompleted(uri, stream);
}
}
catch (Exception e)
{
var ie = e;
while (ie != null)
{
System.Diagnostics.Debug.WriteLine(ie.Message);
ie = ie.InnerException;
}
}
},
request);
}
See More Examples