namespace StockSharp.Configuration; using System.Text; using Newtonsoft.Json; using NuGet.Configuration; /// /// System paths. /// public static class Paths { static Paths() { var companyPath = PathsHolder.CompanyPath ?? ConfigManager.TryGet("companyPath"); CompanyPath = companyPath.IsEmpty() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "StockSharp") : companyPath.ToFullPathIfNeed(); CredentialsFile = Path.Combine(CompanyPath, $"credentials{DefaultSettingsExt}"); AppName = ConfigManager.TryGet("appName", TypeHelper.ApplicationName); AppDataPath = GetAppDataPath(PathsHolder.AppDataPath ?? ConfigManager.TryGet("settingsPath"), AppName2); PlatformConfigurationFile = Path.Combine(AppDataPath, $"platform_config{DefaultSettingsExt}"); ProxyConfigurationFile = Path.Combine(CompanyPath, $"proxy_config{DefaultSettingsExt}"); SecurityNativeIdDir = Path.Combine(AppDataPath, "NativeId"); SecurityMappingDir = Path.Combine(AppDataPath, "Symbol mapping"); SecurityExtendedInfo = Path.Combine(AppDataPath, "Extended info"); StorageDir = Path.Combine(AppDataPath, "Storage"); SnapshotsDir = Path.Combine(AppDataPath, "Snapshots"); CandlePatternsFile = Path.Combine(AppDataPath, $"candle_patterns{DefaultSettingsExt}"); CompilerCacheDir = Path.Combine(AppDataPath, "compiler_cache"); LogsDir = Path.Combine(AppDataPath, "Logs"); ReportLogsPath = Path.Combine(AppDataPath, "BugReports"); PythonUtilsPath = Path.Combine(CompanyPath, "Python"); InstallerDir = Path.Combine(CompanyPath, "Installer"); InstallerInstallationsConfigPath = Path.Combine(InstallerDir, $"installer_apps_installed{DefaultSettingsExt}"); try { var settings = Settings.LoadDefaultSettings(null); HistoryDataPath = GetHistoryDataPath(SettingsUtility.GetGlobalPackagesFolder(settings)); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex); } } /// /// Get . /// /// Relative . /// /// public static string GetAppDataPath(string appDataPath, string appName) => appDataPath.IsEmpty() ? Path.Combine(CompanyPath, appName) : appDataPath.ToFullPathIfNeed(); /// /// Get history data path. /// /// Directory. /// History data path. public static string GetHistoryDataPath(string startDir) { static DirectoryInfo FindHistoryDataSubfolder(DirectoryInfo packageRoot) { if (!packageRoot.Exists) return null; foreach (var di in packageRoot.GetDirectories().OrderByDescending(di => di.Name)) { var d = new DirectoryInfo(Path.Combine(di.FullName, "HistoryData")); if (d.Exists) return d; } return null; } var dir = new DirectoryInfo(Path.GetDirectoryName(startDir)); while (dir != null) { var hdRoot = FindHistoryDataSubfolder(new DirectoryInfo(Path.Combine(dir.FullName, "packages", "stocksharp.samples.historydata"))); if (hdRoot != null) return hdRoot.FullName; dir = dir.Parent; } return null; } /// /// App title. /// public static readonly string AppName; /// /// /// public static string AppName2 => AppName.Remove("S#.", true); /// /// App title with version. /// public static string AppNameWithVersion => $"{AppName} v{InstalledVersion}"; /// /// The path to directory with all applications. /// public static readonly string CompanyPath; /// /// The path to the file with credentials. /// public static readonly string CredentialsFile; /// /// The path to the settings directory. /// public static readonly string AppDataPath; /// /// The path to the Python utils directory. /// public static readonly string PythonUtilsPath; /// /// The path to the settings directory. /// public static readonly string ReportLogsPath; /// /// The path to the configuration file of platform definition. /// public static readonly string PlatformConfigurationFile; /// /// The path to the configuration file of proxy settings. /// public static readonly string ProxyConfigurationFile; /// /// The path to the directory with native security identifiers. /// public static readonly string SecurityNativeIdDir; /// /// The path to the directory with securities id mapping. /// public static readonly string SecurityMappingDir; /// /// The path to the directory with securities extended info. /// public static readonly string SecurityExtendedInfo; /// /// The path to the directory with market data. /// public static readonly string StorageDir; /// /// The path to the directory with snapshots of market data. /// public static readonly string SnapshotsDir; /// /// The path to the file with candle patterns. /// public static readonly string CandlePatternsFile; /// /// The path to the compiler cache directory. /// public static readonly string CompilerCacheDir; /// /// The path to the logs directory. /// public static readonly string LogsDir; /// /// The path to the installer directory. /// public static readonly string InstallerDir; /// /// The path to the installer directory. /// public static readonly string InstallerInstallationsConfigPath; /// /// Installer UI exe name. /// public const string InstallerUIName = "StockSharp.Installer.UI"; /// /// Installer console exe name. /// public const string InstallerConsoleName = "StockSharp.Installer.Console"; /// /// Setup name. /// public const string SetupName = "stocksharp_setup"; /// /// Web site domain. /// public static string Domain => LocalizedStrings.StockSharpDomain; /// /// Get website url. /// /// Localized url. public static string GetWebSiteUrl() => $"https://stocksharp.{Domain}"; /// /// Get logo url. /// /// Logo url. public static string GetLogoUrl() => $"{GetWebSiteUrl()}/images/logo.png"; /// /// Chat in Telegram. /// public static string Chat => LocalizedStrings.StockSharpChatUrl; /// /// Bot in Telegram. /// public static string Bot => $"https://t.me/stocksharpbot"; /// /// public static class Pages { /// /// public const long Eula = 274; /// /// public const long Pricing = 157; /// /// public const long NugetManual = 241; /// /// public const long Message = 278; /// /// public const long Topic = 275; /// /// public const long File = 276; /// /// public const long Users = 246; /// /// public const long Register = 252; /// /// public const long Forgot = 253; /// /// public const long Faq = 239; /// /// public const long Store = 164; /// /// public const long Login = 251; /// /// public const long Profile = 243; } /// /// Get page url. /// /// Page id. /// Url part (topic id, file name etc.). /// Localized url. public static string GetPageUrl(long id, object urlPart = default) { var url = GetWebSiteUrl() + "/"; url += id switch { Pages.Eula => "products/eula", Pages.Pricing => "pricing", Pages.NugetManual => "products/nuget_manual", Pages.Message => "posts/m", Pages.Topic => "topic", Pages.File => "file", Pages.Users => "users", Pages.Register => "register", Pages.Forgot => "forgot", Pages.Faq => "store/faq", Pages.Store => "store", Pages.Login => "login", Pages.Profile => "profile", _ => throw new ArgumentOutOfRangeException(nameof(id), id, LocalizedStrings.InvalidValue), }; url += "/"; if (urlPart is not null) url += $"{urlPart}/"; return url; } /// /// Try to build documentation URL. /// /// URL part. /// Absolute URL. public static string TryBuildDocUrl(this string urlPart) { if (!urlPart.StartsWithIgnoreCase("http")) urlPart = GetDocUrl(urlPart); return urlPart; } /// /// To create localized url. /// /// Help topic. /// Localized url. public static string GetDocUrl(string docUrl) => $"https://doc.stocksharp.{Domain}/{docUrl}"; /// /// Entry assembly. /// public static Assembly EntryAssembly => Assembly.GetEntryAssembly(); private static string _installedVersion; /// /// Installed version of the product. /// public static string InstalledVersion { get { if (_installedVersion != null) return _installedVersion; static string GetAssemblyVersion() => EntryAssembly?.GetName().Version.To(); try { _installedVersion = TryGetInstalledVersion(Directory.GetCurrentDirectory()).IsEmpty(ConfigManager.TryGet("actualVersion", "5.0.0").IsEmpty(GetAssemblyVersion())); } catch { _installedVersion = GetAssemblyVersion(); } return _installedVersion; } } /// /// Reset installed version cache so it would be re-generated next time when it's requested. /// public static void ResetInstalledVersionCache() => _installedVersion = null; /// /// Build info version. /// public static string BuildVersion => EntryAssembly?.GetAttribute()?.InformationalVersion; private static SettingsStorage[] GetInstallations() { if (!InstallerInstallationsConfigPath.IsConfigExists()) return null; SettingsStorage storage; lock (InstallerInstallationsConfigPath) storage = InstallerInstallationsConfigPath.DeserializeInvariant(); if (storage is null) return null; var installations = storage?.GetValue("Installations"); if (!(installations?.Length > 0)) return null; return installations; } /// /// Try get installed path by product id. /// /// Identifier. /// Installed path. public static string TryGetInstalledPath(long productId) { var installations = GetInstallations(); if (installations == null) return null; var installation = installations.FirstOrDefault(ss => productId == ss.TryGet("ProductKey")); if (installation == null) return null; return installation.TryGet("InstallDirectory"); } /// /// Get currently installed version of the product. /// /// File system path to product installation. /// Installed version of the product. public static string TryGetInstalledVersion(string productInstallPath) { if (productInstallPath.IsEmpty()) throw new ArgumentException(nameof(productInstallPath)); var installations = GetInstallations(); if (installations == null) return null; var installation = installations.FirstOrDefault(ss => productInstallPath.ComparePaths(ss.TryGet("InstallDirectory"))); if (installation == null) return null; var version = installation.GetValue("Version"); if (version is string str) return str; var identityStr = ((SettingsStorage)version)? .TryGet("Metadata")? .TryGet("Identity"); if (identityStr.IsEmpty()) return null; // ReSharper disable once PossibleNullReferenceException var parts = identityStr.Split('|'); return parts.Length != 2 ? null : parts[1]; } /// /// Sample history data. /// public static readonly string HistoryDataPath; /// /// Sample history data security. /// public const string HistoryDefaultSecurity = "BTCUSDT@BNBFT"; /// /// Sample history data security. /// public const string HistoryDefaultSecurity2 = "TONUSDT@BNBFT"; /// /// Begin date of . /// public static readonly DateTime HistoryBeginDate = new DateTime(2024, 3, 1).UtcKind(); /// /// End date of . /// public static readonly DateTime HistoryEndDate = new DateTime(2024, 3, 31).UtcKind(); /// /// Birthday. /// public static readonly DateTime Birthday = new DateTime(1977, 5, 24).UtcKind(); /// /// Default extension for settings file. /// public const string DefaultSettingsExt = FileExts.Json; /// /// Returns an files with extension. /// /// The relative or absolute path to the directory to search. /// The search string to match against the names of files in path. /// Files. public static IEnumerable EnumerateConfigs(this string path, string filter = "*") => Directory.EnumerateFiles(path, $"{filter}{DefaultSettingsExt}"); /// /// Make the specified with extension. /// /// File path. /// File path. public static string MakeBackup(this string filePath) => $"{filePath}{FileExts.Backup}"; /// /// Rename the specified file with extension. /// /// File path. /// Backup file path. public static void MoveToBackup(this string filePath, string backupFilePath = null) { var target = backupFilePath ?? filePath; var bak = target.MakeBackup(); var idx = 0; do { if(!File.Exists(bak)) break; bak = (target + $".{++idx}").MakeBackup(); } while(true); File.Move(filePath, bak); } /// /// Create serializer. /// /// Value type. /// Serializer adds UTF8 BOM preamble. /// Serializer. public static ISerializer CreateSerializer(bool bom = true) => new JsonSerializer { Indent = true, Encoding = bom ? Encoding.UTF8 : JsonHelper.UTF8NoBom, EnumAsString = true, NullValueHandling = NullValueHandling.Ignore, }; /// /// Serialize state into value. /// /// Type of . /// Value. /// Serializer adds UTF8 BOM preamble. /// value. public static string SerializeToString(this T value, bool bom = true) => Serialize(value, bom).UTF8(); /// /// Deserialize state from . /// /// Type of . /// Value. /// value. public static void DeserializeFromString(this T value, string str) where T : IPersistable => value.Load(Deserialize(str.UTF8())); /// /// Serialize value into the specified file. /// /// Value type. /// Value. /// File path. /// Add UTF8 BOM preamble. public static void Serialize(this T value, string filePath, bool bom = true) => CreateSerializer(bom).Serialize(value, filePath); /// /// Serialize value into byte array. /// /// Value type. /// Value. /// Add UTF8 BOM preamble. /// Serialized data. public static byte[] Serialize(this T value, bool bom = true) => CreateSerializer(bom).Serialize(value); /// /// Deserialize value from the specified file. /// /// Value type. /// File path. /// Value. public static T Deserialize(this string filePath) { try { return filePath.DeserializeOrThrow(); } catch (Exception e) { new Exception($"Error deserializing '{filePath}'", e).LogError(); return default; } } /// /// Deserialize value from the specified file. /// /// Value type. /// File path. /// Value. public static T DeserializeOrThrow(this string filePath) { var defFile = Path.ChangeExtension(filePath, DefaultSettingsExt); var defSer = CreateSerializer(); if(!File.Exists(defFile)) throw new FileNotFoundException($"file not found: '{defFile}'"); return defSer.Deserialize(defFile); } /// /// Deserialize value from the serialized data. /// /// Value type. /// Serialized data. /// Value. public static T Deserialize(this byte[] data) { var serializer = CreateSerializer(); try { return serializer.Deserialize(data); } catch(Exception e) { e.LogError(); } return default; } /// /// Deserialize value from the serialized data. /// /// Value type. /// Serialized data. /// Value. public static T Deserialize(this Stream data) { var serializer = CreateSerializer(); try { return serializer.Deserialize(data); } catch (Exception e) { e.LogError(); } return default; } /// /// Get file name without extension for the specified id. /// /// Identifier. /// Replacing character. /// File name without extension. public static string GetFileNameWithoutExtension(this Guid id, char? by = '_') { var s = id.ToString(); return by is null ? s.Remove("-") : s.Replace('-', by.Value); } /// /// Get file name for the specified id. /// /// Identifier. /// File name. public static string GetFileName(this Guid id) => $"{id.GetFileNameWithoutExtension()}{DefaultSettingsExt}"; /// /// Determines the specified config file exists. /// /// Config file. /// Check result. public static bool IsConfigExists(this string configFile) => File.Exists(configFile); /// /// in case . /// public const string TokenBasedEmail = "x"; }