Config.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. using System;
  2. using System.Drawing;
  3. using System.Drawing.Text;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using System.Threading.Tasks;
  9. namespace FastReport.Utils
  10. {
  11. /// <summary>
  12. /// Contains some configuration properties and settings that will be applied to the FastReport.Net
  13. /// environment, including Report, Designer and Preview components.
  14. /// </summary>
  15. public static partial class Config
  16. {
  17. #if COMMUNITY
  18. const string CONFIG_NAME = "FastReport.Community.config";
  19. #elif MONO
  20. #if WPF
  21. const string CONFIG_NAME = "FastReport.WPF.config";
  22. #elif AVALONIA
  23. const string CONFIG_NAME = "FastReport.Avalonia.config";
  24. #else
  25. const string CONFIG_NAME = "FastReport.Mono.config";
  26. #endif
  27. #else
  28. const string CONFIG_NAME = "FastReport.config";
  29. #endif
  30. #region Private Fields
  31. private static readonly XmlDocument FDoc = new XmlDocument();
  32. private static readonly string version = typeof(Report).Assembly.GetName().Version.ToString(3);
  33. private static string FFolder = null;
  34. private static string FFontListFolder = null;
  35. private static string FLogs = "";
  36. private static bool FIsRunningOnMono;
  37. private static ReportSettings FReportSettings = new ReportSettings();
  38. private static bool FRightToLeft = false;
  39. private static string FTempFolder = null;
  40. private static string systemTempFolder = null;
  41. private static bool FStringOptimization = true;
  42. private static bool FWebMode;
  43. private static bool preparedCompressed = true;
  44. private static bool enableScriptSecurity = false;
  45. private static ScriptSecurityProperties scriptSecurityProps = null;
  46. private static bool forbidLocalData = false;
  47. private static bool userSetsScriptSecurity = false;
  48. private static readonly FRPrivateFontCollection privateFontCollection = new FRPrivateFontCollection();
  49. internal static bool CleanupOnExit;
  50. private static CompilerSettings compilerSettings = new CompilerSettings();
  51. private static string applicationFolder;
  52. private static readonly string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
  53. #endregion Private Fields
  54. #region Public Properties
  55. /// <summary>
  56. /// Gets a value indicating that the Mono runtime is used.
  57. /// </summary>
  58. internal static bool IsRunningOnMono
  59. {
  60. get { return FIsRunningOnMono; }
  61. }
  62. #if CROSSPLATFORM
  63. internal static bool IsWindows { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
  64. internal static bool IsWasm { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER"));// (int)RuntimeInformation.ProcessArchitecture == 4; // Architecture.Wasm = 4;
  65. #endif
  66. /// <summary>
  67. /// Gets or sets a value indicating is it impossible to specify a local data path in Xml and Csv.
  68. /// </summary>
  69. public static bool ForbidLocalData
  70. {
  71. get { return forbidLocalData; }
  72. set { forbidLocalData = value; }
  73. }
  74. /// <summary>
  75. /// Gets or sets the optimization of strings. Is experimental feature.
  76. /// </summary>
  77. public static bool IsStringOptimization
  78. {
  79. get { return FStringOptimization; }
  80. set { FStringOptimization = value; }
  81. }
  82. /// <summary>
  83. /// Enable or disable the compression in files with prepared reports (fpx).
  84. /// </summary>
  85. public static bool PreparedCompressed
  86. {
  87. get { return preparedCompressed; }
  88. set { preparedCompressed = value; }
  89. }
  90. /// <summary>
  91. /// Gets or sets the application folder.
  92. /// </summary>
  93. public static string ApplicationFolder
  94. {
  95. get
  96. {
  97. if (applicationFolder == null)
  98. return baseDirectory;
  99. return applicationFolder;
  100. }
  101. set
  102. {
  103. applicationFolder = value;
  104. }
  105. }
  106. /// <summary>
  107. /// Gets or sets the path used to load/save the configuration file.
  108. /// </summary>
  109. /// <remarks>
  110. /// By default, the configuration file is saved to the application local data folder
  111. /// (C:\Documents and Settings\User_Name\Local Settings\Application Data\FastReport\).
  112. /// Set this property to "" if you want to store the configuration file in the application folder.
  113. /// </remarks>
  114. public static string Folder
  115. {
  116. get { return FFolder; }
  117. set { FFolder = value; }
  118. }
  119. /// <summary>
  120. /// Gets or sets the path used to font.list file.
  121. /// </summary>
  122. /// <remarks>
  123. /// By default, the font.list file is saved to the FastReport.config folder
  124. /// If WebMode enabled (or config file path is null), then file is saved in the application folder.
  125. /// </remarks>
  126. public static string FontListFolder
  127. {
  128. get { return FFontListFolder; }
  129. set { FFontListFolder = value; }
  130. }
  131. /// <summary>
  132. /// Gets or sets the settings for the Report component.
  133. /// </summary>
  134. public static ReportSettings ReportSettings
  135. {
  136. get { return FReportSettings; }
  137. set { FReportSettings = value; }
  138. }
  139. /// <summary>
  140. /// Gets or sets a value indicating whether RTL layout should be used.
  141. /// </summary>
  142. public static bool RightToLeft
  143. {
  144. get { return FRightToLeft; }
  145. set { FRightToLeft = value; }
  146. }
  147. /// <summary>
  148. /// Gets the root item of config xml.
  149. /// </summary>
  150. public static XmlItem Root
  151. {
  152. get { return FDoc.Root; }
  153. }
  154. /// <summary>
  155. /// Gets or sets the path to the temporary folder used to store temporary files.
  156. /// </summary>
  157. /// <remarks>
  158. /// The default value is <b>null</b>, so the system temp folder will be used.
  159. /// </remarks>
  160. public static string TempFolder
  161. {
  162. get { return FTempFolder; }
  163. set { FTempFolder = value; }
  164. }
  165. /// <summary>
  166. /// Gets the path to the system temporary folder used to store temporary files.
  167. /// </summary>
  168. public static string SystemTempFolder
  169. {
  170. get { return systemTempFolder == null ? GetTempPath() : systemTempFolder; }
  171. }
  172. /// <summary>
  173. /// Gets FastReport version.
  174. /// </summary>
  175. public static string Version
  176. {
  177. get { return version; }
  178. }
  179. /// <summary>
  180. /// Called on script compile
  181. /// </summary>
  182. public static event EventHandler<ScriptSecurityEventArgs> ScriptCompile;
  183. /// <summary>
  184. /// Gets a PrivateFontCollection instance.
  185. /// </summary>
  186. [Obsolete("Use FastReport.FontManager instead")]
  187. public static FRPrivateFontCollection PrivateFontCollection
  188. {
  189. get { return privateFontCollection; }
  190. }
  191. /// <summary>
  192. /// Enable report script validation. For WebMode only
  193. /// </summary>
  194. public static bool EnableScriptSecurity
  195. {
  196. get
  197. {
  198. return enableScriptSecurity;
  199. }
  200. set
  201. {
  202. if (OnEnableScriptSecurityChanged != null)
  203. OnEnableScriptSecurityChanged.Invoke(null, null);
  204. enableScriptSecurity = value;
  205. //
  206. userSetsScriptSecurity = true;
  207. if (value)
  208. {
  209. if (scriptSecurityProps == null)
  210. scriptSecurityProps = new ScriptSecurityProperties();
  211. }
  212. }
  213. }
  214. /// <summary>
  215. /// Throws when property EnableScriptSecurity has been changed
  216. /// </summary>
  217. public static event EventHandler OnEnableScriptSecurityChanged;
  218. /// <summary>
  219. /// Properties of report script validation
  220. /// </summary>
  221. public static ScriptSecurityProperties ScriptSecurityProps
  222. {
  223. get { return scriptSecurityProps; }
  224. }
  225. /// <summary>
  226. /// Settings of report compiler.
  227. /// </summary>
  228. public static CompilerSettings CompilerSettings
  229. {
  230. get { return compilerSettings; }
  231. set { compilerSettings = value; }
  232. }
  233. #endregion Public Properties
  234. #region Public Methods
  235. /// <summary>
  236. /// Warms up the Roslyn compiler asynchronously.
  237. /// </summary>
  238. /// <remarks>
  239. /// Call this method at an application start to warm up the Roslyn compiler (used in NetCore).
  240. /// </remarks>
  241. public static async void CompilerWarmup()
  242. {
  243. Report.EnsureInit();
  244. await Task.Run(() =>
  245. {
  246. new Report() { ScriptText = "using System; namespace FastReport { public class ReportScript {\r\n} }" }.Compile();
  247. });
  248. }
  249. #endregion
  250. #region Internal Methods
  251. internal static string CreateTempFile(string dir)
  252. {
  253. if (String.IsNullOrEmpty(dir))
  254. return GetTempFileName();
  255. return Path.Combine(dir, Path.GetRandomFileName());
  256. }
  257. internal static string GetTempFolder()
  258. {
  259. return TempFolder == null ? GetTempPath() : TempFolder;
  260. }
  261. internal static void Init()
  262. {
  263. FIsRunningOnMono = Type.GetType("Mono.Runtime") != null;
  264. CheckWebMode();
  265. #if !CROSSPLATFORM || AVALONIA
  266. if (!WebMode)
  267. LoadConfig();
  268. #endif
  269. if (!userSetsScriptSecurity && WebMode)
  270. {
  271. enableScriptSecurity = true; // don't throw event
  272. scriptSecurityProps = new ScriptSecurityProperties();
  273. }
  274. LoadPlugins();
  275. #if !COMMUNITY
  276. RestoreExportOptions();
  277. #endif
  278. #if !SKIA
  279. InitTextRenderingHint();
  280. #endif
  281. }
  282. private static void InitTextRenderingHint()
  283. {
  284. // init TextRenderingHint.SystemDefault
  285. // bug in .Net: if you use any other hint before SystemDefault, the SystemDefault will
  286. // look like SingleBitPerPixel
  287. using (Bitmap bmp = new Bitmap(1, 1))
  288. using (Graphics g = Graphics.FromImage(bmp))
  289. {
  290. g.TextRenderingHint = TextRenderingHint.SystemDefault;
  291. g.DrawString(" ", SystemFonts.DefaultFont, Brushes.Black, 0, 0);
  292. }
  293. }
  294. private static void CheckWebMode()
  295. {
  296. // If we/user sets 'WebMode = true' before this check - Config shouln't change it (because check may be incorrect)
  297. if (!WebMode)
  298. {
  299. #if NETSTANDARD || NETCOREAPP
  300. var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
  301. foreach (var loadedAsmbly in loadedAssemblies)
  302. {
  303. bool isAspNetCore = loadedAsmbly.GetName().Name.StartsWith("Microsoft.AspNetCore");
  304. if (isAspNetCore)
  305. {
  306. WebMode = true;
  307. break;
  308. }
  309. }
  310. #else
  311. string processName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
  312. WebMode = String.Compare(processName, "iisexpress") == 0 ||
  313. String.Compare(processName, "w3wp") == 0;
  314. #endif
  315. }
  316. }
  317. internal static void WriteLogString(string s)
  318. {
  319. WriteLogString(s, false);
  320. }
  321. internal static void WriteLogString(string s, bool distinct)
  322. {
  323. if (distinct)
  324. {
  325. if (FLogs.IndexOf(s + "\r\n") != -1)
  326. return;
  327. }
  328. FLogs += s + "\r\n";
  329. }
  330. internal static void OnScriptCompile(ScriptSecurityEventArgs e)
  331. {
  332. if (ScriptCompile != null)
  333. {
  334. ScriptCompile.Invoke(null, e);
  335. }
  336. if (!e.IsValid)
  337. {
  338. throw new CompilerException(Res.Get("Messages,CompilerError"));
  339. }
  340. }
  341. #if NETSTANDARD || NETCOREAPP
  342. public static event EventHandler<Code.CodeDom.Compiler.CompilationEventArgs> BeforeEmitCompile;
  343. internal static void OnBeforeScriptCompilation(object sender, Code.CodeDom.Compiler.CompilationEventArgs e)
  344. {
  345. if (BeforeEmitCompile != null)
  346. {
  347. BeforeEmitCompile.Invoke(sender, e);
  348. }
  349. }
  350. #endif
  351. #endregion Internal Methods
  352. #region Private Methods
  353. private static string GetTempFileName()
  354. {
  355. return Path.Combine(GetTempFolder(), SystemFake.DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss-") + Path.GetRandomFileName());
  356. }
  357. private static string GetTempPath()
  358. {
  359. if (!string.IsNullOrEmpty(systemTempFolder))
  360. return systemTempFolder;
  361. systemTempFolder = Environment.GetEnvironmentVariable("TMP");
  362. if (string.IsNullOrEmpty(systemTempFolder))
  363. systemTempFolder = Environment.GetEnvironmentVariable("TEMP");
  364. if (string.IsNullOrEmpty(systemTempFolder))
  365. systemTempFolder = Environment.GetEnvironmentVariable("TMPDIR");
  366. if (string.IsNullOrEmpty(systemTempFolder))
  367. systemTempFolder = Path.GetTempPath();
  368. return systemTempFolder;
  369. }
  370. static partial void SaveConnectionStringVisible();
  371. private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
  372. {
  373. FDoc.Root.Name = "Config";
  374. FDoc.AutoIndent = true;
  375. SaveUIStyle();
  376. SaveUIOptions();
  377. SaveCompilerSettings();
  378. SaveAuthServiceUser();
  379. SaveConnectionStringVisible();
  380. #if !COMMUNITY
  381. SaveExportOptions();
  382. #endif
  383. if (!WebMode)
  384. {
  385. try
  386. {
  387. if (!Directory.Exists(Folder))
  388. Directory.CreateDirectory(Folder);
  389. string configFile = Path.Combine(Folder, CONFIG_NAME);
  390. if (CleanupOnExit)
  391. {
  392. File.Delete(configFile);
  393. }
  394. else
  395. {
  396. FDoc.Save(configFile);
  397. }
  398. if (FLogs != "")
  399. File.WriteAllText(Path.Combine(Folder, "FastReport.logs"), FLogs);
  400. }
  401. catch
  402. {
  403. }
  404. }
  405. }
  406. static partial void RestoreConnectionStringVisible();
  407. private static void LoadConfig()
  408. {
  409. bool configLoaded = false;
  410. if (!Config.WebMode)
  411. {
  412. try
  413. {
  414. if (Folder == null)
  415. {
  416. string baseFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
  417. Folder = Path.Combine(baseFolder, "FastReport");
  418. }
  419. else if (Folder == "")
  420. Folder = ApplicationFolder;
  421. }
  422. catch
  423. {
  424. }
  425. string fileName = Path.Combine(Folder, CONFIG_NAME);
  426. if (File.Exists(fileName))
  427. {
  428. try
  429. {
  430. FDoc.Load(fileName);
  431. configLoaded = true;
  432. }
  433. catch
  434. {
  435. }
  436. }
  437. RestoreUIStyle();
  438. RestoreDefaultLanguage();
  439. RestoreUIOptions();
  440. RestoreCompilerSettings();
  441. Res.LoadDefaultLocale();
  442. RestoreAuthServiceUser();
  443. RestoreConnectionStringVisible();
  444. AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
  445. }
  446. if (!configLoaded)
  447. {
  448. // load default config
  449. using (Stream stream = ResourceLoader.GetStream("FastReport.config"))
  450. {
  451. FDoc.Load(stream);
  452. }
  453. }
  454. }
  455. private static void LoadPlugins()
  456. {
  457. // main assembly initializer
  458. ProcessMainAssembly();
  459. XmlItem pluginsItem = Root.FindItem("Plugins");
  460. for (int i = 0; i < pluginsItem.Count; i++)
  461. {
  462. XmlItem item = pluginsItem[i];
  463. string pluginName = item.GetProp("Name");
  464. try
  465. {
  466. var assembly = Assembly.LoadFrom(pluginName);
  467. ProcessAssembly(assembly);
  468. }
  469. catch
  470. {
  471. }
  472. }
  473. // For CoreWin
  474. #if (COREWIN || AVALONIA)
  475. LoadPluginsInCurrentFolder();
  476. #endif
  477. }
  478. private static void ProcessAssembly(Assembly a)
  479. {
  480. foreach (Type t in a.GetTypes())
  481. {
  482. if (t.IsSubclassOf(typeof(AssemblyInitializerBase)))
  483. Activator.CreateInstance(t);
  484. }
  485. }
  486. private static void RestoreDefaultLanguage()
  487. {
  488. var storage = new StorageService("Designer,Code");
  489. ReportSettings.DefaultLanguage = storage.GetEnum("DefaultScriptLanguage", Language.CSharp);
  490. }
  491. private static void RestoreRightToLeft()
  492. {
  493. XmlItem xi = Root.FindItem("UIOptions");
  494. string rtl = xi.GetProp("RightToLeft");
  495. if (!String.IsNullOrEmpty(rtl))
  496. {
  497. switch (rtl)
  498. {
  499. case "Auto":
  500. RightToLeft = CultureInfo.CurrentCulture.TextInfo.IsRightToLeft;
  501. break;
  502. case "No":
  503. RightToLeft = false;
  504. break;
  505. case "Yes":
  506. RightToLeft = true;
  507. break;
  508. default:
  509. RightToLeft = false;
  510. break;
  511. }
  512. }
  513. }
  514. /// <summary>
  515. /// Properties of ScriptSecurity
  516. /// </summary>
  517. public class ScriptSecurityProperties
  518. {
  519. private static readonly string[] defaultStopList = new[]
  520. {
  521. "GetType",
  522. "typeof",
  523. "TypeOf", // VB
  524. "DllImport",
  525. "LoadLibrary",
  526. "GetProcAddress",
  527. };
  528. private string[] stopList;
  529. /// <summary>
  530. /// Add stubs for the most dangerous classes (in System.IO, System.Reflection etc)
  531. /// </summary>
  532. public bool AddStubClasses { get; set; } = true;
  533. /// <summary>
  534. /// List of keywords that shouldn't be declared in the report script
  535. /// </summary>
  536. public string[] StopList
  537. {
  538. get { return (string[])stopList.Clone(); }
  539. set
  540. {
  541. if (value != null)
  542. {
  543. OnStopListChanged?.Invoke(this, null);
  544. stopList = value;
  545. }
  546. }
  547. }
  548. /// <summary>
  549. /// Throws when <see cref="StopList"/> has changed
  550. /// </summary>
  551. public event EventHandler OnStopListChanged;
  552. internal ScriptSecurityProperties()
  553. {
  554. SetDefaultStopList();
  555. }
  556. internal ScriptSecurityProperties(string[] stopList)
  557. {
  558. this.stopList = stopList;
  559. }
  560. /// <summary>
  561. /// Sets default value for <see cref="StopList"/>
  562. /// </summary>
  563. public void SetDefaultStopList()
  564. {
  565. StopList = defaultStopList;
  566. }
  567. }
  568. private static void SaveCompilerSettings()
  569. {
  570. var storage = new StorageService("CompilerSettings");
  571. storage.SetStr("Placeholder", CompilerSettings.Placeholder);
  572. storage.SetEnum("ExceptionBehaviour", CompilerSettings.ExceptionBehaviour);
  573. }
  574. private static void RestoreCompilerSettings()
  575. {
  576. var storage = new StorageService("CompilerSettings");
  577. CompilerSettings.Placeholder = storage.GetStr("Placeholder");
  578. CompilerSettings.ExceptionBehaviour = storage.GetEnum("ExceptionBehaviour", CompilerExceptionBehaviour.Default);
  579. }
  580. #endregion Private Methods
  581. }
  582. }