Here are the examples of the csharp api System.Convert.ToBase64String(byte[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3495 Examples
19
View Source File : Encryption.cs
License : GNU General Public License v3.0
Project Creator : 00000vish
License : GNU General Public License v3.0
Project Creator : 00000vish
public static string Encrypt<T>(string value, string preplacedword)
where T : SymmetricAlgorithm, new()
{
byte[] vectorBytes = ASCIIEncoding.ASCII.GetBytes(_vector);
byte[] saltBytes = ASCIIEncoding.ASCII.GetBytes(_salt);
byte[] valueBytes = UTF8Encoding.UTF8.GetBytes(value);
byte[] encrypted;
using (T cipher = new T())
{
PreplacedwordDeriveBytes _preplacedwordBytes =
new PreplacedwordDeriveBytes(preplacedword, saltBytes, _hash, _iterations);
byte[] keyBytes = _preplacedwordBytes.GetBytes(_keySize / 8);
cipher.Mode = CipherMode.CBC;
using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes))
{
using (MemoryStream to = new MemoryStream())
{
using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write))
{
writer.Write(valueBytes, 0, valueBytes.Length);
writer.FlushFinalBlock();
encrypted = to.ToArray();
}
}
}
cipher.Clear();
}
return Convert.ToBase64String(encrypted);
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen
License : GNU General Public License v3.0
Project Creator : 0xthirteen
static void GetFileContent(string paylocation, string droploc, string fname, string dtype)
{
bool uricheck = Uri.IsWellFormedUriString(paylocation, UriKind.RelativeOrAbsolute);
if (paylocation == "local")
{
String plfile = "LOADLOADLOAD";
if(dtype == "flat")
{
String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
vbsp = vbsp.Insert(0, finalpay);
}
else if (dtype == "nonflat")
{
datavals = plfile;
}
}
else
{
if (uricheck)
{
try
{
WebClient webcl = new WebClient();
//May want to change this
webcl.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
byte[] filedata = webcl.DownloadData(paylocation);
string plfile = Convert.ToBase64String(filedata);
if (dtype == "flat")
{
String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
vbsp = vbsp.Insert(0, finalpay);
}
else if (dtype == "nonflat")
{
datavals = plfile;
}
}
catch (WebException)
{
Console.WriteLine("[X] URL doesnt exist");
return;
}
}
else
{
try
{
Byte[] plbytes = File.ReadAllBytes(paylocation);
String plfile = Convert.ToBase64String(plbytes);
if(dtype == "flat")
{
String finalpay = String.Format("Dim pLoad, fnames, droploc\npLoad =\"{0}\"\nfnames = \"{1}\"\ndroploc = \"{2}\"\n", plfile, fname, droploc);
vbsp = vbsp.Insert(0, finalpay);
}
else if (dtype == "nonflat")
{
datavals = plfile;
}
}
catch (IOException)
{
Console.WriteLine("[X] File doesnt exist");
return;
}
}
}
}
19
View Source File : CacheBuilder.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios
License : GNU General Public License v3.0
Project Creator : 1330-Studios
public static void Build() {
ResourceSet resourceSet = BloonSprites.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry v in resourceSet) {
if (v.Key is string id && v.Value is Byte[] bytes) {
built.Add(id, Convert.ToBase64String(bytes));
}
}
}
19
View Source File : DefaultVerifyCodeProvider.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public async Task<VerifyCodeModel> Create()
{
var code = _stringHelper.GenerateRandomNumber();
var bytes = DrawVerifyCode(code);
var id = Guid.NewGuid().ToString();
await _cacheHandler.Set(_cacheKeys.VerifyCode(id), code, 5);
return new VerifyCodeModel
{
Id = id,
Base64 = "data:image/png;base64," + Convert.ToBase64String(bytes)
};
}
19
View Source File : StringExtensions.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public static string ToBase64(this byte[] bytes)
{
if (bytes == null)
return null;
return Convert.ToBase64String(bytes);
}
19
View Source File : Encrypter.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static string Encrypt(string key, string data)
{
Encoding unicode = Encoding.Unicode;
return Convert.ToBase64String(Encrypt(unicode.GetBytes(key), unicode.GetBytes(data)));
}
19
View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
public static string Base64Encode(string plainText)
{
try
{
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(plainTextBytes);
}
catch (Exception ex)
{
SaveLog("Base64Encode", ex);
return string.Empty;
}
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
static void Main(string[] args)
{
try
{
logo();
// https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10
var arguments = new Dictionary<string, string>();
foreach (var argument in args)
{
var idx = argument.IndexOf(':');
if (idx > 0)
arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
else
arguments[argument] = string.Empty;
}
WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
if (principal.IsInRole(WindowsBuiltInRole.Administrator))
{
Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
}
else
{
Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
}
if (arguments.Count == 0)
{
PrintError("[-] No arguments specified. Please refer the help section for more details.");
help();
}
else if (arguments.ContainsKey("/help"))
{
help();
}
else if (arguments.Count < 3)
{
PrintError("[-] Some arguments are missing. Please refer the help section for more details.");
help();
}
else if (arguments.Count >= 3)
{
string key = "SuperStrongKey";
string shellcode = null;
byte[] rawshellcode = new byte[] { };
if (arguments.ContainsKey("/path") && System.IO.File.Exists(arguments["/path"]))
{
if (arguments["/f"] == "raw")
{
rawshellcode = System.IO.File.ReadAllBytes(arguments["/path"]);
}
else
{
shellcode = System.IO.File.ReadAllText(arguments["/path"]);
}
}
else if (arguments.ContainsKey("/url"))
{
if (arguments["/f"] == "raw")
{
rawshellcode = GetRawShellcode(arguments["/url"]);
}
else
{
shellcode = GetShellcode(arguments["/url"]);
}
}
if (shellcode != null || rawshellcode.Length > 0)
{
byte[] buf = new byte[] { };
if (arguments.ContainsKey("/key"))
{
key = (arguments["/key"]);
}
PrintInfo($"[!] Shellcode will be encrypted using '{key}' key");
if (arguments["/enc"] == "xor")
{
byte[] xorshellcode = new byte[] { };
if (arguments["/f"] == "base64")
{
buf = Convert.FromBase64String(shellcode);
xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
PrintSuccess("[+] Shellcode encrypted successfully.");
//Console.WriteLine(Convert.ToBase64String(xorshellcode));
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(xorshellcode));
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(xorshellcode));
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else if (arguments["/f"] == "hex")
{
buf = StringToByteArray(shellcode);
xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
PrintSuccess("[+] Shellcode encrypted successfully.");
//Console.WriteLine(ByteArrayToString(xorshellcode));
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(xorshellcode));
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllText("output.bin", ByteArrayToString(xorshellcode));
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else if (arguments["/f"] == "c")
{
buf = convertfromc(shellcode);
xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
StringBuilder newshellcode = new StringBuilder();
for (int i = 0; i < xorshellcode.Length; i++)
{
newshellcode.Append("\\x");
newshellcode.AppendFormat("{0:x2}", xorshellcode[i]);
}
PrintSuccess("[+] Shellcode encrypted successfully.");
//Console.WriteLine(newshellcode);
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else if (arguments["/f"] == "raw")
{
xorshellcode = XOR(rawshellcode, Encoding.ASCII.GetBytes(key));
PrintSuccess("[+] Shellcode encrypted successfully.");
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllBytes(arguments["/o"], xorshellcode);
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllBytes("output.bin", xorshellcode);
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else
{
PrintError("[-] Please specify correct shellcode format.");
}
}
else if (arguments["/enc"] == "aes")
{
byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(key);
preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
byte[] bytesEncrypted = new byte[] { };
if (arguments["/f"] == "base64")
{
buf = Convert.FromBase64String(shellcode);
bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
PrintSuccess("[+] Shellcode encrypted successfully.");
//Console.WriteLine(Convert.ToBase64String(bytesEncrypted));
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(bytesEncrypted));
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(bytesEncrypted));
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else if (arguments["/f"] == "hex")
{
buf = StringToByteArray(shellcode);
bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
PrintSuccess("[+] Shellcode encrypted successfully.");
//Console.WriteLine(ByteArrayToString(bytesEncrypted));
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(bytesEncrypted));
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllText("output.bin", ByteArrayToString(bytesEncrypted));
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else if (arguments["/f"] == "c")
{
buf = convertfromc(shellcode);
bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
StringBuilder newshellcode = new StringBuilder();
for (int i = 0; i < bytesEncrypted.Length; i++)
{
newshellcode.Append("\\x");
newshellcode.AppendFormat("{0:x2}", bytesEncrypted[i]);
}
PrintSuccess("[+] Shellcode encrypted successfully.");
//Console.WriteLine(newshellcode);
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else if (arguments["/f"] == "raw")
{
bytesEncrypted = AES_Encrypt(rawshellcode, preplacedwordBytes);
if (arguments.ContainsKey("/o"))
{
System.IO.File.WriteAllBytes(arguments["/o"], bytesEncrypted);
PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
}
else
{
System.IO.File.WriteAllBytes("output.bin", bytesEncrypted);
PrintSuccess($"[+] Output saved in 'output.bin' file.");
}
}
else
{
PrintError("[-] Please specify correct shellcode format.");
}
}
else
{
PrintError("[-] Please specify correct encryption type.");
}
}
else
{
PrintError("[-] Please check the specified file path or the URL.");
}
}
else
{
PrintError("[-] File doesn't exists. Please check the specified file path.");
}
}
catch (Exception ex)
{
PrintError(ex.Message);
}
}
19
View Source File : BaseApiClient.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
protected string GetSignature(string signatureBaseString)
{
byte[] key = Encoding.ASCII.GetBytes(string.Concat(Uri.EscapeDataString(ConsumerSecret), "&", Uri.EscapeDataString(AccessTokenSecret)));
string signature;
using (HMACSHA1 hasher = new HMACSHA1(key))
{
signature = Convert.ToBase64String(hasher.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString)));
}
return signature;
}
19
View Source File : WebhookServer.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
private string CRC(string consumerSecret, string crcToken)
{
byte[] consumerSecretBytes = Encoding.UTF8.GetBytes(consumerSecret);
byte[] crcTokenBytes = Encoding.UTF8.GetBytes(crcToken);
HMACSHA256 hmacSHA256Alog = new HMACSHA256(consumerSecretBytes);
byte[] computedHash = hmacSHA256Alog.ComputeHash(crcTokenBytes);
return "{\n" +
$"\"response_token\":\"sha256={Convert.ToBase64String(computedHash)}\"" +
"\n}";
}
19
View Source File : WebhookServer.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
private bool VerifySignature(string signature, byte[] body)
{
using (var crypto = new HMACSHA256(Encoding.UTF8.GetBytes(ConsumerSecret)))
{
var hash = Convert.ToBase64String(crypto.ComputeHash(body));
return hash == signature.Replace("sha256=", "");
}
}
19
View Source File : LyricsFetcher.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public static string GetLyricsHash(this IBeatmapLevel level)
{
string id = string.Join(", ", level.songName, level.songAuthorName, level.songSubName, level.beatsPerMinute, level.songDuration, level.songTimeOffset);
return Convert.ToBase64String(Encoding.UTF8.GetBytes(id));
}
19
View Source File : SimpleJSON.cs
License : MIT License
Project Creator : 734843327
License : MIT License
Project Creator : 734843327
public string SaveToBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
19
View Source File : RSAEncode.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
{
byte[] PlainTextBArray;
byte[] CypherTextBArray;
string Result;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPublicKey);
PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString);
CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
Result = Convert.ToBase64String(CypherTextBArray);
return Result;
}
19
View Source File : RSAEncode.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
{
byte[] CypherTextBArray;
string Result;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPublicKey);
CypherTextBArray = rsa.Encrypt(EncryptString, false);
Result = Convert.ToBase64String(CypherTextBArray);
return Result;
}
19
View Source File : RSAEncode.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public bool GetHash(string m_strSource, ref string strHashData)
{
//从字符串中取得Hash描述
byte[] Buffer;
byte[] HashData;
HashAlgorithm MD5 = HashAlgorithm.Create("MD5");
Buffer = Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
HashData = MD5.ComputeHash(Buffer);
strHashData = Convert.ToBase64String(HashData);
return true;
}
19
View Source File : RSAEncode.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public bool GetHash(FileStream objFile, ref string strHashData)
{
//从文件中取得Hash描述
byte[] HashData;
HashAlgorithm MD5 = HashAlgorithm.Create("MD5");
HashData = MD5.ComputeHash(objFile);
objFile.Close();
strHashData = Convert.ToBase64String(HashData);
return true;
}
19
View Source File : RSAEncode.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData)
{
byte[] EncryptedSignatureData;
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.FromXmlString(p_strKeyPrivate);
RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(RSA);
//设置签名的算法为MD5
RSAFormatter.SetHashAlgorithm("MD5");
//执行签名
EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
return true;
}
19
View Source File : RSAEncode.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData)
{
byte[] HashbyteSignature;
byte[] EncryptedSignatureData;
HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.FromXmlString(p_strKeyPrivate);
RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(RSA);
//设置签名的算法为MD5
RSAFormatter.SetHashAlgorithm("MD5");
//执行签名
EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
return true;
}
19
View Source File : Base64.cs
License : MIT License
Project Creator : 944095635
License : MIT License
Project Creator : 944095635
public static string EncodeBase64(Encoding encode, string source)
{
byte[] bytes = encode.GetBytes(source);
try
{
source = Convert.ToBase64String(bytes);
}
catch
{
}
return source;
}
19
View Source File : EncryptionUtility.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public static string EncodeFileName(string text, string salt = "")
{
var textBytes = Encoding.UTF8.GetBytes(text);
var res = Convert.ToBase64String(textBytes);
return res.ToLower();
}
19
View Source File : EncryptionUtility.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public static byte[] GenerateIV(string preplaced)
{
var textBytes = Encoding.ASCII.GetBytes(preplaced+"_umldata");
var res = Convert.ToBase64String(textBytes);
return Encoding.ASCII.GetBytes(res.Substring(0,8));
}
19
View Source File : EncryptionUtility.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public static string GenerateRandomPW(int length = 16)
{
byte[] b = new byte[length];
RandomNumberGenerator rg = RandomNumberGenerator.Create();
rg.GetBytes(b);
return Convert.ToBase64String(b);
}
19
View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private string DoMethod(NameValueCollection jParams)
{
const int RequestTimeoutMilliseconds = 2*1000; // 2 sec
string tempResult = "";
try
{
lock (m_tonceLock)
{
//get tonce
TimeSpan timeSpan = DateTime.UtcNow - genesis;
long milliSeconds = Convert.ToInt64(timeSpan.TotalMilliseconds*1000);
jParams[pTonce] = Convert.ToString(milliSeconds, CultureInfo.InvariantCulture);
//mock json request id
jParams[pId] = jsonRequestID.Next().ToString(CultureInfo.InvariantCulture);
//build http head
string paramsHash = GetHMACSHA1Hash(jParams);
string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes(accessKey + ':' + paramsHash));
string postData = "{\"method\": \"" + jParams[pMethod] + "\", \"params\": [" + jParams[pParams] + "], \"id\": " +
jParams[pId] + "}";
//get webrequest,respawn new object per call for multiple connections
var webRequest = (HttpWebRequest) WebRequest.Create(url);
webRequest.Timeout = RequestTimeoutMilliseconds;
var bytes = Encoding.ASCII.GetBytes(postData);
webRequest.Method = jParams[pRequestMethod];
webRequest.ContentType = "application/json-rpc";
webRequest.ContentLength = bytes.Length;
webRequest.Headers["Authorization"] = "Basic " + base64String;
webRequest.Headers["Json-Rpc-Tonce"] = jParams[pTonce];
// Send the json authentication post request
using (var dataStream = webRequest.GetRequestStream())
{
dataStream.Write(bytes, 0, bytes.Length);
}
// Get authentication response
using (var response = webRequest.GetResponse())
{
using (var stream = response.GetResponseStream())
{
// ReSharper disable once replacedignNullToNotNullAttribute
using (var reader = new StreamReader(stream))
{
tempResult = reader.ReadToEnd();
}
}
}
}
}
catch (WebException ex)
{
throw new BTCChinaException(jParams[pMethod], jParams[pId], ex.Message, ex);
}
//there are two kinds of API response, result or error.
if (tempResult.IndexOf("result", StringComparison.Ordinal) < 0)
{
throw new BTCChinaException(jParams[pMethod], jParams[pId], "API error:\n" + tempResult);
}
//compare response id with request id and remove it from result
try
{
int cutoff = tempResult.LastIndexOf(':') + 2;//"id":"1"} so (last index of ':')+2=length of cutoff=start of id-string
string idString = tempResult.Substring(cutoff, tempResult.Length - cutoff - 2);//2=last "}
if (idString != jParams[pId])
{
throw new BTCChinaException(jParams[pMethod], jParams[pId], "JSON-request id is not equal with JSON-response id.");
}
else
{
//remove json request id from response json string
int fromComma = tempResult.LastIndexOf(',');
int toLastBrace = tempResult.Length - 1;
tempResult = tempResult.Remove(fromComma, toLastBrace - fromComma);
}
}
catch (ArgumentOutOfRangeException ex)
{
throw new BTCChinaException(jParams[pMethod], jParams[pId], "Argument out of range in parsing JSON response id:" + ex.Message, ex);
}
return tempResult;
}
19
View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static List<string> BuildBase64PayloadMacros(byte[] shellcode)
{
List<string> base64Strings = new List<string>();
//Base64 expansion is 4/3, and we have 252 bytes to spend, so we can have 189 bytes / cell
//As an added bonus, 189 is always divisible by 3, so we won't have == padding.
int maxBytesPerCell = 189;
for (int offset = 0; offset < shellcode.Length; offset += maxBytesPerCell)
{
byte[] guidShellcode;
if (shellcode.Length - offset < maxBytesPerCell)
{
guidShellcode = shellcode.Skip(offset).ToArray();
}
else
{
guidShellcode = shellcode.Skip(offset).Take(maxBytesPerCell).ToArray();
}
base64Strings.Add(Convert.ToBase64String(guidShellcode));
}
base64Strings.Add("END");
return base64Strings;
}
19
View Source File : BitfinexApi.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private string GetRestResponse(BitfinexPostBase obj)
{
HttpRequestMessage request;
{
var jsonObj = JsonConvert.SerializeObject(obj);
var payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonObj));
request = new HttpRequestMessage(HttpMethod.Post, obj.Request);
request.Headers.Add(ApiBfxKey, ApiKey);
request.Headers.Add(ApiBfxPayload, payload);
request.Headers.Add(ApiBfxSig, GetHexHashSignature(payload));
}
var responseMessage = WebApi.Client.SendAsync(request).Result;
var response = responseMessage.Content.ReadreplacedtringAsync().Result;
CheckResultCode(responseMessage.StatusCode, response);
return response;
}
19
View Source File : FileChecker.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static string GetCheckSum(string data)
{
var sha = SHA512.Create();
return Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(data)));
}
19
View Source File : Crypto.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public string ToBase64(string source)
{
var sourceByte = Encoding.UTF8.GetBytes(source);
return Convert.ToBase64String(sourceByte);
}
19
View Source File : Crypto.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public string Encrypt(string message)
{
return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(message)));
}
19
View Source File : Crypto.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public string SymmetricEncrypt(string message)
{
return Convert.ToBase64String(SymmetricEncrypt(Encoding.UTF8.GetBytes(message), SymmetricKey));
}
19
View Source File : GZip.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static string Zip(string str)
{
return Convert.ToBase64String(ZipByte(str));
}
19
View Source File : FdbConverters.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
private static void RegisterDefaultConverters()
{
//TODO: there is too much generic type combinations! need to refactor this ...
RegisterUnsafe<bool, Slice>((value) => Slice.FromByte(value ? (byte)1 : default(byte)));
RegisterUnsafe<bool, byte[]>((value) => Slice.FromByte(value ? (byte)1 : default(byte)).GetBytes());
RegisterUnsafe<bool, string>((value) => value ? "true" : "false");
RegisterUnsafe<bool, sbyte>((value) => value ? (sbyte)1 : default(sbyte));
RegisterUnsafe<bool, byte>((value) => value ? (byte)1 : default(byte));
RegisterUnsafe<bool, short>((value) => value ? (short)1 : default(short));
RegisterUnsafe<bool, ushort>((value) => value ? (ushort)1 : default(ushort));
RegisterUnsafe<bool, int>((value) => value ? 1 : default(int));
RegisterUnsafe<bool, uint>((value) => value ? 1U : default(uint));
RegisterUnsafe<bool, long>((value) => value ? 1L : default(long));
RegisterUnsafe<bool, ulong>((value) => value ? 1UL : default(ulong));
RegisterUnsafe<bool, double>((value) => value ? 0.0d : 1.0d);
RegisterUnsafe<bool, float>((value) => value ? 0.0f : 1.0f);
RegisterUnsafe<int, Slice>((value) => Slice.FromInt32(value));
RegisterUnsafe<int, byte[]>((value) => Slice.FromInt32(value).GetBytes());
RegisterUnsafe<int, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<int, bool>((value) => value != 0);
RegisterUnsafe<int, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<int, byte>((value) => checked((byte)value));
RegisterUnsafe<int, short>((value) => checked((short)value));
RegisterUnsafe<int, ushort>((value) => checked((ushort)value));
RegisterUnsafe<int, uint>((value) => (uint)value);
RegisterUnsafe<int, long>((value) => value);
RegisterUnsafe<int, ulong>((value) => (ulong)value);
RegisterUnsafe<int, double>((value) => value);
RegisterUnsafe<int, float>((value) => checked((float)value));
RegisterUnsafe<int, FdbTupleAlias>((value) => (FdbTupleAlias)value);
RegisterUnsafe<uint, Slice>((value) => Slice.FromUInt64(value));
RegisterUnsafe<uint, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
RegisterUnsafe<uint, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<uint, bool>((value) => value != 0);
RegisterUnsafe<uint, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<uint, byte>((value) => checked((byte)value));
RegisterUnsafe<uint, short>((value) => checked((short)value));
RegisterUnsafe<uint, ushort>((value) => checked((ushort)value));
RegisterUnsafe<uint, int>((value) => (int)value);
RegisterUnsafe<uint, long>((value) => value);
RegisterUnsafe<uint, ulong>((value) => value);
RegisterUnsafe<uint, double>((value) => value);
RegisterUnsafe<uint, float>((value) => checked((float)value));
RegisterUnsafe<long, Slice>((value) => Slice.FromInt64(value));
RegisterUnsafe<long, byte[]>((value) => Slice.FromInt64(value).GetBytes());
RegisterUnsafe<long, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<long, bool>((value) => value != 0);
RegisterUnsafe<long, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<long, byte>((value) => checked((byte)value));
RegisterUnsafe<long, short>((value) => checked((short)value));
RegisterUnsafe<long, ushort>((value) => checked((ushort)value));
RegisterUnsafe<long, int>((value) => checked((int)value));
RegisterUnsafe<long, uint>((value) => (uint)value);
RegisterUnsafe<long, ulong>((value) => (ulong)value);
RegisterUnsafe<long, double>((value) => checked((double)value));
RegisterUnsafe<long, float>((value) => checked((float)value));
RegisterUnsafe<long, TimeSpan>((value) => TimeSpan.FromTicks(value));
RegisterUnsafe<long, Uuid64>((value) => new Uuid64(value));
RegisterUnsafe<long, System.Net.IPAddress>((value) => new System.Net.IPAddress(value));
RegisterUnsafe<ulong, Slice>((value) => Slice.FromUInt64(value));
RegisterUnsafe<ulong, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
RegisterUnsafe<ulong, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<ulong, bool>((value) => value != 0);
RegisterUnsafe<ulong, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<ulong, byte>((value) => checked((byte)value));
RegisterUnsafe<ulong, short>((value) => checked((short)value));
RegisterUnsafe<ulong, ushort>((value) => checked((ushort)value));
RegisterUnsafe<ulong, int>((value) => checked((int)value));
RegisterUnsafe<ulong, uint>((value) => checked((uint)value));
RegisterUnsafe<ulong, long>((value) => checked((long)value));
RegisterUnsafe<ulong, double>((value) => checked((double)value));
RegisterUnsafe<ulong, float>((value) => checked((float)value));
RegisterUnsafe<ulong, Uuid64>((value) => new Uuid64(value));
RegisterUnsafe<ulong, TimeSpan>((value) => TimeSpan.FromTicks(checked((long)value)));
RegisterUnsafe<short, Slice>((value) => Slice.FromInt32(value));
RegisterUnsafe<short, byte[]>((value) => Slice.FromInt32(value).GetBytes());
RegisterUnsafe<short, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<short, bool>((value) => value != 0);
RegisterUnsafe<short, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<short, byte>((value) => checked((byte)value));
RegisterUnsafe<short, ushort>((value) => checked((ushort)value));
RegisterUnsafe<short, int>((value) => value);
RegisterUnsafe<short, uint>((value) => checked((uint)value));
RegisterUnsafe<short, long>((value) => value);
RegisterUnsafe<short, ulong>((value) => checked((ulong)value));
RegisterUnsafe<short, double>((value) => value);
RegisterUnsafe<short, float>((value) => value);
RegisterUnsafe<short, FdbTupleAlias>((value) => (FdbTupleAlias)value);
RegisterUnsafe<ushort, Slice>((value) => Slice.FromUInt64(value));
RegisterUnsafe<ushort, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
RegisterUnsafe<ushort, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<ushort, bool>((value) => value != 0);
RegisterUnsafe<ushort, byte>((value) => checked((byte)value));
RegisterUnsafe<ushort, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<ushort, short>((value) => checked((short)value));
RegisterUnsafe<ushort, int>((value) => value);
RegisterUnsafe<ushort, uint>((value) => value);
RegisterUnsafe<ushort, long>((value) => value);
RegisterUnsafe<ushort, ulong>((value) => value);
RegisterUnsafe<ushort, double>((value) => value);
RegisterUnsafe<ushort, float>((value) => value);
RegisterUnsafe<byte, Slice>((value) => Slice.FromInt32(value));
RegisterUnsafe<byte, byte[]>((value) => Slice.FromInt32(value).GetBytes());
RegisterUnsafe<byte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<byte, bool>((value) => value != 0);
RegisterUnsafe<byte, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<byte, short>((value) => value);
RegisterUnsafe<byte, ushort>((value) => value);
RegisterUnsafe<byte, int>((value) => value);
RegisterUnsafe<byte, uint>((value) => value);
RegisterUnsafe<byte, long>((value) => value);
RegisterUnsafe<byte, ulong>((value) => value);
RegisterUnsafe<byte, double>((value) => value);
RegisterUnsafe<byte, float>((value) => value);
RegisterUnsafe<byte, FdbTupleAlias>((value) => (FdbTupleAlias)value);
RegisterUnsafe<sbyte, Slice>((value) => Slice.FromInt64(value));
RegisterUnsafe<sbyte, byte[]>((value) => Slice.FromInt64(value).GetBytes());
RegisterUnsafe<sbyte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<sbyte, bool>((value) => value != 0);
RegisterUnsafe<sbyte, byte>((value) => checked((byte)value));
RegisterUnsafe<sbyte, short>((value) => value);
RegisterUnsafe<sbyte, ushort>((value) => checked((ushort)value));
RegisterUnsafe<sbyte, int>((value) => value);
RegisterUnsafe<sbyte, uint>((value) => checked((uint)value));
RegisterUnsafe<sbyte, long>((value) => value);
RegisterUnsafe<sbyte, ulong>((value) => checked((ulong)value));
RegisterUnsafe<sbyte, double>((value) => value);
RegisterUnsafe<sbyte, float>((value) => value);
RegisterUnsafe<float, Slice>((value) => Slice.FromSingle(value));
RegisterUnsafe<float, byte[]>((value) => Slice.FromSingle(value).GetBytes());
RegisterUnsafe<float, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
RegisterUnsafe<float, bool>((value) => !(value == 0f || float.IsNaN(value)));
RegisterUnsafe<float, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<float, byte>((value) => checked((byte)value));
RegisterUnsafe<float, short>((value) => checked((short)value));
RegisterUnsafe<float, ushort>((value) => checked((ushort)value));
RegisterUnsafe<float, int>((value) => checked((int)value));
RegisterUnsafe<float, uint>((value) => (uint)value);
RegisterUnsafe<float, long>((value) => checked((long)value));
RegisterUnsafe<float, ulong>((value) => (ulong)value);
RegisterUnsafe<float, double>((value) => value);
RegisterUnsafe<double, Slice>((value) => Slice.FromDouble(value));
RegisterUnsafe<double, byte[]>((value) => Slice.FromDouble(value).GetBytes());
RegisterUnsafe<double, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
RegisterUnsafe<double, bool>((value) => !(value == 0d || double.IsNaN(value)));
RegisterUnsafe<double, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<double, byte>((value) => checked((byte)value));
RegisterUnsafe<double, short>((value) => checked((short)value));
RegisterUnsafe<double, ushort>((value) => checked((ushort)value));
RegisterUnsafe<double, int>((value) => checked((int)value));
RegisterUnsafe<double, uint>((value) => (uint)value);
RegisterUnsafe<double, long>((value) => checked((long)value));
RegisterUnsafe<double, ulong>((value) => (ulong)value);
RegisterUnsafe<double, float>((value) => checked((float)value));
RegisterUnsafe<string, Slice>((value) => Slice.FromString(value));
RegisterUnsafe<string, byte[]>((value) => Slice.FromString(value).GetBytes());
RegisterUnsafe<string, bool>((value) => !string.IsNullOrEmpty(value));
RegisterUnsafe<string, sbyte>((value) => string.IsNullOrEmpty(value) ? default(sbyte) : SByte.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, byte>((value) => string.IsNullOrEmpty(value) ? default(byte) : Byte.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, short>((value) => string.IsNullOrEmpty(value) ? default(short) : Int16.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, ushort>((value) => string.IsNullOrEmpty(value) ? default(ushort) : UInt16.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, int>((value) => string.IsNullOrEmpty(value) ? default(int) : Int32.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, uint>((value) => string.IsNullOrEmpty(value) ? default(uint) : UInt32.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, long>((value) => string.IsNullOrEmpty(value) ? default(long) : Int64.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, ulong>((value) => string.IsNullOrEmpty(value) ? default(ulong) : UInt64.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, float>((value) => string.IsNullOrEmpty(value) ? default(float) : Single.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
RegisterUnsafe<string, double>((value) => string.IsNullOrEmpty(value) ? default(double) : Double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
RegisterUnsafe<string, Guid>((value) => string.IsNullOrEmpty(value) ? default(Guid) : Guid.Parse(value));
RegisterUnsafe<string, Uuid128>((value) => string.IsNullOrEmpty(value) ? default(Uuid128) : Uuid128.Parse(value));
RegisterUnsafe<string, Uuid64>((value) => string.IsNullOrEmpty(value) ? default(Uuid64) : Uuid64.Parse(value));
RegisterUnsafe<string, System.Net.IPAddress>((value) => string.IsNullOrEmpty(value) ? default(System.Net.IPAddress) : System.Net.IPAddress.Parse(value));
RegisterUnsafe<byte[], Slice>((value) => Slice.Create(value));
RegisterUnsafe<byte[], string>((value) => value == null ? default(string) : value.Length == 0 ? String.Empty : System.Convert.ToBase64String(value));
RegisterUnsafe<byte[], bool>((value) => value != null && value.Length > 0);
RegisterUnsafe<byte[], sbyte>((value) => value == null ? default(sbyte) : Slice.Create(value).ToSByte());
RegisterUnsafe<byte[], byte>((value) => value == null ? default(byte) : Slice.Create(value).ToByte());
RegisterUnsafe<byte[], short>((value) => value == null ? default(short) : Slice.Create(value).ToInt16());
RegisterUnsafe<byte[], ushort>((value) => value == null ? default(ushort) : Slice.Create(value).ToUInt16());
RegisterUnsafe<byte[], int>((value) => value == null ? 0 : Slice.Create(value).ToInt32());
RegisterUnsafe<byte[], uint>((value) => value == null ? 0U : Slice.Create(value).ToUInt32());
RegisterUnsafe<byte[], long>((value) => value == null ? 0L : Slice.Create(value).ToInt64());
RegisterUnsafe<byte[], ulong>((value) => value == null ? 0UL : Slice.Create(value).ToUInt64());
RegisterUnsafe<byte[], Guid>((value) => value == null || value.Length == 0 ? default(Guid) : new Uuid128(value).ToGuid());
RegisterUnsafe<byte[], Uuid128>((value) => value == null || value.Length == 0 ? default(Uuid128) : new Uuid128(value));
RegisterUnsafe<byte[], Uuid64>((value) => value == null || value.Length == 0 ? default(Uuid64) : new Uuid64(value));
RegisterUnsafe<byte[], TimeSpan>((value) => value == null ? TimeSpan.Zero : TimeSpan.FromTicks(Slice.Create(value).ToInt64()));
RegisterUnsafe<byte[], System.Net.IPAddress>((value) => value == null || value.Length == 0 ? default(System.Net.IPAddress) : new System.Net.IPAddress(value));
RegisterUnsafe<Guid, Slice>((value) => Slice.FromGuid(value));
RegisterUnsafe<Guid, byte[]>((value) => Slice.FromGuid(value).GetBytes());
RegisterUnsafe<Guid, string>((value) => value.ToString("D", null));
RegisterUnsafe<Guid, Uuid128>((value) => new Uuid128(value));
RegisterUnsafe<Guid, bool>((value) => value != Guid.Empty);
RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(new Uuid128(value).ToByteArray()));
RegisterUnsafe<Uuid128, Slice>((value) => value.ToSlice());
RegisterUnsafe<Uuid128, byte[]>((value) => value.ToByteArray());
RegisterUnsafe<Uuid128, string>((value) => value.ToString("D", null));
RegisterUnsafe<Uuid128, Guid>((value) => value.ToGuid());
RegisterUnsafe<Uuid128, bool>((value) => value != Uuid128.Empty);
RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(value.ToByteArray()));
RegisterUnsafe<Uuid64, Slice>((value) => value.ToSlice());
RegisterUnsafe<Uuid64, byte[]>((value) => value.ToByteArray());
RegisterUnsafe<Uuid64, string>((value) => value.ToString("D", null));
RegisterUnsafe<Uuid64, long>((value) => value.ToInt64());
RegisterUnsafe<Uuid64, ulong>((value) => value.ToUInt64());
RegisterUnsafe<Uuid64, bool>((value) => value.ToInt64() != 0L);
RegisterUnsafe<TimeSpan, Slice>((value) => Slice.FromInt64(value.Ticks));
RegisterUnsafe<TimeSpan, byte[]>((value) => Slice.FromInt64(value.Ticks).GetBytes());
RegisterUnsafe<TimeSpan, long>((value) => value.Ticks);
RegisterUnsafe<TimeSpan, ulong>((value) => checked((ulong)value.Ticks));
RegisterUnsafe<TimeSpan, double>((value) => value.TotalSeconds);
RegisterUnsafe<TimeSpan, bool>((value) => value == TimeSpan.Zero);
RegisterUnsafe<System.Net.IPAddress, Slice>((value) => value != null ? Slice.Create(value.GetAddressBytes()) : Slice.Nil);
RegisterUnsafe<System.Net.IPAddress, byte[]>((value) => value != null ? value.GetAddressBytes() : null);
RegisterUnsafe<System.Net.IPAddress, string>((value) => value != null ? value.ToString() : null);
RegisterUnsafe<FdbTupleAlias, byte>((value) => (byte)value);
RegisterUnsafe<FdbTupleAlias, int>((value) => (int)value);
RegisterUnsafe<FdbTupleAlias, Slice>((value) => Slice.FromByte((byte)value));
//REVIEW: this should go in the Tuples layer !
RegisterUnsafe<Slice, byte[]>((value) => value.GetBytes());
RegisterUnsafe<Slice, string>((value) => value.ToUnicode());
RegisterUnsafe<Slice, bool>((value) => value.ToBool());
RegisterUnsafe<Slice, sbyte>((value) => value.ToSByte());
RegisterUnsafe<Slice, byte>((value) => value.ToByte());
RegisterUnsafe<Slice, short>((value) => value.ToInt16());
RegisterUnsafe<Slice, ushort>((value) => value.ToUInt16());
RegisterUnsafe<Slice, int>((value) => value.ToInt32());
RegisterUnsafe<Slice, uint>((value) => value.ToUInt32());
RegisterUnsafe<Slice, long>((value) => value.ToInt64());
RegisterUnsafe<Slice, ulong>((value) => value.ToUInt64());
RegisterUnsafe<Slice, Guid>((value) => value.ToGuid());
RegisterUnsafe<Slice, Uuid128>((value) => value.ToUuid128());
RegisterUnsafe<Slice, Uuid64>((value) => value.ToUuid64());
RegisterUnsafe<Slice, TimeSpan>((value) => TimeSpan.FromTicks(value.ToInt64()));
RegisterUnsafe<Slice, FdbTupleAlias>((value) => (FdbTupleAlias)value.ToByte());
RegisterUnsafe<Slice, System.Net.IPAddress>((value) => !value.IsNullOrEmpty ? new System.Net.IPAddress(value.GetBytes()) : null);
}
19
View Source File : StringExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static string EncodeTo64(this string toEncode)
{
byte[] toEncodeAsBytes = Encoding.ASCII.GetBytes(toEncode);
return Convert.ToBase64String(toEncodeAsBytes);
}
19
View Source File : Rest.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static string GetBasicAuthentication(string username, string preplacedword)
{
return $"Basic {Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{username}:{preplacedword}"))}";
}
19
View Source File : GuidGenerator.cs
License : MIT License
Project Creator : abock
License : MIT License
Project Creator : abock
static string FormatGuid(GuidFormat format, Guid guid)
{
switch (format)
{
case GuidFormat.N:
return guid.ToString("N");
case GuidFormat.B:
return guid.ToString("B");
case GuidFormat.P:
return guid.ToString("P");
case GuidFormat.X:
return guid.ToString("X");
case GuidFormat.Base64:
return Convert.ToBase64String(guid.ToByteArray());
case GuidFormat.Short:
return Convert.ToBase64String(guid.ToByteArray())
.Replace("/", "_")
.Replace("+", "-")
.Substring(0, 22);
case GuidFormat.D:
default:
return guid.ToString("D");
}
}
19
View Source File : UsageServiceClient.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private string GetAuthHeader(string username)
{
// Get salt
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] four_bytes = new byte[4];
rng.GetBytes(four_bytes);
var salt = BitConverter.ToUInt32(four_bytes, 0).ToString();
// Get timestamp
string timestamp = DateTime.UtcNow.ToString("o");
// create signature
string rawSig = (username ?? "") + timestamp + salt;
var encoding = new System.Text.UTF8Encoding();
byte[] keyByte = encoding.GetBytes(secretKey);
byte[] messageBytes = encoding.GetBytes(rawSig);
string signature;
// hash and base64 encode
using (var sha256 = new HMACSHA256(keyByte))
{
byte[] hashMessage = sha256.ComputeHash(messageBytes);
signature = Convert.ToBase64String(hashMessage);
}
// build auth header
return timestamp + "," + salt + "," + signature;
}
19
View Source File : Utils.cs
License : Apache License 2.0
Project Creator : ac87
License : Apache License 2.0
Project Creator : ac87
public static string Base64UrlEncodeNoPadding(byte[] buffer)
{
string base64 = Convert.ToBase64String(buffer);
// Converts base64 to base64url.
base64 = base64.Replace("+", "-");
base64 = base64.Replace("/", "_");
// Strips padding.
base64 = base64.Replace("=", "");
return base64;
}
19
View Source File : NameUtility.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public static string Encode(string str)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(str)).Replace('+', '-').Replace('/', '_');
}
19
View Source File : DocumentProtector.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public async Task<Doreplacedent> Protect(Doreplacedent value, ProtectionKey key, CancellationToken cancellationToken = default)
{
try
{
byte[] bs;
await using (var ms = new MemoryStream())
{
await JsonSerializer.SerializeAsync(ms, value, cancellationToken: cancellationToken);
bs = ms.ToArray();
}
// var ky = Encoding.UTF8.GetBytes(key.Preplacedword); AesEncrypt(bs, ky)
return new Doreplacedent { Tag = _protectFlag, Raw = Convert.ToBase64String(bs) };
}
catch (Exception ex)
{
throw new ProtectionException("Protect failed.", ex);
}
}
19
View Source File : Utils.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public static string GetGravatarUrl(string email, uint size = 128, string @default = "mp")
{
static string ComputeHash(string input)
{
/*MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
byte[] inputArray = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashedArray = MD5.ComputeHash(inputArray);
MD5.Clear();
return BitConverter.ToString(hashedArray).Replace("-", "");*/
return Convert.ToBase64String(Encoding.UTF8.GetBytes(input));
}
email = email.Trim().ToLower();
string src = $"https://www.gravatar.com/avatar/{ComputeHash(email).ToLower()}?size={size}&d={@default}";
return src;
}
19
View Source File : SecureExtensions.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
public static string EncryptByRsa(this string text, string publicKeyXml = null)
{
if (RsaPublicKey == null) return text;
Rsa.FromXmlString(publicKeyXml ?? RsaPublicKey);
return Convert.ToBase64String(Rsa.Encrypt(Encoding.UTF8.GetBytes(text), false));
}
19
View Source File : AccountExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static string GetPreplacedwordHash(Account account, string preplacedword)
{
byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(preplacedword);
byte[] saltBytes = Convert.FromBase64String(account.PreplacedwordSalt);
byte[] buffer = preplacedwordBytes.Concat(saltBytes).ToArray();
byte[] hash;
using (SHA512Managed hasher = new SHA512Managed())
hash = hasher.ComputeHash(buffer);
return Convert.ToBase64String(hash);
}
19
View Source File : PlayerCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
[CommandHandler("reportbug", AccessLevel.Player, CommandHandlerFlag.RequiresWorld, 2,
"Generate a Bug Report",
"<category> <description>\n" +
"This command generates a URL for you to copy and paste into your web browser to submit for review by server operators and developers.\n" +
"Category can be the following:\n" +
"Creature\n" +
"NPC\n" +
"Item\n" +
"Quest\n" +
"Recipe\n" +
"Landblock\n" +
"Mechanic\n" +
"Code\n" +
"Other\n" +
"For the first three options, the bug report will include identifiers for what you currently have selected/targeted.\n" +
"After category, please include a brief description of the issue, which you can further detail in the report on the website.\n" +
"Examples:\n" +
"/reportbug creature Drudge Prowler is over powered\n" +
"/reportbug npc Ulgrim doesn't know what to do with Sake\n" +
"/reportbug quest I can't enter the portal to the Lost City of Frore\n" +
"/reportbug recipe I cannot combine Bundle of Arrowheads with Bundle of Arrowshafts\n" +
"/reportbug code I was killed by a Non-Player Killer\n"
)]
public static void HandleReportbug(Session session, params string[] parameters)
{
if (!PropertyManager.GetBool("reportbug_enabled").Item)
{
session.Network.EnqueueSend(new GameMessageSystemChat("The command \"reportbug\" is not currently enabled on this server.", ChatMessageType.Broadcast));
return;
}
var category = parameters[0];
var description = "";
for (var i = 1; i < parameters.Length; i++)
description += parameters[i] + " ";
description.Trim();
switch (category.ToLower())
{
case "creature":
case "npc":
case "quest":
case "item":
case "recipe":
case "landblock":
case "mechanic":
case "code":
case "other":
break;
default:
category = "Other";
break;
}
var sn = ConfigManager.Config.Server.WorldName;
var c = session.Player.Name;
var st = "ACE";
//var versions = ServerBuildInfo.GetVersionInfo();
var databaseVersion = DatabaseManager.World.GetVersion();
var sv = ServerBuildInfo.FullVersion;
var pv = databaseVersion.PatchVersion;
//var ct = PropertyManager.GetString("reportbug_content_type").Item;
var cg = category.ToLower();
var w = "";
var g = "";
if (cg == "creature" || cg == "npc"|| cg == "item" || cg == "item")
{
var objectId = new ObjectGuid();
if (session.Player.HealthQueryTarget.HasValue || session.Player.ManaQueryTarget.HasValue || session.Player.CurrentAppraisalTarget.HasValue)
{
if (session.Player.HealthQueryTarget.HasValue)
objectId = new ObjectGuid((uint)session.Player.HealthQueryTarget);
else if (session.Player.ManaQueryTarget.HasValue)
objectId = new ObjectGuid((uint)session.Player.ManaQueryTarget);
else
objectId = new ObjectGuid((uint)session.Player.CurrentAppraisalTarget);
//var wo = session.Player.CurrentLandblock?.GetObject(objectId);
var wo = session.Player.FindObject(objectId.Full, Player.SearchLocations.Everywhere);
if (wo != null)
{
w = $"{wo.WeenieClreplacedId}";
g = $"0x{wo.Guid:X8}";
}
}
}
var l = session.Player.Location.ToLOCString();
var issue = description;
var urlbase = $"https://www.accpp.net/bug?";
var url = urlbase;
if (sn.Length > 0)
url += $"sn={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sn))}";
if (c.Length > 0)
url += $"&c={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(c))}";
if (st.Length > 0)
url += $"&st={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(st))}";
if (sv.Length > 0)
url += $"&sv={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sv))}";
if (pv.Length > 0)
url += $"&pv={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(pv))}";
//if (ct.Length > 0)
// url += $"&ct={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ct))}";
if (cg.Length > 0)
{
if (cg == "npc")
cg = cg.ToUpper();
else
cg = char.ToUpper(cg[0]) + cg.Substring(1);
url += $"&cg={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cg))}";
}
if (w.Length > 0)
url += $"&w={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(w))}";
if (g.Length > 0)
url += $"&g={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(g))}";
if (l.Length > 0)
url += $"&l={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(l))}";
if (issue.Length > 0)
url += $"&i={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(issue))}";
var msg = "\n\n\n\n";
msg += "Bug Report - Copy and Paste the following URL into your browser to submit a bug report\n";
msg += "-=-\n";
msg += $"{url}\n";
msg += "-=-\n";
msg += "\n\n\n\n";
session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.AdminTell));
}
19
View Source File : HttpApiTransport.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public void SetBasicAuth(string username, string preplacedword)
{
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(
Encoding.ASCII.GetBytes($"{username}:{preplacedword}")));
}
19
View Source File : GitSourceProvider.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private string GenerateBasicAuthHeader(RunnerActionPluginExecutionContext executionContext, string accessToken)
{
// use basic auth header with username:preplacedword in base64encoding.
string authHeader = $"x-access-token:{accessToken}";
string base64encodedAuthHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes(authHeader));
// add base64 encoding auth header into secretMasker.
executionContext.AddMask(base64encodedAuthHeader);
return $"basic {base64encodedAuthHeader}";
}
19
View Source File : ConfigurationManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private async Task<GitHubRunnerRegisterToken> GetJITRunnerTokenAsync(string githubUrl, string githubToken, string tokenType)
{
var githubApiUrl = "";
var gitHubUrlBuilder = new UriBuilder(githubUrl);
var path = gitHubUrlBuilder.Path.Split('/', '\\', StringSplitOptions.RemoveEmptyEntries);
if (path.Length == 1)
{
// org runner
if (UrlUtil.IsHostedServer(gitHubUrlBuilder))
{
githubApiUrl = $"{gitHubUrlBuilder.Scheme}://api.{gitHubUrlBuilder.Host}/orgs/{path[0]}/actions/runners/{tokenType}-token";
}
else
{
githubApiUrl = $"{gitHubUrlBuilder.Scheme}://{gitHubUrlBuilder.Host}/api/v3/orgs/{path[0]}/actions/runners/{tokenType}-token";
}
}
else if (path.Length == 2)
{
// repo or enterprise runner.
var repoScope = "repos/";
if (string.Equals(path[0], "enterprises", StringComparison.OrdinalIgnoreCase))
{
repoScope = "";
}
if (UrlUtil.IsHostedServer(gitHubUrlBuilder))
{
githubApiUrl = $"{gitHubUrlBuilder.Scheme}://api.{gitHubUrlBuilder.Host}/{repoScope}{path[0]}/{path[1]}/actions/runners/{tokenType}-token";
}
else
{
githubApiUrl = $"{gitHubUrlBuilder.Scheme}://{gitHubUrlBuilder.Host}/api/v3/{repoScope}{path[0]}/{path[1]}/actions/runners/{tokenType}-token";
}
}
else
{
throw new ArgumentException($"'{githubUrl}' should point to an org or repository.");
}
using (var httpClientHandler = HostContext.CreateHttpClientHandler())
using (var httpClient = new HttpClient(httpClientHandler))
{
var base64EncodingToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"github:{githubToken}"));
HostContext.SecretMasker.AddValue(base64EncodingToken);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("basic", base64EncodingToken);
httpClient.DefaultRequestHeaders.UserAgent.AddRange(HostContext.UserAgents);
httpClient.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github.v3+json");
var response = await httpClient.PostAsync(githubApiUrl, new StringContent(string.Empty));
if (response.IsSuccessStatusCode)
{
Trace.Info($"Http response code: {response.StatusCode} from 'POST {githubApiUrl}'");
var jsonResponse = await response.Content.ReadreplacedtringAsync();
return StringUtil.ConvertFromJson<GitHubRunnerRegisterToken>(jsonResponse);
}
else
{
_term.WriteError($"Http response code: {response.StatusCode} from 'POST {githubApiUrl}'");
var errorResponse = await response.Content.ReadreplacedtringAsync();
_term.WriteError(errorResponse);
response.EnsureSuccessStatusCode();
return null;
}
}
}
19
View Source File : PrimitiveExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static String ToBase64StringNoPadding(this byte[] bytes)
{
ArgumentUtility.CheckEnumerableForNullOrEmpty(bytes, "bytes");
string s = Convert.ToBase64String(bytes); // Regular base64 encoder
s = s.Split('=')[0]; // Remove any trailing '='s
s = s.Replace('+', '-'); // 62nd char of encoding
s = s.Replace('/', '_'); // 63rd char of encoding
return s;
}
19
View Source File : ExecutionContext.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void InitializeJob(Pipelines.AgentJobRequestMessage message, CancellationToken token)
{
// Validation
Trace.Entering();
ArgUtil.NotNull(message, nameof(message));
ArgUtil.NotNull(message.Resources, nameof(message.Resources));
ArgUtil.NotNull(message.Variables, nameof(message.Variables));
ArgUtil.NotNull(message.Plan, nameof(message.Plan));
_cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token);
Global = new GlobalContext();
// Plan
Global.Plan = message.Plan;
Global.Features = PlanUtil.GetFeatures(message.Plan);
// Endpoints
Global.Endpoints = message.Resources.Endpoints;
// Variables
Global.Variables = new Variables(HostContext, message.Variables);
// Environment variables shared across all actions
Global.EnvironmentVariables = new Dictionary<string, string>(VarUtil.EnvironmentVariableKeyComparer);
// Job defaults shared across all actions
Global.JobDefaults = new Dictionary<string, IDictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
// Job Outputs
JobOutputs = new Dictionary<string, VariableValue>(StringComparer.OrdinalIgnoreCase);
// Actions environment
ActionsEnvironment = message.ActionsEnvironment;
// ActionsStepTelemetry
ActionsStepsTelemetry = new List<ActionsStepTelemetry>();
JobTelemetry = new List<JobTelemetry>();
// Service container info
Global.ServiceContainers = new List<ContainerInfo>();
// Steps context (StepsRunner manages adding the scoped steps context)
Global.StepsContext = new StepsContext();
// File table
Global.FileTable = new List<String>(message.FileTable ?? new string[0]);
// Expression values
if (message.ContextData?.Count > 0)
{
foreach (var pair in message.ContextData)
{
ExpressionValues[pair.Key] = pair.Value;
}
}
ExpressionValues["secrets"] = Global.Variables.ToSecretsContext();
ExpressionValues["runner"] = new RunnerContext();
ExpressionValues["job"] = new JobContext();
Trace.Info("Initialize GitHub context");
var githubAccessToken = new StringContextData(Global.Variables.Get("system.github.token"));
var base64EncodedToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"x-access-token:{githubAccessToken}"));
HostContext.SecretMasker.AddValue(base64EncodedToken);
var githubJob = Global.Variables.Get("system.github.job");
var githubContext = new GitHubContext();
githubContext["token"] = githubAccessToken;
if (!string.IsNullOrEmpty(githubJob))
{
githubContext["job"] = new StringContextData(githubJob);
}
var githubDictionary = ExpressionValues["github"].replacedertDictionary("github");
foreach (var pair in githubDictionary)
{
githubContext[pair.Key] = pair.Value;
}
ExpressionValues["github"] = githubContext;
Trace.Info("Initialize Env context");
#if OS_WINDOWS
ExpressionValues["env"] = new DictionaryContextData();
#else
ExpressionValues["env"] = new CaseSensitiveDictionaryContextData();
#endif
// Prepend Path
Global.PrependPath = new List<string>();
// JobSteps for job ExecutionContext
JobSteps = new Queue<IStep>();
// PostJobSteps for job ExecutionContext
PostJobSteps = new Stack<IStep>();
// StepsWithPostRegistered for job ExecutionContext
StepsWithPostRegistered = new HashSet<Guid>();
// EmbeddedStepsWithPostRegistered for job ExecutionContext
EmbeddedStepsWithPostRegistered = new Dictionary<Guid, string>();
// EmbeddedIntraActionState for job ExecutionContext
EmbeddedIntraActionState = new Dictionary<Guid, Dictionary<string, string>>();
// Job timeline record.
InitializeTimelineRecord(
timelineId: message.Timeline.Id,
timelineRecordId: message.JobId,
parentTimelineRecordId: null,
recordType: ExecutionContextType.Job,
displayName: message.JobDisplayName,
refName: message.JobName,
order: null); // The job timeline record's order is set by server.
// Logger (must be initialized before writing warnings).
_logger = HostContext.CreateService<IPagingLogger>();
_logger.Setup(_mainTimelineId, _record.Id);
// Initialize 'echo on action command success' property, default to false, unless Step_Debug is set
EchoOnActionCommand = Global.Variables.Step_Debug ?? false;
// Verbosity (from GitHub.Step_Debug).
Global.WriteDebug = Global.Variables.Step_Debug ?? false;
// Hook up JobServerQueueThrottling event, we will log warning on server tarpit.
_jobServerQueue.JobServerQueueThrottling += JobServerQueueThrottling_EventReceived;
}
19
View Source File : ValueEncoders.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private static string Base64StringEscapeShift(String value, int shift)
{
var bytes = Encoding.UTF8.GetBytes(value);
if (bytes.Length > shift)
{
var shiftArray = new byte[bytes.Length - shift];
Array.Copy(bytes, shift, shiftArray, 0, bytes.Length - shift);
return Convert.ToBase64String(shiftArray);
}
else
{
return Convert.ToBase64String(bytes);
}
}
19
View Source File : FileContainerHttpClient.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[EditorBrowsable(EditorBrowsableState.Never)]
public async Task<HttpResponseMessage> UploadFileAsync(
Int64 containerId,
String itemPath,
Stream fileStream,
byte[] contentId,
Int64 fileLength,
Boolean isGzipped,
Guid scopeIdentifier,
CancellationToken cancellationToken = default(CancellationToken),
int chunkSize = c_defaultChunkSize,
int chunkRetryTimes = c_defaultChunkRetryTimes,
bool uploadFirstChunk = false,
Object userState = null)
{
if (containerId < 1)
{
throw new ArgumentException(WebApiResources.ContainerIdMustBeGreaterThanZero(), "containerId");
}
if (chunkSize > c_maxChunkSize)
{
chunkSize = c_maxChunkSize;
}
// if a contentId is specified but the chunk size is not a 2mb multiple error
if (contentId != null && (chunkSize % c_ContentChunkMultiple) != 0)
{
throw new ArgumentException(FileContainerResources.ChunksizeWrongWithContentId(c_ContentChunkMultiple), "chunkSize");
}
ArgumentUtility.CheckForNull(fileStream, "fileStream");
ApiResourceVersion gzipSupportedVersion = new ApiResourceVersion(new Version(1, 0), 2);
ApiResourceVersion requestVersion = await NegotiateRequestVersionAsync(FileContainerResourceIds.FileContainer, s_currentApiVersion, userState, cancellationToken).ConfigureAwait(false);
if (isGzipped
&& (requestVersion.ApiVersion < gzipSupportedVersion.ApiVersion
|| (requestVersion.ApiVersion == gzipSupportedVersion.ApiVersion && requestVersion.ResourceVersion < gzipSupportedVersion.ResourceVersion)))
{
throw new ArgumentException(FileContainerResources.GzipNotSupportedOnServer(), "isGzipped");
}
if (isGzipped && fileStream.Length >= fileLength)
{
throw new ArgumentException(FileContainerResources.BadCompression(), "fileLength");
}
HttpRequestMessage requestMessage = null;
List<KeyValuePair<String, String>> query = AppendItemQueryString(itemPath, scopeIdentifier);
if (fileStream.Length == 0)
{
// zero byte upload
FileUploadTrace(itemPath, $"Upload zero byte file '{itemPath}'.");
requestMessage = await CreateRequestMessageAsync(HttpMethod.Put, FileContainerResourceIds.FileContainer, routeValues: new { containerId = containerId }, version: s_currentApiVersion, queryParameters: query, userState: userState, cancellationToken: cancellationToken).ConfigureAwait(false);
return await SendAsync(requestMessage, userState, cancellationToken).ConfigureAwait(false);
}
bool multiChunk = false;
int totalChunks = 1;
if (fileStream.Length > chunkSize)
{
totalChunks = (int)Math.Ceiling(fileStream.Length / (double)chunkSize);
FileUploadTrace(itemPath, $"Begin chunking upload file '{itemPath}', chunk size '{chunkSize} Bytes', total chunks '{totalChunks}'.");
multiChunk = true;
}
else
{
FileUploadTrace(itemPath, $"File '{itemPath}' will be uploaded in one chunk.");
chunkSize = (int)fileStream.Length;
}
StreamParser streamParser = new StreamParser(fileStream, chunkSize);
SubStream currentStream = streamParser.GetNextStream();
HttpResponseMessage response = null;
Byte[] dataToSend = new Byte[chunkSize];
int currentChunk = 0;
Stopwatch uploadTimer = new Stopwatch();
while (currentStream.Length > 0 && !cancellationToken.IsCancellationRequested)
{
currentChunk++;
for (int attempt = 1; attempt <= chunkRetryTimes && !cancellationToken.IsCancellationRequested; attempt++)
{
if (attempt > 1)
{
TimeSpan backoff = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10));
FileUploadTrace(itemPath, $"Backoff {backoff.TotalSeconds} seconds before attempt '{attempt}' chunk '{currentChunk}' of file '{itemPath}'.");
await Task.Delay(backoff, cancellationToken).ConfigureAwait(false);
currentStream.Seek(0, SeekOrigin.Begin);
}
FileUploadTrace(itemPath, $"Attempt '{attempt}' for uploading chunk '{currentChunk}' of file '{itemPath}'.");
// inorder for the upload to be retryable, we need the content to be re-readable
// to ensure this we copy the chunk into a byte array and send that
// chunk size ensures we can convert the length to an int
int bytesToCopy = (int)currentStream.Length;
using (MemoryStream ms = new MemoryStream(dataToSend))
{
await currentStream.CopyToAsync(ms, bytesToCopy, cancellationToken).ConfigureAwait(false);
}
// set the content and the Content-Range header
HttpContent byteArrayContent = new ByteArrayContent(dataToSend, 0, bytesToCopy);
byteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
byteArrayContent.Headers.ContentLength = currentStream.Length;
byteArrayContent.Headers.ContentRange = new System.Net.Http.Headers.ContentRangeHeaderValue(currentStream.StartingPostionOnOuterStream,
currentStream.EndingPostionOnOuterStream,
streamParser.Length);
FileUploadTrace(itemPath, $"Generate new HttpRequest for uploading file '{itemPath}', chunk '{currentChunk}' of '{totalChunks}'.");
try
{
if (requestMessage != null)
{
requestMessage.Dispose();
requestMessage = null;
}
requestMessage = await CreateRequestMessageAsync(
HttpMethod.Put,
FileContainerResourceIds.FileContainer,
routeValues: new { containerId = containerId },
version: s_currentApiVersion,
content: byteArrayContent,
queryParameters: query,
userState: userState,
cancellationToken: cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// stop re-try on cancellation.
throw;
}
catch (Exception ex) when (attempt < chunkRetryTimes) // not the last attempt
{
FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' fail to create HttpRequest. Error: {ex.ToString()}.");
continue;
}
if (isGzipped)
{
//add gzip header info
byteArrayContent.Headers.ContentEncoding.Add("gzip");
byteArrayContent.Headers.Add("x-tfs-filelength", fileLength.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
if (contentId != null)
{
byteArrayContent.Headers.Add("x-vso-contentId", Convert.ToBase64String(contentId)); // Base64FormattingOptions.None is default when not supplied
}
FileUploadTrace(itemPath, $"Start uploading file '{itemPath}' to server, chunk '{currentChunk}'.");
uploadTimer.Restart();
try
{
if (response != null)
{
response.Dispose();
response = null;
}
response = await SendAsync(requestMessage, userState, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// stop re-try on cancellation.
throw;
}
catch (Exception ex) when (attempt < chunkRetryTimes) // not the last attempt
{
FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' fail to send request to server. Error: {ex.ToString()}.");
continue;
}
uploadTimer.Stop();
FileUploadTrace(itemPath, $"Finished upload chunk '{currentChunk}' of file '{itemPath}', elapsed {uploadTimer.ElapsedMilliseconds} (ms), response code '{response.StatusCode}'.");
if (multiChunk)
{
FileUploadProgress(itemPath, currentChunk, (int)Math.Ceiling(fileStream.Length / (double)chunkSize));
}
if (response.IsSuccessStatusCode)
{
break;
}
else if (IsFastFailResponse(response))
{
FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' received non-success status code {response.StatusCode} for sending request and cannot continue.");
break;
}
else
{
FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' received non-success status code {response.StatusCode} for sending request.");
continue;
}
}
// if we don't have success then bail and return the failed response
if (!response.IsSuccessStatusCode)
{
break;
}
if (contentId != null && response.StatusCode == HttpStatusCode.Created)
{
// no need to keep uploading since the server said it has all the content
FileUploadTrace(itemPath, $"Stop chunking upload the rest of the file '{itemPath}', since server already has all the content.");
break;
}
currentStream = streamParser.GetNextStream();
if (uploadFirstChunk)
{
break;
}
}
cancellationToken.ThrowIfCancellationRequested();
return response;
}
See More Examples