PTMagic/Core/Helper/SystemHelper.cs

693 lines
19 KiB
C#
Raw Normal View History

2018-05-22 10:11:50 +02:00
using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Linq;
using System.Text;
using System.Globalization;
using Core.Main;
namespace Core.Helper
{
2018-05-22 10:11:50 +02:00
public class SystemHelper
{
private static bool AllwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
{
2018-05-22 10:11:50 +02:00
return true;
}
/// <summary>
/// Checks, if a string is numeric.
/// </summary>
/// <param name="s">The string to check.</param>
/// <returns>True, if the string is numeric.</returns>
public static bool IsNumeric(string s)
{
try
{
2018-05-22 10:11:50 +02:00
Int32.Parse(s);
}
catch
{
2018-05-22 10:11:50 +02:00
return false;
}
return true;
}
public static bool IsInteger(double d)
{
2018-05-22 10:11:50 +02:00
return d % 1 == 0;
}
public static bool IsBoolean(string s)
{
try
{
2018-05-22 10:11:50 +02:00
Boolean.Parse(s);
}
catch
{
2018-05-22 10:11:50 +02:00
return false;
}
return true;
}
/// <summary>
/// Checks, if a string is a double value.
/// </summary>
/// <param name="s">The string to check.</param>
/// <returns>True, if the string is a double value.</returns>
public static bool IsDouble(string s)
{
try
{
2018-05-22 10:11:50 +02:00
Double.Parse(s);
}
catch
{
2018-05-22 10:11:50 +02:00
return false;
}
return true;
}
public static bool IsDouble(string s, string culture)
{
try
{
2018-05-22 10:11:50 +02:00
Double.Parse(s, new CultureInfo(culture));
}
catch
{
2018-05-22 10:11:50 +02:00
return false;
}
return true;
}
/// <summary>
/// Checks, if a string is a DateTime value.
/// </summary>
/// <param name="s">The string to check.</param>
/// <returns>True, if the string is a DateTime value.</returns>
public static bool IsDateTime(string s)
{
try
{
2018-05-22 10:11:50 +02:00
DateTime.Parse(s);
}
catch
{
2018-05-22 10:11:50 +02:00
return false;
}
return true;
}
/// <summary>
/// Konvertiert einen Text zu einem Integer-Wert mit Fehlerbehandlung.
/// </summary>
/// <param name="text">Zu konvertierender Text.</param>
/// <param name="defaultValue">Der Vorgabewert für den Fall, dass keine gültige Zahl eingegeben wurde.</param>
/// <returns>Den Text als Integer. Wenn die Konvertierung fehlschlägt, dann wird der Defaultwert zurückgegeben.</returns>
public static int TextToInteger(string text, int defaultValue)
{
2018-05-22 10:11:50 +02:00
int result = defaultValue;
try
{
2018-05-22 10:11:50 +02:00
string localText = text.Replace(".", "");
result = Convert.ToInt32(localText.Trim());
}
catch { }
2018-05-22 10:11:50 +02:00
return result;
}
/// <summary>
/// Konvertiert einen Text zu einem Integer64-Wert mit Fehlerbehandlung.
/// </summary>
/// <param name="text">Zu konvertierender Text.</param>
/// <param name="defaultValue">Der Vorgabewert für den Fall, dass keine gültige Zahl eingegeben wurde.</param>
/// <returns>Den Text als Integer64. Wenn die Konvertierung fehlschlägt, dann wird der Defaultwert zurückgegeben.</returns>
public static Int64 TextToInteger64(string text, Int64 defaultValue)
{
2018-05-22 10:11:50 +02:00
Int64 result = defaultValue;
try
{
2018-05-22 10:11:50 +02:00
string localText = text.Replace(".", "");
result = Convert.ToInt64(localText.Trim());
}
catch { }
2018-05-22 10:11:50 +02:00
return result;
}
public static double TextToDouble(string text, double defaultValue, string culture)
{
2018-05-22 10:11:50 +02:00
double result = defaultValue;
try
{
if (!string.IsNullOrEmpty(text))
{
2018-05-22 10:11:50 +02:00
double.TryParse(text, NumberStyles.Any, new System.Globalization.CultureInfo(culture), out result);
}
}
catch { }
2018-05-22 10:11:50 +02:00
return result;
}
/// <summary>
/// Konvertiert einen Text zu einem DateTime-Wert mit Fehlerbehandlung.
/// </summary>
/// <param name="text">Zu konvertierender Text.</param>
/// <param name="defaultValue">Der Vorgabewert für den Fall, dass keine gültige DateTime eingegeben wurde.</param>
/// <returns>Den Text als DateTime. Wenn die Konvertierung fehlschlägt, dann wird der Defaultwert zurückgegeben.</returns>
public static DateTime TextToDateTime(string text, DateTime defaultValue)
{
2018-05-22 10:11:50 +02:00
DateTime result = defaultValue;
try
{
2018-05-22 10:11:50 +02:00
result = Convert.ToDateTime(text.Trim());
}
catch { }
2018-05-22 10:11:50 +02:00
return result;
}
public static DateTime TextToDateTime(string text, DateTime defaultValue, string culture)
{
2018-05-22 10:11:50 +02:00
DateTime result = defaultValue;
try
{
2018-05-22 10:11:50 +02:00
result = Convert.ToDateTime(text.Trim(), new System.Globalization.CultureInfo(culture));
}
catch { }
2018-05-22 10:11:50 +02:00
return result;
}
/// <summary>
/// Konvertiert einen Text zu einem Boolean-Wert mit Fehlerbehandlung.
/// </summary>
/// <param name="text">Zu konvertierender Text.</param>
/// <param name="defaultValue">Der Vorgabewert für den Fall, dass keine gültige Boolean eingegeben wurde.</param>
/// <returns>Den Text als Boolean. Wenn die Konvertierung fehlschlägt, dann wird der Defaultwert zurückgegeben.</returns>
public static bool TextToBoolean(string text, bool defaultValue)
{
2018-05-22 10:11:50 +02:00
bool result = defaultValue;
try
{
2018-05-22 10:11:50 +02:00
result = Convert.ToBoolean(text.Trim());
}
catch
{
try
{
2018-05-22 10:11:50 +02:00
int intValue = Convert.ToInt32(text.Trim());
result = intValue == 0 ? false : true;
}
catch { }
2018-05-22 10:11:50 +02:00
}
return result;
}
public static string SplitCamelCase(string s)
{
2018-05-22 10:11:50 +02:00
string result = "";
string whiteList = "ABCDEFGHIJKLMNOPQRSTUVWXYZÄÜÖßabcdefghijklmnopqrstuvwxyzäüö0123456789_- ";
if (!string.IsNullOrEmpty(s))
{
for (int i = 0; i < s.Length; i++)
{
if (char.IsUpper(s[i]) || char.IsNumber(s[i]))
{
if (i > 0 && whiteList.Contains(s[i - 1].ToString()))
{
if (char.IsUpper(s[i]))
{
2018-05-22 10:11:50 +02:00
if (!char.IsUpper(s[i - 1]) && !char.IsNumber(s[i - 1])) result += " ";
}
else if (char.IsNumber(s[i]))
{
2018-05-22 10:11:50 +02:00
if (!char.IsNumber(s[i - 1])) result += " ";
}
}
}
result += s[i].ToString();
}
}
return result;
}
/// <summary>
/// Clears a string using a whitelist.
/// </summary>
/// <param name="text">Text to clear.</param>
/// <param name="allowedCharacters">Allowed characters.</param>
/// <returns>The cleared text.</returns>
public static string StripBadCode(string text, string allowedCharacters)
{
2018-05-22 10:11:50 +02:00
StringBuilder sb = new StringBuilder();
if (text != null)
{
for (int i = 0; i < text.Length; i++)
{
2018-05-22 10:11:50 +02:00
if (allowedCharacters.Contains(text[i].ToString())) sb.Append(text[i]);
}
}
return sb.ToString();
}
public static bool CheckForBadCode(string text, string allowedCharacters)
{
2018-05-22 10:11:50 +02:00
bool result = false;
for (int i = 0; i < text.Length; i++)
{
if (!allowedCharacters.Contains(text[i].ToString()))
{
2018-05-22 10:11:50 +02:00
result = true;
break;
}
}
return result;
}
/// <summary>
/// Schneidet einen Text nach x Zeichen ab
/// </summary>
/// <param name="text">Der Text, der gekürzt werden soll.</param>
/// <param name="maxLength">Die maximale Länge, auf die der Text gekürzt werden soll.</param>
/// <returns>Der gekürzte Text.</returns>
public static string CutText(string text, int maxLength, bool addDots)
{
2018-05-22 10:11:50 +02:00
string result = text;
if (result.Length > maxLength)
{
2018-05-22 10:11:50 +02:00
result = result.Substring(0, maxLength);
if (addDots) result += "...";
}
return result;
}
/// <summary>
/// Ermittelt den Teilstring eines Zeitstring, der die Stunden darstellt.
/// </summary>
public static string GetHourFromString(string timeString)
{
2018-05-22 10:11:50 +02:00
string result = "";
if (timeString.Contains(":"))
{
2018-05-22 10:11:50 +02:00
string[] arrTime = timeString.Split(":".ToCharArray());
result = arrTime[0];
}
return result;
}
/// <summary>
/// Ermittelt den Teilstring eines Zeitstring, der die Minuten darstellt.
/// </summary>
public static string GetMinutesFromString(string timeString)
{
2018-05-22 10:11:50 +02:00
string result = "";
if (timeString.Contains(":"))
{
2018-05-22 10:11:50 +02:00
string[] arrTime = timeString.Split(":".ToCharArray());
result = arrTime[1];
}
return result;
}
public static List<string> ConvertTokenStringToList(string tokenizedString, string separator)
{
2018-05-22 10:11:50 +02:00
List<string> result = new List<string>();
if (!String.IsNullOrEmpty(tokenizedString) && !String.IsNullOrEmpty(separator))
{
2018-05-22 10:11:50 +02:00
string[] arrTokens = tokenizedString.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < arrTokens.Length; i++)
{
2018-05-22 10:11:50 +02:00
result.Add(arrTokens[i].Trim());
}
}
return result;
}
public static List<int> ConvertTokenStringToListInt(string tokenizedString, string separator)
{
2018-05-22 10:11:50 +02:00
List<int> result = new List<int>();
if (!String.IsNullOrEmpty(tokenizedString) && !String.IsNullOrEmpty(separator))
{
2018-05-22 10:11:50 +02:00
string[] arrTokens = tokenizedString.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < arrTokens.Length; i++)
{
2018-05-22 10:11:50 +02:00
result.Add(Convert.ToInt32(arrTokens[i]));
}
}
return result;
}
public static string ConvertListToTokenString(List<string> tokenList, string separator, bool cropDoubleSeparators)
{
2018-05-22 10:11:50 +02:00
string result = "";
if (tokenList.Count > 0)
{
for (int i = 0; i < tokenList.Count; i++)
{
result += tokenList[i].Trim() + (i < (tokenList.Count - 1) ? separator : "");
2018-05-22 10:11:50 +02:00
}
if (cropDoubleSeparators) result = result.Replace(separator + separator, "");
2018-05-22 10:11:50 +02:00
}
return result;
}
public static string ConvertListToTokenString(List<int> tokenList, string separator)
{
2018-05-22 10:11:50 +02:00
string result = "";
if (tokenList.Count > 0)
{
for (int i = 0; i < tokenList.Count; i++)
{
2018-05-22 10:11:50 +02:00
result += tokenList[i].ToString() + separator;
}
result += separator;
result = result.Replace(separator + separator, "");
}
return result;
}
public static List<object> ConvertToObjectList<T>(List<T> inputList)
{
2018-05-22 10:11:50 +02:00
List<object> result = new List<object>();
foreach (T item in inputList)
{
2018-05-22 10:11:50 +02:00
result.Add(item);
}
return result;
}
public static Hashtable ConvertTokenStringToHashtable(string tokenizedString, string pairSeparator, string fieldSeperator)
{
2018-05-22 10:11:50 +02:00
Hashtable result = new Hashtable();
if (!String.IsNullOrEmpty(tokenizedString) && !String.IsNullOrEmpty(pairSeparator) && !String.IsNullOrEmpty(fieldSeperator))
{
2018-05-22 10:11:50 +02:00
string[] arrTokens = tokenizedString.Split(pairSeparator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < arrTokens.Length; i++)
{
2018-05-22 10:11:50 +02:00
string[] arrKeyValuePair = arrTokens[i].Split(fieldSeperator.ToCharArray());
result.Add(arrKeyValuePair[0], arrKeyValuePair[1]);
}
}
return result;
}
public static string ConvertHashtableToTokenString(Hashtable tokenHashtable, string pairSeparator, string fieldSeperator)
{
2018-05-22 10:11:50 +02:00
string result = "";
if (tokenHashtable.Keys.Count > 0)
{
foreach (string key in tokenHashtable.Keys)
{
2018-05-22 10:11:50 +02:00
result += key + fieldSeperator + tokenHashtable[key] + pairSeparator;
}
result += pairSeparator;
result = result.Replace(pairSeparator + pairSeparator, "");
}
return result;
}
public static string GetProperDurationTime(int durationSeconds, bool includeDays = true)
{
2018-05-22 10:11:50 +02:00
string result = "";
int days = (int)Math.Floor((double)durationSeconds / (60.0 * 60.0 * 24.0));
if (!includeDays) days = 0;
int hours = (int)Math.Floor((double)durationSeconds / (60.0 * 60.0)) - days * 24;
int minutes = (int)Math.Floor((double)durationSeconds / 60.0) - (hours * 60) - (days * 24 * 60);
int seconds = durationSeconds - (minutes * 60) - (hours * 60 * 60) - (days * 24 * 60 * 60);
if (days > 0)
{
2018-05-22 10:11:50 +02:00
result += days.ToString() + "d";
}
if (hours > 0)
{
2018-05-22 10:11:50 +02:00
if (days > 0) result += " ";
result += hours.ToString() + "h";
}
if (minutes > 0)
{
2018-05-22 10:11:50 +02:00
if (hours > 0 || days > 0) result += " ";
result += minutes.ToString() + "m";
}
if (seconds > 0)
{
2018-05-22 10:11:50 +02:00
if (minutes > 0 || hours > 0 || days > 0) result += " ";
result += seconds.ToString() + "s";
}
return result;
}
public static void AddValueToStringBuilder(StringBuilder sb, string value, int length, bool fillField, string delimiter)
{
if (!string.IsNullOrEmpty(value))
{
2018-05-22 10:11:50 +02:00
if (value.Length > length)
sb.Append(value.Substring(0, length)); // Beschneiden
else
{
2018-05-22 10:11:50 +02:00
if (fillField)
sb.Append(value.PadRight(length));
else
sb.Append(value);
}
}
else
{
2018-05-22 10:11:50 +02:00
if (fillField)
sb.Append(string.Empty.PadRight(length));
}
sb.Append(delimiter);
}
public static bool UrlIsReachable(string url)
{
2018-05-22 10:11:50 +02:00
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AllwaysGoodCertificate);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Timeout = 10000;
request.Method = "GET";
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
2018-05-22 10:11:50 +02:00
return response.StatusCode == HttpStatusCode.OK;
}
}
catch (WebException)
{
2018-05-22 10:11:50 +02:00
return false;
}
}
public static string GetMarketLink(string platform, string exchange, string market, string mainMarket)
{
2018-05-22 10:11:50 +02:00
string result = "#";
if (platform.Equals("TradingView"))
{
2018-05-22 10:11:50 +02:00
result = "https://www.tradingview.com/chart/?symbol=" + exchange.ToUpper() + ":";
string pairName = SystemHelper.StripBadCode(market, Constants.WhiteListMinimal);
if (pairName.StartsWith(mainMarket))
{
2018-05-22 10:11:50 +02:00
pairName = pairName.Replace(mainMarket, "") + mainMarket;
}
result += pairName;
}
else
{
switch (exchange)
{
2018-05-22 10:11:50 +02:00
case "Bittrex":
result = "https://bittrex.com/Market/Index?MarketName=" + market;
break;
case "Binance":
result = "https://www.binance.com/trade.html?symbol=" + market;
break;
2019-10-16 07:03:19 +02:00
case "BinanceUS":
result = "https://www.binance.us/trade.html?symbol=" + market;
break;
2018-05-22 10:11:50 +02:00
case "Poloniex":
result = "https://poloniex.com/exchange#" + market.ToLower();
break;
}
}
return result;
}
public static string GetFullMarketName(string mainMarket, string market, string exchange)
{
2018-05-22 10:11:50 +02:00
string result = market;
switch (exchange)
{
2018-05-22 10:11:50 +02:00
case "Bittrex":
result = mainMarket + "-" + market;
break;
case "Binance":
result = market + mainMarket;
break;
2019-10-16 07:03:19 +02:00
case "BinanceUS":
result = market + mainMarket;
break;
2018-05-22 10:11:50 +02:00
case "Poloniex":
result = mainMarket + "_" + market;
break;
}
return result;
}
public static string GetTradingViewSymbol(string exchange, string market, string mainMarket)
{
2018-05-22 10:11:50 +02:00
string result = exchange.ToUpper() + ":";
string pairName = SystemHelper.StripBadCode(market, Constants.WhiteListMinimal);
if (pairName.StartsWith(mainMarket))
{
2018-05-22 10:11:50 +02:00
pairName = pairName.Replace(mainMarket, "") + mainMarket;
}
result += pairName;
return result;
}
2019-01-14 04:21:30 +01:00
public static string GetTradingViewStudies(string study)
{
string result = study;
return result;
}
2019-03-19 17:13:41 +01:00
public static string GetMainCurrencySymbol(string tvSymbol)
{
string result = tvSymbol;
return result;
}
public static string GetCurrencySymbol(string code)
{
2018-05-22 10:11:50 +02:00
string result = code;
try
{
2018-05-22 10:11:50 +02:00
System.Globalization.RegionInfo regionInfo = (from culture in System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures)
where culture.Name.Length > 0 && !culture.IsNeutralCulture
let region = new System.Globalization.RegionInfo(culture.LCID)
where String.Equals(region.ISOCurrencySymbol, code, StringComparison.InvariantCultureIgnoreCase)
select region).First();
result = regionInfo.CurrencySymbol;
}
catch
{
2018-05-22 10:11:50 +02:00
}
return result;
}
public static string PropertyToString(object property)
{
2018-05-22 10:11:50 +02:00
string result = property.ToString();
if (!property.ToString().Equals("true", StringComparison.InvariantCultureIgnoreCase) && !property.ToString().Equals("false", StringComparison.InvariantCultureIgnoreCase))
{
double resultDouble;
if (double.TryParse(property.ToString(), out resultDouble))
{
result = ((decimal)resultDouble).ToString();
}
}
else
{
2018-05-22 10:11:50 +02:00
result = property.ToString().ToLower();
}
return result;
}
public static bool IsRecentVersion(string currentVersion, string latestVersion)
{
2018-05-22 10:11:50 +02:00
bool result = true;
List<int> currentVersionInfo = SystemHelper.ConvertTokenStringToListInt(currentVersion, ".");
List<int> latestVersionInfo = SystemHelper.ConvertTokenStringToListInt(latestVersion, ".");
if (currentVersionInfo[0] < latestVersionInfo[0])
{
2018-05-22 10:11:50 +02:00
result = false;
}
if (currentVersionInfo[0] == latestVersionInfo[0] && currentVersionInfo[1] < latestVersionInfo[1])
{
2018-05-22 10:11:50 +02:00
result = false;
}
if (currentVersionInfo[0] == latestVersionInfo[0] && currentVersionInfo[1] == latestVersionInfo[1] && currentVersionInfo[2] < latestVersionInfo[2])
{
2018-05-22 10:11:50 +02:00
result = false;
}
return result;
}
}
}