Here are the examples of the csharp api System.Net.WebResponse.GetResponseStream() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
848 Examples
19
Source : Utility.Http.cs
with MIT License
from 7Bytes-Studio
with MIT License
from 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
Source : BTCChinaAPI.cs
with MIT License
from aabiryukov
with MIT License
from 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
Source : ViaCepWebservice.cs
with MIT License
from ACBrNet
with MIT License
from 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
Source : ConsultaExtensions.cs
with MIT License
from ACBrNet
with MIT License
from ACBrNet
internal static string SendPost(this HttpWebRequest request, Dictionary<string, string> postData, Encoding enconde)
{
request.Method = "POST";
var post = new StringBuilder();
var lastKey = postData.Last().Key;
foreach (var postValue in postData)
{
post.Append($"{postValue.Key}={postValue.Value}");
if (postValue.Key != lastKey) post.Append("&");
}
var byteArray = enconde.GetBytes(post.ToString());
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
Guard.Against<ACBrException>(responseStream == null, "Erro ao acessar o site.");
string retorno;
using (var stHtml = new StreamReader(responseStream, enconde))
retorno = stHtml.ReadToEnd();
return retorno;
}
19
Source : CorreiosWebservice.cs
with MIT License
from ACBrNet
with MIT License
from 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
Source : Program_DbUpdates.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from 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
Source : Program_Setup.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from 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
Source : SCaddins.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from 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
Source : PaypalHelper.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : SharePointFileHandler.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public void ProcessRequest(HttpContext context)
{
if (!string.Equals(context.Request.HttpMethod, "GET", StringComparison.InvariantCultureIgnoreCase)
|| SharePointFileUrl == null
|| string.IsNullOrWhiteSpace(FileName))
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
try
{
var spConnection = new SharePointConnection("SharePoint");
var factory = new ClientFactory();
var request = factory.CreateHttpWebRequest(spConnection, SharePointFileUrl) as HttpWebRequest;
// make sure SharePoint receives the cache control headers from the browser
var requestHeaders = _headersToRequest
.Select(name => new { Name = name, Value = context.Request.Headers[name] })
.Where(header => !string.IsNullOrWhiteSpace(header.Value))
.ToList();
foreach (var header in requestHeaders)
{
request.Headers[header.Name] = header.Value;
}
request.Accept = context.Request.Headers["Accept"];
request.UserAgent = context.Request.Headers["User-Agent"];
DateTime ifModifiedSince;
if (DateTime.TryParse(context.Request.Headers["If-Modified-Since"], out ifModifiedSince))
{
request.IfModifiedSince = ifModifiedSince;
}
WebResponse response;
try
{
response = request.GetResponse();
}
catch (WebException we)
{
// handle non-200 response from SharePoint
var hwr = we.Response as HttpWebResponse;
if (hwr != null && hwr.StatusCode == HttpStatusCode.NotModified)
{
context.Response.StatusCode = (int)HttpStatusCode.NotModified;
return;
}
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Exception thrown trying to download {0}", SharePointFileUrl));
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("ProcessRequest", "Exception details: {0}", we.ToString()));
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
return;
}
using (var stream = response.GetResponseStream())
{
// forward SharePoint response headers back to the browser
var responseHeaders = _headersToRespond
.Select(name => new { Name = name, Value = response.Headers[name] })
.Where(header => !string.IsNullOrWhiteSpace(header.Value))
.ToList();
foreach (var header in responseHeaders)
{
context.Response.AppendHeader(header.Name, header.Value);
}
context.Response.AppendHeader("Content-Disposition", @"attachment; filename=""{0}""".FormatWith(FileName));
int contentLength;
if (!int.TryParse(response.Headers["Content-Length"], out contentLength))
{
// indeterminant length
contentLength = -1;
}
if (contentLength == 0)
{
context.Response.StatusCode = (int)HttpStatusCode.NoContent;
return;
}
// start streaming file
context.Response.StatusCode = (int)HttpStatusCode.OK;
const int bufferSize = 65536;
var buffer = new byte[bufferSize];
int bytesRead;
do
{
bytesRead = stream.Read(buffer, 0, bufferSize);
context.Response.OutputStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
}
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Exception thrown trying to download {0}", SharePointFileUrl));
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Exception details: {0}", e.ToString()));
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
}
19
Source : deviceidmanager.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : WebApiCaller.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public ApiResult<TResult> GetResult<TResult>(HttpWebRequest req)
{
string jsonResult;
try
{
using (var webResponse = req.GetResponse())
{
var receivedStream2 = webResponse.GetResponseStream();
if (receivedStream2 == null)
{
LogRecorderX.EndStepMonitor();
return ApiResult.Error<TResult>(-1, "服务器无返回值");
}
jsonResult = new StreamReader(receivedStream2).ReadToEnd();
receivedStream2.Dispose();
webResponse.Close();
}
}
catch (WebException e)
{
if (e.Status != WebExceptionStatus.ProtocolError)
{
LogRecorderX.EndStepMonitor();
switch (e.Status)
{
case WebExceptionStatus.CacheEntryNotFound:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "找不到指定的缓存项");
case WebExceptionStatus.ConnectFailure:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "在传输级别无法联系远程服务点");
case WebExceptionStatus.ConnectionClosed:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "过早关闭连接");
case WebExceptionStatus.KeepAliveFailure:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "指定保持活动状态的标头的请求的连接意外关闭");
case WebExceptionStatus.MessageLengthLimitExceeded:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "已收到一条消息的发送请求时超出指定的限制或从服务器接收响应");
case WebExceptionStatus.NameResolutionFailure:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "名称解析程序服务或无法解析主机名");
case WebExceptionStatus.Pending:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "内部异步请求处于挂起状态");
case WebExceptionStatus.PipelineFailure:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "该请求是管线请求和连接被关闭之前收到响应");
case WebExceptionStatus.ProxyNameResolutionFailure:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "名称解析程序服务无法解析代理服务器主机名");
case WebExceptionStatus.ReceiveFailure:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "从远程服务器未收到完整的响应");
case WebExceptionStatus.RequestCanceled:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "请求已取消");
case WebExceptionStatus.RequestProhibitedByCachePolicy:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "缓存策略不允许该请求");
case WebExceptionStatus.RequestProhibitedByProxy:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "由该代理不允许此请求");
case WebExceptionStatus.SecureChannelFailure:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "使用 SSL 建立连接时出错");
case WebExceptionStatus.SendFailure:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "无法与远程服务器发送一个完整的请求");
case WebExceptionStatus.ServerProtocolViolation:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "服务器响应不是有效的 HTTP 响应");
case WebExceptionStatus.Timeout:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "请求的超时期限内未不收到任何响应");
case WebExceptionStatus.TrustFailure:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "无法验证服务器证书");
default:
return ApiResult.Error<TResult>(ErrorCode.RemoteError, "发生未知类型的异常");
}
}
using (var response = e.Response)
{
var receivedStream = response.GetResponseStream();
if (receivedStream == null)
{
LogRecorderX.EndStepMonitor();
return ApiResult.Error<TResult>(-1, "服务器无返回值");
}
jsonResult = new StreamReader(receivedStream).ReadToEnd();
receivedStream.Dispose();
response.Close();
}
}
catch (Exception ex)
{
LogRecorderX.Exception(ex);
LogRecorderX.EndStepMonitor();
return ApiResult.Error<TResult>(ErrorCode.RemoteError);
}
LogRecorderX.MonitorTrace(jsonResult);
try
{
return string.IsNullOrWhiteSpace(jsonResult)
? ApiResult.Error<TResult>(-1)
: JsonConvert.DeserializeObject<ApiResult<TResult>>(jsonResult);
}
catch (Exception ex2)
{
LogRecorderX.Exception(ex2);
return ApiResult.Error<TResult>(-1);
}
finally
{
LogRecorderX.EndStepMonitor();
}
}
19
Source : WebApiCaller.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public ApiValueResult GetResult(HttpWebRequest req)
{
string jsonResult;
try
{
using (var response = req.GetResponse())
{
var receivedStream2 = response.GetResponseStream();
if (receivedStream2 == null)
{
LogRecorderX.EndStepMonitor();
return ErrorResult(-1, "服务器无返回值");
}
jsonResult = new StreamReader(receivedStream2).ReadToEnd();
receivedStream2.Dispose();
response.Close();
}
}
catch (WebException e3)
{
try
{
if (e3.Status != WebExceptionStatus.ProtocolError)
{
LogRecorderX.EndStepMonitor();
switch (e3.Status)
{
case WebExceptionStatus.CacheEntryNotFound:
return ErrorResult(-3, "找不到指定的缓存项");
case WebExceptionStatus.ConnectFailure:
return ErrorResult(-3, "在传输级别无法联系远程服务点");
case WebExceptionStatus.ConnectionClosed:
return ErrorResult(-3, "过早关闭连接");
case WebExceptionStatus.KeepAliveFailure:
return ErrorResult(-3, "指定保持活动状态的标头的请求的连接意外关闭");
case WebExceptionStatus.MessageLengthLimitExceeded:
return ErrorResult(-3, "已收到一条消息的发送请求时超出指定的限制或从服务器接收响应");
case WebExceptionStatus.NameResolutionFailure:
return ErrorResult(-3, "名称解析程序服务或无法解析主机名");
case WebExceptionStatus.Pending:
return ErrorResult(-3, "内部异步请求处于挂起状态");
case WebExceptionStatus.PipelineFailure:
return ErrorResult(-3, "该请求是管线请求和连接被关闭之前收到响应");
case WebExceptionStatus.ProxyNameResolutionFailure:
return ErrorResult(-3, "名称解析程序服务无法解析代理服务器主机名");
case WebExceptionStatus.ReceiveFailure:
return ErrorResult(-3, "从远程服务器未收到完整的响应");
case WebExceptionStatus.RequestCanceled:
return ErrorResult(-3, "请求已取消");
case WebExceptionStatus.RequestProhibitedByCachePolicy:
return ErrorResult(-3, "缓存策略不允许该请求");
case WebExceptionStatus.RequestProhibitedByProxy:
return ErrorResult(-3, "由该代理不允许此请求");
case WebExceptionStatus.SecureChannelFailure:
return ErrorResult(-3, "使用 SSL 建立连接时出错");
case WebExceptionStatus.SendFailure:
return ErrorResult(-3, "无法与远程服务器发送一个完整的请求");
case WebExceptionStatus.ServerProtocolViolation:
return ErrorResult(-3, "服务器响应不是有效的 HTTP 响应");
case WebExceptionStatus.Timeout:
return ErrorResult(-3, "请求的超时期限内未不收到任何响应");
case WebExceptionStatus.TrustFailure:
LogRecorderX.EndStepMonitor();
return ErrorResult(-3, "无法验证服务器证书");
default:
return ErrorResult(-3, "发生未知类型的异常");
}
}
var codes = e3.Message.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
if (codes.Length == 3 && int.TryParse(codes[1], out var s) && s == 404)
{
return ErrorResult(-3, "服务器内部错误", "页面不存在");
}
using (var webResponse = e3.Response)
{
var receivedStream = webResponse.GetResponseStream();
if (receivedStream == null)
{
LogRecorderX.EndStepMonitor();
return ErrorResult(-1, "服务器无返回值");
}
jsonResult = new StreamReader(receivedStream).ReadToEnd();
receivedStream.Dispose();
webResponse.Close();
}
}
catch (Exception e)
{
LogRecorderX.Exception(e);
LogRecorderX.EndStepMonitor();
return ErrorResult(-1, "未知错误", e.Message);
}
}
catch (Exception e2)
{
LogRecorderX.Exception(e2);
LogRecorderX.EndStepMonitor();
return ErrorResult(-1, "未知错误", e2.Message);
}
LogRecorderX.MonitorTrace(jsonResult);
try
{
if (string.IsNullOrWhiteSpace(jsonResult))
return ErrorResult(-1);
var baseResult = JsonConvert.DeserializeObject<ApiResult>(jsonResult);
return (!baseResult.Success) ? ErrorResult(baseResult.Status.ErrorCode, baseResult.Status.ClientMessage) : ApiValueResult.Succees(ReadResultData(jsonResult, "ResultData"));
}
catch (Exception e)
{
LogRecorderX.Exception(e);
return ErrorResult(-1, "未知错误", e.Message);
}
}
19
Source : HttpApiCaller.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
private static async Task<string> ReadResponse(WebResponse response)
{
string json;
using (response)
{
if (response.ContentLength == 0)
{
return null;
}
var receivedStream = response.GetResponseStream();
if (receivedStream == null)
return null;
using (receivedStream)
{
using (var streamReader = new StreamReader(receivedStream))
{
json = await streamReader.ReadToEndAsync();
streamReader.Close();
}
receivedStream.Close();
}
response.Close();
}
return json;
}
19
Source : HttpApiCaller.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
private static string ReadResponse(WebResponse response)
{
string result = null;
using (response)
{
if (response.ContentLength != 0)
{
var receivedStream = response.GetResponseStream();
if (receivedStream != null)
{
using (receivedStream)
{
using (var streamReader = new StreamReader(receivedStream))
{
result = streamReader.ReadToEnd();
streamReader.Close();
}
}
receivedStream.Close();
}
}
response.Close();
}
return result;
}
19
Source : HttpApiCaller.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
private static string ReadResponse(WebResponse response)
{
string result;
using (response)
{
if (response.ContentLength == 0)
{
result = ApiResult.RemoteEmptyErrorJson;
}
else
{
var receivedStream = response.GetResponseStream();
if (receivedStream == null)
result = ApiResult.RemoteEmptyErrorJson;
else
using (receivedStream)
{
using (var streamReader = new StreamReader(receivedStream))
{
result = streamReader.ReadToEnd();
streamReader.Close();
}
receivedStream.Close();
}
}
response.Close();
}
return result;
}
19
Source : Comment.cs
with MIT License
from AlaricGilbert
with MIT License
from AlaricGilbert
public static async Task<string> SendAsync(string av_number, string comment)
{
var req = WebRequest.CreateHttp($"https://api.bilibili.com/x/v2/reply/add?oid={av_number}&type=1&message={comment}&plat=1&jsonp=jsonp&csrf={Account.CookieJObjet["bili_jct"].Value<string>()}");
req.Method = "POST";
req.Host = "api.bilibili.com";
//req.Connection = "keep-alive";
req.Accept = "application/json, text/javascript, */*; q=0.01";
req.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36";
req.ContentType = "application/x-www-form-urlencoded";
req.Referer = "https://www.bilibili.com/video/av" + av_number;
req.Headers.Add("Accept-Encoding", "gzip, deflate, br");
req.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9");
req.Headers.Add("Cookie", Account.CookieString);
var response = await req.GetResponseAsync();
var r_stream = response.GetResponseStream();
byte[] buffer = new byte[response.ContentLength];
r_stream.ReadAsync(buffer, 0, (int)response.ContentLength).Wait();
return Encoding.UTF8.GetString(buffer);
}
19
Source : Embedder.cs
with MIT License
from alexanderkyte
with MIT License
from alexanderkyte
public static WebreplacedemblyEmbedder
FromUrl (string URL)
{
using (var source = WebRequest.Create(URL).GetResponse().GetResponseStream ()) {
return new WebreplacedemblyEmbedder (source);
}
}
19
Source : CrashForm.cs
with MIT License
from AlexGyver
with MIT License
from 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
Source : ReportForm.cs
with MIT License
from AlexGyver
with MIT License
from 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
Source : TileMapAnnotation.cs
with MIT License
from AlexGyver
with MIT License
from 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
Source : TileMapAnnotation.cs
with MIT License
from AlexGyver
with MIT License
from 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);
}
19
Source : BitMexClient.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public string CreateQuery(string method, string function, Dictionary<string, string> param = null, bool auth = false)
{
lock (_queryHttpLocker)
{
//Wait for RateGate
_rateGate.WaitToProceed();
string paramData = BuildQueryData(param);
string url = "/api/v1" + function + ((method == "GET" && paramData != "") ? "?" + paramData : "");
string postData = (method != "GET") ? paramData : "";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_domain + url);
webRequest.Method = method;
if (auth)
{
string nonce = GetNonce().ToString();
string message = method + url + nonce + postData;
byte[] signatureBytes = Hmacsha256(Encoding.UTF8.GetBytes(_secKey), Encoding.UTF8.GetBytes(message));
string signatureString = ByteArrayToString(signatureBytes);
webRequest.Headers.Add("api-nonce", nonce);
webRequest.Headers.Add("api-key", _id);
webRequest.Headers.Add("api-signature", signatureString);
}
try
{
if (postData != "")
{
webRequest.ContentType = "application/x-www-form-urlencoded";
var data = Encoding.UTF8.GetBytes(postData);
using (var stream = webRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
using (WebResponse webResponse = webRequest.GetResponse())
using (Stream str = webResponse.GetResponseStream())
using (StreamReader sr = new StreamReader(str))
{
return sr.ReadToEnd();
}
}
catch (WebException wex)
{
using (HttpWebResponse response = (HttpWebResponse)wex.Response)
{
if (response == null)
throw;
using (Stream str = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
string error = sr.ReadToEnd();
if (ErrorEvent != null)
{
ErrorEvent(error);
}
return sr.ReadToEnd();
}
}
}
}
}
}
19
Source : KrakenRestApi.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private JsonObject QueryPublic(string a_sMethod, string props = null)
{
string address = string.Format("{0}/{1}/public/{2}", _url, _version, a_sMethod);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(address);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
lock (_queryLocker)
{
try
{
if (props != null)
{
using (var writer = new StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(props);
}
}
}
catch (Exception)
{
//Thread.Sleep(2000);
if (props != null)
{
using (var writer = new StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(props);
}
}
}
//Wait for RateGate
_rateGate.WaitToProceed();
}
//Make the request
try
{
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (WebResponse webResponse = webRequest.GetResponse())
{
using (Stream str = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return (JsonObject)JsonConvert.Import(sr);
}
}
}
}
catch (WebException wex)
{
using (HttpWebResponse response = (HttpWebResponse)wex.Response)
{
using (Stream str = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
if (response.StatusCode != HttpStatusCode.InternalServerError)
{
throw;
}
return (JsonObject)JsonConvert.Import(sr);
}
}
}
}
}
19
Source : LivecoinClient.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private string SendQuery(bool isAuth, string endPoint, string publicKey = "", string secretKey = "", string data = "")
{
string ResponseFromServer = "";
HttpStatusCode StatusCode;
string uri;
if (isAuth)
{
uri = _baseUri + endPoint;
}
else
{
uri = _baseUri + endPoint + data;
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream;
if (isAuth)
{
string param = http_build_query(data);
string Sign = HashHMAC(secretKey, param).ToUpper();
request.Headers["Api-Key"] = publicKey;
request.Headers["Sign"] = Sign;
}
try
{
WebResponse WebResponse = request.GetResponse();
dataStream = WebResponse.GetResponseStream();
StreamReader StreamReader = new StreamReader(dataStream);
ResponseFromServer = StreamReader.ReadToEnd();
dataStream.Close();
WebResponse.Close();
StatusCode = HttpStatusCode.OK;
return ResponseFromServer;
}
catch (WebException ex)
{
if (ex.Response != null)
{
dataStream = ex.Response.GetResponseStream();
StreamReader StreamReader = new StreamReader(dataStream);
StatusCode = ((HttpWebResponse)ex.Response).StatusCode;
ResponseFromServer = ex.Message;
}
else
{
StatusCode = HttpStatusCode.ExpectationFailed;
ResponseFromServer = "Неизвестная ошибка";
}
return ResponseFromServer;
}
catch (Exception ex)
{
StatusCode = HttpStatusCode.ExpectationFailed;
ResponseFromServer = "Неизвестная ошибка";
return ResponseFromServer;
}
}
19
Source : KrakenRestApi.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private JsonObject QueryPrivate(string a_sMethod, string props = null)
{
// generate a 64 bit nonce using a timestamp at tick resolution
Int64 nonce = DateTime.Now.Ticks;
props = "nonce=" + nonce + props;
string path = string.Format("/{0}/private/{1}", _version, a_sMethod);
string address = _url + path;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(address);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
webRequest.Headers.Add("API-Key", _key);
byte[] base64DecodedSecred = Convert.FromBase64String(_secret);
var np = nonce + Convert.ToChar(0) + props;
var pathBytes = Encoding.UTF8.GetBytes(path);
var hash256Bytes = sha256_hash(np);
var z = new byte[pathBytes.Count() + hash256Bytes.Count()];
pathBytes.CopyTo(z, 0);
hash256Bytes.CopyTo(z, pathBytes.Count());
var signature = getHash(base64DecodedSecred, z);
webRequest.Headers.Add("API-Sign", Convert.ToBase64String(signature));
if (props != null)
{
using (var writer = new StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(props);
}
}
//Make the request
try
{
//Wait for RateGate
_rateGate.WaitToProceed();
//Thread.Sleep(2000);
using (WebResponse webResponse = webRequest.GetResponse())
{
using (Stream str = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return (JsonObject)JsonConvert.Import(sr);
}
}
}
}
catch (WebException wex)
{
using (HttpWebResponse response = (HttpWebResponse)wex.Response)
{
using (Stream str = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
if (response.StatusCode != HttpStatusCode.InternalServerError)
{
throw;
}
return (JsonObject)JsonConvert.Import(sr);
}
}
}
}
}
19
Source : Response.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from 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
Source : SelfUpdateProgressPage.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from 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
Source : CheckForUpdates.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
private void OnResponse(IAsyncResult ar)
{
IAnkhConfigurationService config = Context.GetService<IAnkhConfigurationService>();
bool failed = true;
string tag = null;
try
{
WebRequest rq = ((WebRequest)ar.AsyncState);
WebResponse wr;
try
{
wr = rq.EndGetResponse(ar);
}
catch (WebException e)
{
HttpWebResponse hwr = e.Response as HttpWebResponse;
if (hwr != null)
{
if (hwr.StatusCode == HttpStatusCode.NotFound)
{
failed = false;
return; // File not found.. Update info not yet or no longer available
}
}
return;
}
catch
{
return;
}
if (wr.ContentLength > 65536) // Not for us.. We expect a few hundred bytes max
return;
string body;
using (Stream s = wr.GetResponseStream())
using (StreamReader sr = new StreamReader(s))
{
body = sr.ReadToEnd().Trim();
}
if (string.IsNullOrEmpty(body))
{
failed = false;
return;
}
if (body[0] != '<' || body[body.Length - 1] != '>')
return; // No valid xml or empty
failed = false;
XmlDoreplacedent doc = new XmlDoreplacedent();
doc.LoadXml(body);
string replacedle = NodeText(doc, "/u/i/t");
string header = NodeText(doc, "/u/i/h") ?? replacedle;
string description = NodeText(doc, "/u/i/d");
string url = NodeText(doc, "/u/i/u");
string urltext = NodeText(doc, "/u/i/l");
string version = NodeText(doc, "/u/i/v");
string newVersion = NodeText(doc, "/u/i/n") ?? version;
tag = NodeText(doc, "/u/g");
if (!string.IsNullOrEmpty(replacedle) && !string.IsNullOrEmpty(description))
{
if (!string.IsNullOrEmpty(version))
{
Version v = new Version(version);
if (v <= GetCurrentVersion(Context))
return;
}
if (!string.IsNullOrEmpty(tag))
{
using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
{
string pTag = rk.GetValue("SkipTag") as string;
if (pTag == tag)
return;
}
}
IAnkhCommandService cs = Context.GetService<IAnkhCommandService>();
cs.PostExecCommand(AnkhCommand.CheckForUpdates,
new string[] { replacedle, header, description, url, urltext, version, newVersion, tag });
}
}
finally
{
using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
{
object fails = rk.GetValue("Fails", 0);
rk.DeleteValue("LastCheck", false);
rk.DeleteValue("LastVersion", false);
rk.DeleteValue("FailedChecks", false);
rk.SetValue("LastCheck", DateTime.UtcNow.Ticks);
rk.SetValue("LastVersion", GetCurrentVersion(Context).ToString());
if (tag != null)
rk.SetValue("LastTag", tag);
else
rk.DeleteValue("LastTag", false);
if (failed)
{
int f = 0;
if (fails is int)
f = (int)fails + 1;
rk.SetValue("FailedChecks", f);
}
}
}
}
19
Source : Networking.cs
with GNU General Public License v3.0
from anderson-joyle
with GNU General Public License v3.0
from anderson-joyle
protected string fetch(Uri uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri.AbsoluteUri);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol =
SecurityProtocolType.Tls |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls12 |
SecurityProtocolType.Ssl3;
string ret = string.Empty;
request.Method = "GET";
request.Accept = "application/json";
request.ContentLength = 0;
using (var response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(responseStream))
{
ret = streamReader.ReadToEnd();
}
}
}
return ret;
}
19
Source : GeoCodeAddress.cs
with MIT License
from AndrewButenko
with MIT License
from AndrewButenko
protected override void ExecuteWorkflowLogic()
{
if (string.IsNullOrWhiteSpace(Context.Settings.BingMapsKey))
throw new InvalidPluginExecutionException("BingMaps Key setting is not available.");
var address = Address.Get(Context.ExecutionContext);
if (string.IsNullOrWhiteSpace(address))
throw new InvalidPluginExecutionException("Address parameter is not available");
var url = $"http://dev.virtualearth.net/REST/v1/Locations?q={Uri.EscapeDataString(address)}&key={Context.Settings.BingMapsKey}";
string jsonResult = null;
var request = (HttpWebRequest)WebRequest.Create(url);
using (var resStream = new StreamReader(request.GetResponse().GetResponseStream()))
{
jsonResult = resStream.ReadToEnd();
}
var response = JsonConvert.DeserializeObject<Response>(jsonResult);
if (response.StatusCode != 200)
{
throw new InvalidPluginExecutionException($"BingMaps Endpoint call failed - {string.Join(Environment.NewLine, response.ErrorDetails)}{Environment.NewLine}{response.StatusDescription}");
}
var geocodePoint = response.ResourceSets.FirstOrDefault()?.Resources.FirstOrDefault()?.GeocodePoints
.FirstOrDefault();
if (geocodePoint == null)
{
IsResolved.Set(Context.ExecutionContext, false);
return;
}
IsResolved.Set(Context.ExecutionContext, true);
Lareplacedude.Set(Context.ExecutionContext, Convert.ToDecimal(geocodePoint.Coordinates[0]));
Longitude.Set(Context.ExecutionContext, Convert.ToDecimal(geocodePoint.Coordinates[1]));
}
19
Source : ConvertFile.cs
with MIT License
from AndrewButenko
with MIT License
from AndrewButenko
protected override void ExecuteOperation(Enreplacedy file, EnreplacedyReference parentRecord, string currentFileName)
{
var resultingFileName = ResultingFileName.Get(Context.ExecutionContext);
if (string.IsNullOrEmpty(resultingFileName))
throw new InvalidPluginExecutionException("Resulting File Name Parameter is empty!");
var resultingFileNameParts = resultingFileName.Split('.');
var currentFileNameParts = currentFileName.Split('.');
var baseUrl = "https://api.cloudconvert.com/convert";
var request = WebRequest.Create(baseUrl);
request.Method = "POST";
request.ContentType = "application/json";
var convertFileRequest = new ConvertFileRequest()
{
ApiKey = Context.Settings.CloudConvertKey,
File = file.GetAttributeValue<string>("doreplacedentbody"),
OutputFormat = resultingFileNameParts[resultingFileNameParts.Length - 1],
InputMethod = "base64",
FileName = currentFileName,
InputFormat = currentFileNameParts[currentFileNameParts.Length - 1]
};
var requestBodyString = JsonConvert.SerializeObject(convertFileRequest);
var requestData = Encoding.Default.GetBytes(requestBodyString);
using (var stream = request.GetRequestStream())
{
stream.Write(requestData, 0, requestData.Length);
}
var inputStream = request.GetResponse().GetResponseStream();
var memoStream = new MemoryStream();
inputStream.CopyTo(memoStream);
inputStream.Close();
string newFileContent;
memoStream.Position = 0;
using (var msr = new StreamReader(memoStream, Encoding.Default))
{
newFileContent = msr.ReadToEnd();
}
memoStream.Close();
var attachment = new Enreplacedy("annotation")
{
["subject"] = file.GetAttributeValue<string>("subject"),
["filename"] = resultingFileName,
["doreplacedentbody"] = Convert.ToBase64String(Encoding.Default.GetBytes(newFileContent)),
["isdoreplacedent"] = true,
["objectid"] = parentRecord
};
var isReplaceOriginal = IsReplaceOriginalFile.Get(Context.ExecutionContext);
if (isReplaceOriginal)
{
attachment.Id = file.Id;
Context.UserService.Update(attachment);
}
else
{
Context.UserService.Create(attachment);
}
}
19
Source : RefreshCurrencyExchangeRates.cs
with MIT License
from AndrewButenko
with MIT License
from 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
Source : ImageLoader.cs
with MIT License
from AngeloCresta
with MIT License
from 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
Source : MGDBDownloader.cs
with MIT License
from architdate
with MIT License
from architdate
public static string DownloadString(string address)
{
using (WebClient client = new WebClient())
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/projectpokemon/EventsGallery/releases/latest");
request.Method = "GET";
request.UserAgent = "PKHeX-Auto-Legality-Mod";
request.Accept = "application/json";
WebResponse response = request.GetResponse(); //Error Here
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string result = reader.ReadToEnd();
return result;
}
}
19
Source : NetUtil.cs
with MIT License
from architdate
with MIT License
from architdate
private static Stream GetStreamFromURL(string url)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// The GitHub API will fail if no user agent is provided
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36";
var httpWebResponse = httpWebRequest.GetResponse();
return httpWebResponse.GetResponseStream();
}
19
Source : QRParser.cs
with MIT License
from architdate
with MIT License
from architdate
public Image getQRData()
{
byte[] data = Encoding.ASCII.GetBytes("savedataId=" + sID + "&battleTeamCd=" + tID);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://3ds.pokemon-gl.com/frontendApi/battleTeam/getQr");
request.Method = "POST";
request.Accept = "*/*";
request.Headers["Accept-Encoding"] = "gzip, deflate, br";
request.Headers["Accept-Language"] = "en-US,en;q=0.8";
request.KeepAlive = true;
request.ContentLength = 73;
request.ContentType = "application/x-www-form-urlencoded";
request.Headers["Cookie"] = cookie;
request.Host = "3ds.pokemon-gl.com";
request.Headers["Origin"] = "https://3ds.pokemon-gl.com/";
request.Referer = "https://3ds.pokemon-gl.com/rentalteam/" + tID;
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36";
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
//add failing validation.
try
{
return Image.FromStream(stream);
}
catch (Exception e)
{
//invalid QR
return null;
}
}
}
}
19
Source : Proxy_Back.aspx.cs
with GNU General Public License v3.0
from ardatdev
with GNU General Public License v3.0
from ardatdev
protected void Page_Load(object sender, EventArgs e)
{
string url = Request.QueryString["url"];
if (url != null)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.Trim());
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string htmlText = reader.ReadToEnd();
reader.Close();
response.Close();
string a = "href=\"/";
int link = htmlText.IndexOf(a);
while (link >= 0)
{
htmlText = htmlText.Replace("\"/", "\"" + url);
if (a.Length < htmlText.Length)
{
link = htmlText.IndexOf(a, a.Length);
}
else
{
link = -1;
}
}
Web_Context.Text = htmlText;
}
}
19
Source : BotModule.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
[Command("setavatar", "Changes the bot's avatar.", CommandFlags.DirectMessageAllow | CommandFlags.OwnerOnly)]
[Parameter("Url", ParameterType.String, ParameterFlags.Optional)]
[Comment("Attach your new image to the message or provide a link.")]
public async Task SetAvatar(ICommand command)
{
if (command.ParametersCount <= 0 && command.Message.Attachments.Count <= 0)
throw new Framework.Exceptions.IncorrectParametersCommandException("Missing attachment.");
var request = WebRequest.CreateHttp(command["Url"].HasValue ? command["Url"] : command.Message.Attachments.First().Url);
using (var response = await request.GetResponseAsync())
using (var stream = response.GetResponseStream())
using (var memStream = new MemoryStream())
{
await stream.CopyToAsync(memStream);
memStream.Position = 0;
var image = new Image(memStream);
try
{
await _client.CurrentUser.ModifyAsync(x => x.Avatar = image);
}
catch (RateLimitedException)
{
await command.ReplyError("You are changing avatars too fast, wait a few minutes and try again.");
return;
}
}
await command.ReplySuccess("Avatar was changed!");
}
19
Source : AdministrationModule.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
[Command("say", "Sends a specified message.")]
[Permissions(GuildPermission.ManageMessages)]
[Parameter("TargetChannel", ParameterType.TextChannel, "a channel that will receive the message")]
[Parameter("Message", ParameterType.String, ParameterFlags.Remainder | ParameterFlags.Optional, "the message to be sent (you may also include one attachment)")]
public async Task Say(ICommand command)
{
var message = command["Message"].replacedtring ?? "";
var channel = command["TargetChannel"].AsTextChannel;
// This is a mods-only command, but to prevent permission escalation, check
// if there's any non-mentionable role and if the sender has a mention everyone perm
var nonMentionableRoles = command.Message.MentionedRoleIds.Where(x => !command.Guild.GetRole(x)?.IsMentionable ?? false).ToList();
var replaceRoleMentions = (message.ContainsEveryonePings() || nonMentionableRoles.Any()) &&
!((IGuildUser)command.Author).GetPermissions(channel).MentionEveryone;
if (replaceRoleMentions)
{
message = DiscordHelpers.ReplaceRoleMentions(message, nonMentionableRoles, command.Guild)
.Sanitise(allowRoleMentions: true);
}
if (command.Message.Attachments.Count <= 0)
{
if (string.IsNullOrEmpty(command["Message"]))
throw new Framework.Exceptions.IncorrectParametersCommandException("Specify a message or an attachment.");
await channel.SendMessageAsync(message);
}
else
{
var attachment = command.Message.Attachments.First();
var request = WebRequest.CreateHttp(attachment.Url);
using (var response = await request.GetResponseAsync())
using (var stream = response.GetResponseStream())
using (var memStream = new MemoryStream())
{
await stream.CopyToAsync(memStream);
memStream.Position = 0;
await channel.SendFileAsync(memStream, attachment.Filename, message);
}
}
if (command["TargetChannel"].AsTextChannel.Id != command.Message.Channel.Id)
await command.ReplySuccess("Message sent." + (replaceRoleMentions ? " To mention roles, @here, or @everyone you must have the Mention Everyone permission." : ""));
}
19
Source : ReactionsModule.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
[Command("reactions", "import", "Adds all reactions from a file.")]
[Alias("reaction", "import", true)]
[Comment("Attach a file with reactions obtained with `reactions export`. Expected format: \n`[{\"trigger1\":\"value1\"},{\"trigger2\":\"value2\"}]` \n\nAlternative format (doesn't allow duplicates): \n`{\"trigger1\":\"value1\",\"trigger2\":\"value2\"}`")]
public async Task ImportReactions(ICommand command)
{
await replacedertPrivileges(command.Author, command.GuildId);
if (!command.Message.Attachments.Any())
throw new IncorrectParametersCommandException("You need to attach a file with reactions obtained with `reactions export`.", true);
var attachment = command.Message.Attachments.First();
var request = WebRequest.CreateHttp(attachment.Url);
using (var response = await request.GetResponseAsync())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var content = await reader.ReadToEndAsync();
ICollection<Dictionary<string, string>> reactions;
try
{
reactions = JsonConvert.DeserializeObject<ICollection<Dictionary<string, string>>>(content);
}
catch (JsonException)
{
try
{
// Try the second format
reactions = new[] { JsonConvert.DeserializeObject<Dictionary<string, string>>(content) };
}
catch (JsonException)
{
throw new IncorrectParametersCommandException("The provided file is invalid.", true);
}
}
await _settings.Modify(command.GuildId, (ReactionsSettings s) =>
{
foreach (var reaction in reactions.SelectMany(x => x))
{
var newId = s.NextReactionId++;
s.Reactions.Add(new Reaction() { Id = newId, Trigger = reaction.Key, Value = reaction.Value });
}
});
await command.ReplySuccess($"Added {reactions.Count} reactions!");
}
}
19
Source : TranslatorModule.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
[Command("translate", "Translates a piece of text.")]
[Alias("tr"), Alias("번역")]
[Parameter("From", LanguageRegex, ParameterType.String, "the language of the message")]
[Parameter("To", LanguageRegex, ParameterType.String, "the language to translate into")]
[Parameter("Message", ParameterType.String, ParameterFlags.Remainder, "the word or sentence you want to translate")]
[Comment("Korean = `ko` \nreplacedan = `ja` \nEnglish = `en` \nChinese(Simplified) = `zh-CH` \nChinese(Traditional) = `zh-TW` \nSpanish = `es` \nFrench = `fr` \nGerman = `de` \nRussian = `ru` \nPortuguese = `pt` \nItalian = `it` \nVietnamese = `vi` \nThai = `th` \nIndonesian = `id`")]
[Example("ko en 사랑해")]
public async Task Translate(ICommand command, ILogger logger)
{
await command.Message.Channel.TriggerTypingAsync();
var stringMessage = command["Message"].ToString();
var firstLang = command["From"].ToString();
var lastLang = command["To"].ToString();
var byteDataParams = Encoding.UTF8.GetBytes($"source={Uri.EscapeDataString(firstLang)}&target={Uri.EscapeDataString(lastLang)}&text={Uri.EscapeDataString(stringMessage)}");
try
{
var request = WebRequest.CreateHttp("https://openapi.naver.com/v1/papago/n2mt");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("X-Naver-Client-Id", _integrationOptions.Value.PapagoClientId);
request.Headers.Add("X-Naver-Client-Secret", _integrationOptions.Value.PapagoClientSecret);
request.ContentLength = byteDataParams.Length;
using (var st = request.GetRequestStream())
{
st.Write(byteDataParams, 0, byteDataParams.Length);
}
using (var responseClient = await request.GetResponseAsync())
using (var reader = new StreamReader(responseClient.GetResponseStream()))
{
var parserObject = JObject.Parse(await reader.ReadToEndAsync());
var trMessage = parserObject["message"]["result"]["translatedText"].ToString();
var translateSentence = trMessage.Truncate(EmbedBuilder.MaxDescriptionLength);
EmbedBuilder embedBuilder = new EmbedBuilder()
.Withreplacedle($"Translation from **{firstLang.ToUpper()}** to **{lastLang.ToUpper()}**")
.WithDescription(translateSentence)
.WithColor(new Color(0, 206, 56))
.WithFooter("Powered by Papago");
await command.Reply(embedBuilder.Build());
}
}
catch (WebException ex) when (ex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.BadRequest)
{
throw new IncorrectParametersCommandException("Unsupported language combination.");
}
catch (WebException ex)
{
logger.LogError(ex, "Failed to reach Papago");
await command.Reply($"Couldn't reach Papago (error {(ex.Response as HttpWebResponse)?.StatusCode.ToString() ?? ex.Status.ToString()}). Please try again in a few seconds.");
}
}
19
Source : PlayFabAPI.cs
with MIT License
from AstroTechies
with MIT License
from AstroTechies
public static JObject SimpleReq(string operation, string data, bool allowReauth = true)
{
using (var wb = new WebClient())
{
wb.Headers[HttpRequestHeader.ContentType] = "application/json; charset=utf-8";
wb.Headers[HttpRequestHeader.UserAgent] = UserAgent;
wb.Headers.Add("X-PlayFabSDK", PlayFabSDK);
wb.Headers.Add("X-Authorization", Token);
try
{
string response = wb.UploadString("https://5EA1.playfabapi.com/Client/" + operation + "?sdk=" + PlayFabSDK, "POST", data);
return JObject.Parse(response);
}
catch (WebException ex)
{
string responseContent = "";
HttpStatusCode code = HttpStatusCode.Unused;
try
{
code = ((HttpWebResponse)ex.Response).StatusCode;
using (StreamReader r = new StreamReader(ex.Response.GetResponseStream()))
{
responseContent = r.ReadToEnd();
JObject erroredJObj = JObject.Parse(responseContent);
if (allowReauth && erroredJObj.GetValue("status").ToObject<string>() == "Unauthorized")
{
Auth();
return SimpleReq(operation, data, false);
}
}
}
catch { }
throw new PlayFabException(code + ": " + responseContent);
}
}
}
19
Source : AvaTaxClient.cs
with Apache License 2.0
from avadev
with Apache License 2.0
from avadev
private string RestCallString(string verb, AvaTaxPath relativePath, object content = null)
{
string path = CombinePath(_envUri.ToString(), relativePath.ToString());
string jsonPayload = null;
string mimeType = null;
// Use HttpWebRequest so we can get a decent response
var wr = (HttpWebRequest)WebRequest.Create(path);
wr.Proxy = null;
wr.Timeout = 1200000;
// Add headers
foreach (var key in _clientHeaders.Keys)
{
wr.Headers.Add(key, _clientHeaders[key]);
}
// Convert the name-value pairs into a byte array
wr.Method = verb;
//Upload file.
if (content != null && content is FileResult) {
wr.KeepAlive = true;
var fr = (FileResult)content;
mimeType = fr.ContentType;
content = fr.Data;
string dataBoundary = "----dataBoundary";
wr.ContentType = "multipart/form-data; boundary=" + dataBoundary;
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + dataBoundary + "\r\n");
Stream rs = wr.GetRequestStream();
rs.Write(boundaryBytes, 0, boundaryBytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, fr.Filename, fr.Filename, fr.ContentType);
byte[] headerBytes = Encoding.UTF8.GetBytes(header);
rs.Write(headerBytes, 0, headerBytes.Length);
rs.Write(fr.Data, 0, fr.Data.Length);
byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + dataBoundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
} else if (content != null) {
wr.ContentType = mimeType ?? Constants.JSON_MIME_TYPE;
wr.ServicePoint.Expect100Continue = false;
// Encode the payload
jsonPayload = JsonConvert.SerializeObject(content, SerializerSettings);
var encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(jsonPayload);
wr.ContentLength = data.Length;
// Call the server
using (var s = wr.GetRequestStream()) {
s.Write(data, 0, data.Length);
s.Close();
}
}
// Transmit, and get back the response, save it to a temp file
try {
using (var response = wr.GetResponse()) {
using (var inStream = response.GetResponseStream()) {
using (var reader = new StreamReader(inStream)) {
var responseString = reader.ReadToEnd();
// Track the API call
var eventargs = new AvaTaxCallEventArgs() { Code = ((HttpWebResponse)response).StatusCode, Duration = null, HttpVerb = wr.Method, RequestBody = jsonPayload, ResponseString = responseString, RequestUri = new Uri(path) };
OnCallCompleted(eventargs);
// Here's the results
return responseString;
}
}
}
// Catch a web exception
} catch (WebException webex) {
HttpWebResponse httpWebResponse = webex.Response as HttpWebResponse;
if (httpWebResponse != null) {
using (Stream stream = httpWebResponse.GetResponseStream()) {
using (StreamReader reader = new StreamReader(stream)) {
var errString = reader.ReadToEnd();
// Track the API call
var statusCode = ((HttpWebResponse)httpWebResponse).StatusCode;
var eventargs = new AvaTaxCallEventArgs() { Code = statusCode, Duration = null, HttpVerb = wr.Method, RequestBody = jsonPayload, ResponseString = errString, RequestUri = new Uri(path) };
OnCallCompleted(eventargs);
// Here's the results
var err = DeserializeErrorResult(errString, statusCode);
throw new AvaTaxError(err, httpWebResponse.StatusCode);
}
}
}
// If we can't parse it as an AvaTax error, just throw
throw webex;
}
}
19
Source : App.xaml.cs
with MIT License
from automuteus
with MIT License
from automuteus
public void PlaySound(string URL)
{
try
{
var req = WebRequest.Create(URL);
using Stream stream = req.GetResponse().GetResponseStream();
var myNewSound = new SoundPlayer(stream);
myNewSound.Load();
myNewSound.Play();
}
catch (Exception errrr)
{
Console.WriteLine("Minor error");
}
}
19
Source : AvaTaxClient.cs
with Apache License 2.0
from avadev
with Apache License 2.0
from avadev
private FileResult RestCallFile(string verb, AvaTaxPath relativePath, object content = null)
{
string path = CombinePath(_envUri.ToString(), relativePath.ToString());
string jsonPayload = null;
// Use HttpWebRequest so we can get a decent response
var wr = (HttpWebRequest)WebRequest.Create(path);
wr.Proxy = null;
wr.Timeout = 1200000;
// Add headers
foreach (var key in _clientHeaders.Keys)
{
wr.Headers.Add(key, _clientHeaders[key]);
}
// Convert the name-value pairs into a byte array
wr.Method = verb;
if (content != null) {
wr.ContentType = Constants.JSON_MIME_TYPE;
wr.ServicePoint.Expect100Continue = false;
// Encode the payload
jsonPayload = JsonConvert.SerializeObject(content, SerializerSettings);
var encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(jsonPayload);
wr.ContentLength = data.Length;
// Call the server
using (var s = wr.GetRequestStream()) {
s.Write(data, 0, data.Length);
s.Close();
}
}
// Transmit, and get back the response, save it to a temp file
try {
using (var response = wr.GetResponse()) {
using (var inStream = response.GetResponseStream()) {
const int BUFFER_SIZE = 1024;
var chunks = new List<byte>();
var totalBytes = 0;
var bytesRead = 0;
do
{
var buffer = new byte[BUFFER_SIZE];
bytesRead = inStream.Read(buffer, 0, BUFFER_SIZE);
if (bytesRead == BUFFER_SIZE) {
chunks.AddRange(buffer);
} else {
for (int i = 0; i < bytesRead; i++) {
chunks.Add(buffer[i]);
}
}
totalBytes += bytesRead;
} while (bytesRead > 0);
if(totalBytes <= 0) {
throw new IOException("Response contained no data");
}
// Here's your file result
var fr = new FileResult()
{
ContentType = response.Headers["Content-Type"].ToString(),
Filename = GetDispositionFilename(response.Headers["Content-Disposition"].ToString()),
Data = chunks.ToArray()
};
// Track the API call
var eventargs = new AvaTaxCallEventArgs() { Code = ((HttpWebResponse)response).StatusCode, Duration = null, HttpVerb = wr.Method, RequestBody = jsonPayload, ResponseBody = fr.Data, RequestUri = new Uri(path) };
OnCallCompleted(eventargs);
return fr;
}
}
// Catch a web exception
} catch (WebException webex) {
HttpWebResponse httpWebResponse = webex.Response as HttpWebResponse;
if (httpWebResponse != null) {
using (Stream stream = httpWebResponse.GetResponseStream()) {
using (StreamReader reader = new StreamReader(stream)) {
var errString = reader.ReadToEnd();
// Track the API call
var statusCode = ((HttpWebResponse)httpWebResponse).StatusCode;
var eventargs = new AvaTaxCallEventArgs() { Code = statusCode, Duration = null, HttpVerb = wr.Method, RequestBody = jsonPayload, ResponseString = errString, RequestUri = new Uri(path) };
OnCallCompleted(eventargs);
// Preplaced on the error
var err = DeserializeErrorResult(errString, statusCode);
throw new AvaTaxError(err, httpWebResponse.StatusCode);
}
}
}
// If we can't parse it as an AvaTax error, just throw
throw webex;
}
}
19
Source : App.cs
with GNU General Public License v3.0
from Avinch
with GNU General Public License v3.0
from Avinch
public static string GetAppName(int id)
{
string appName = "Unknown App";
string requestUrl = string.Format(CultureInfo.InvariantCulture,
"https://store.steampowered.com/api/appdetails?appids={0}", id);
var requestContents = string.Empty;
const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;
var webRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
webRequest.Method = "GET";
WebResponse response = null;
try
{
response = (HttpWebResponse)webRequest.GetResponse();
}
catch (System.Net.WebException ex)
{
Logger.Instance.Error("Failed to retrieve app name, defaulting to Unknown App");
Logger.Instance.Exception(ex);
return appName;
}
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
requestContents = streamReader.ReadToEnd();
}
try
{
dynamic jsonContents = JObject.Parse(requestContents);
appName = jsonContents[id.ToString()]["data"]["name"];
}
catch (JsonReaderException jsonEx)
{
Logger.Instance.Error("Failed to read app name");
Logger.Instance.Exception(jsonEx);
}
catch (Exception ex)
{
Logger.Instance.Exception(ex);
}
return appName;
}
19
Source : API.cs
with MIT License
from AyrA
with MIT License
from AyrA
public static byte[] Preview(Guid MapId)
{
if (MapId == Guid.Empty)
{
throw new ArgumentNullException(nameof(MapId));
}
var Request = WebRequest.CreateHttp(API_PREVIEW.Replace(API_MAP_ID_PLACEHOLDER, MapId.ToString()));
try
{
using (var Res = Request.GetResponse())
{
using (var MS = new MemoryStream())
{
using (var S = Res.GetResponseStream())
{
S.CopyTo(MS);
}
return MS.ToArray();
}
}
}
catch
{
return null;
}
}
19
Source : API.cs
with MIT License
from AyrA
with MIT License
from AyrA
public static bool Download(Guid MapId, Stream Output)
{
if (Output == null)
{
throw new ArgumentNullException(nameof(Output));
}
if (MapId == Guid.Empty)
{
throw new ArgumentNullException(nameof(MapId));
}
if (!Output.CanWrite)
{
throw new ArgumentException("Stream is not writable", nameof(Output));
}
var Request = WebRequest.CreateHttp(API_DOWNLOAD.Replace(API_MAP_ID_PLACEHOLDER, MapId.ToString()));
//Automatically decompress the data. If not available in your language, use regular gzip decompression.
Request.AutomaticDecompression = DecompressionMethods.GZip;
try
{
using (var Res = Request.GetResponse())
{
using (var S = Res.GetResponseStream())
{
S.CopyTo(Output);
}
}
}
catch (Exception ex)
{
SatisfactorySaveEditor.Log.Write("API: Unable to download the map");
SatisfactorySaveEditor.Log.Write(ex);
return false;
}
return true;
}
19
Source : API.cs
with MIT License
from AyrA
with MIT License
from AyrA
public static InfoResponse Info()
{
var R = Req("info");
try
{
using (var Res = R.GetResponse())
{
using (var SR = new StreamReader(Res.GetResponseStream()))
{
return SR.ReadToEnd().FromXml<InfoResponse>();
}
}
}
catch (Exception ex)
{
SatisfactorySaveEditor.Log.Write("API: Unable to download the map");
SatisfactorySaveEditor.Log.Write(ex);
return new InfoResponse()
{
success = false,
msg = ex.Message
};
}
}
See More Examples