App.xaml.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. using MediaBrowser.ApiInteraction;
  2. using MediaBrowser.ClickOnce;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.IO;
  5. using MediaBrowser.Common.Kernel;
  6. using MediaBrowser.IsoMounter;
  7. using MediaBrowser.Logging.Nlog;
  8. using MediaBrowser.Model.Configuration;
  9. using MediaBrowser.Model.Dto;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Net;
  12. using MediaBrowser.Model.Updates;
  13. using MediaBrowser.Model.Weather;
  14. using MediaBrowser.UI.Controller;
  15. using MediaBrowser.UI.Controls;
  16. using MediaBrowser.UI.Pages;
  17. using MediaBrowser.UI.Uninstall;
  18. using Microsoft.Win32;
  19. using System;
  20. using System.Collections.Generic;
  21. using System.ComponentModel;
  22. using System.IO;
  23. using System.Linq;
  24. using System.Net.Cache;
  25. using System.Threading;
  26. using System.Threading.Tasks;
  27. using System.Windows;
  28. using System.Windows.Controls;
  29. using System.Windows.Media;
  30. using System.Windows.Media.Imaging;
  31. namespace MediaBrowser.UI
  32. {
  33. /// <summary>
  34. /// Interaction logic for App.xaml
  35. /// </summary>
  36. public partial class App : Application, IApplicationHost
  37. {
  38. /// <summary>
  39. /// Gets or sets a value indicating whether [last run at startup value].
  40. /// </summary>
  41. /// <value><c>null</c> if [last run at startup value] contains no value, <c>true</c> if [last run at startup value]; otherwise, <c>false</c>.</value>
  42. private bool? LastRunAtStartupValue { get; set; }
  43. /// <summary>
  44. /// Gets or sets the clock timer.
  45. /// </summary>
  46. /// <value>The clock timer.</value>
  47. private Timer ClockTimer { get; set; }
  48. /// <summary>
  49. /// Gets or sets the server configuration timer.
  50. /// </summary>
  51. /// <value>The server configuration timer.</value>
  52. private Timer ServerConfigurationTimer { get; set; }
  53. /// <summary>
  54. /// The single instance mutex
  55. /// </summary>
  56. private Mutex SingleInstanceMutex;
  57. /// <summary>
  58. /// Gets or sets the kernel.
  59. /// </summary>
  60. /// <value>The kernel.</value>
  61. protected IKernel Kernel { get; set; }
  62. /// <summary>
  63. /// Gets or sets the logger.
  64. /// </summary>
  65. /// <value>The logger.</value>
  66. protected ILogger Logger { get; set; }
  67. /// <summary>
  68. /// Gets or sets the log file path.
  69. /// </summary>
  70. /// <value>The log file path.</value>
  71. public string LogFilePath { get; private set; }
  72. /// <summary>
  73. /// Occurs when [property changed].
  74. /// </summary>
  75. public event PropertyChangedEventHandler PropertyChanged;
  76. /// <summary>
  77. /// Gets the name of the product.
  78. /// </summary>
  79. /// <value>The name of the product.</value>
  80. protected string ProductName
  81. {
  82. get { return Globals.ProductName; }
  83. }
  84. /// <summary>
  85. /// Gets the name of the publisher.
  86. /// </summary>
  87. /// <value>The name of the publisher.</value>
  88. protected string PublisherName
  89. {
  90. get { return Globals.PublisherName; }
  91. }
  92. /// <summary>
  93. /// Gets the name of the suite.
  94. /// </summary>
  95. /// <value>The name of the suite.</value>
  96. protected string SuiteName
  97. {
  98. get { return Globals.SuiteName; }
  99. }
  100. /// <summary>
  101. /// Gets the name of the uninstaller file.
  102. /// </summary>
  103. /// <value>The name of the uninstaller file.</value>
  104. protected string UninstallerFileName
  105. {
  106. get { return "MediaBrowser.UI.Uninstall.exe"; }
  107. }
  108. /// <summary>
  109. /// Gets the instance.
  110. /// </summary>
  111. /// <value>The instance.</value>
  112. public static App Instance
  113. {
  114. get
  115. {
  116. return Current as App;
  117. }
  118. }
  119. /// <summary>
  120. /// Gets the API client.
  121. /// </summary>
  122. /// <value>The API client.</value>
  123. public ApiClient ApiClient
  124. {
  125. get { return UIKernel.Instance.ApiClient; }
  126. }
  127. /// <summary>
  128. /// Gets the application window.
  129. /// </summary>
  130. /// <value>The application window.</value>
  131. public MainWindow ApplicationWindow { get; private set; }
  132. /// <summary>
  133. /// Gets the hidden window.
  134. /// </summary>
  135. /// <value>The hidden window.</value>
  136. public HiddenWindow HiddenWindow { get; private set; }
  137. /// <summary>
  138. /// The _current user
  139. /// </summary>
  140. private UserDto _currentUser;
  141. /// <summary>
  142. /// Gets or sets the current user.
  143. /// </summary>
  144. /// <value>The current user.</value>
  145. public UserDto CurrentUser
  146. {
  147. get
  148. {
  149. return _currentUser;
  150. }
  151. set
  152. {
  153. _currentUser = value;
  154. if (UIKernel.Instance.ApiClient != null)
  155. {
  156. if (value == null)
  157. {
  158. UIKernel.Instance.ApiClient.CurrentUserId = null;
  159. }
  160. else
  161. {
  162. UIKernel.Instance.ApiClient.CurrentUserId = value.Id;
  163. }
  164. }
  165. OnPropertyChanged("CurrentUser");
  166. }
  167. }
  168. /// <summary>
  169. /// The _server configuration
  170. /// </summary>
  171. private ServerConfiguration _serverConfiguration;
  172. /// <summary>
  173. /// Gets or sets the server configuration.
  174. /// </summary>
  175. /// <value>The server configuration.</value>
  176. public ServerConfiguration ServerConfiguration
  177. {
  178. get
  179. {
  180. return _serverConfiguration;
  181. }
  182. set
  183. {
  184. _serverConfiguration = value;
  185. OnPropertyChanged("ServerConfiguration");
  186. }
  187. }
  188. /// <summary>
  189. /// The _current time
  190. /// </summary>
  191. private DateTime _currentTime = DateTime.Now;
  192. /// <summary>
  193. /// Gets the current time.
  194. /// </summary>
  195. /// <value>The current time.</value>
  196. public DateTime CurrentTime
  197. {
  198. get
  199. {
  200. return _currentTime;
  201. }
  202. private set
  203. {
  204. _currentTime = value;
  205. OnPropertyChanged("CurrentTime");
  206. }
  207. }
  208. /// <summary>
  209. /// The _current weather
  210. /// </summary>
  211. private WeatherInfo _currentWeather;
  212. /// <summary>
  213. /// Gets the current weather.
  214. /// </summary>
  215. /// <value>The current weather.</value>
  216. public WeatherInfo CurrentWeather
  217. {
  218. get
  219. {
  220. return _currentWeather;
  221. }
  222. private set
  223. {
  224. _currentWeather = value;
  225. OnPropertyChanged("CurrentWeather");
  226. }
  227. }
  228. /// <summary>
  229. /// The _current theme
  230. /// </summary>
  231. private BaseTheme _currentTheme;
  232. /// <summary>
  233. /// Gets the current theme.
  234. /// </summary>
  235. /// <value>The current theme.</value>
  236. public BaseTheme CurrentTheme
  237. {
  238. get
  239. {
  240. return _currentTheme;
  241. }
  242. private set
  243. {
  244. _currentTheme = value;
  245. OnPropertyChanged("CurrentTheme");
  246. }
  247. }
  248. /// <summary>
  249. /// Defines the entry point of the application.
  250. /// </summary>
  251. [STAThread]
  252. public static void Main()
  253. {
  254. var application = new App(new NLogger("App"));
  255. application.InitializeComponent();
  256. application.Run();
  257. }
  258. /// <summary>
  259. /// Initializes a new instance of the <see cref="App" /> class.
  260. /// </summary>
  261. /// <param name="logger">The logger.</param>
  262. public App(ILogger logger)
  263. {
  264. Logger = logger;
  265. InitializeComponent();
  266. }
  267. /// <summary>
  268. /// Instantiates the kernel.
  269. /// </summary>
  270. /// <returns>IKernel.</returns>
  271. protected IKernel InstantiateKernel()
  272. {
  273. return new UIKernel(this, new PismoIsoManager(Logger), Logger);
  274. }
  275. /// <summary>
  276. /// Instantiates the main window.
  277. /// </summary>
  278. /// <returns>Window.</returns>
  279. protected Window InstantiateMainWindow()
  280. {
  281. HiddenWindow = new HiddenWindow { };
  282. return HiddenWindow;
  283. }
  284. /// <summary>
  285. /// Shows the application window.
  286. /// </summary>
  287. private void ShowApplicationWindow()
  288. {
  289. var win = new MainWindow(Logger);
  290. var config = UIKernel.Instance.Configuration;
  291. // Restore window position/size
  292. if (config.WindowState.HasValue)
  293. {
  294. // Set window state
  295. win.WindowState = config.WindowState.Value;
  296. // Set position if not maximized
  297. if (config.WindowState.Value != WindowState.Maximized)
  298. {
  299. double left = 0;
  300. double top = 0;
  301. // Set left
  302. if (config.WindowLeft.HasValue)
  303. {
  304. win.WindowStartupLocation = WindowStartupLocation.Manual;
  305. win.Left = left = Math.Max(config.WindowLeft.Value, 0);
  306. }
  307. // Set top
  308. if (config.WindowTop.HasValue)
  309. {
  310. win.WindowStartupLocation = WindowStartupLocation.Manual;
  311. win.Top = top = Math.Max(config.WindowTop.Value, 0);
  312. }
  313. // Set width
  314. if (config.WindowWidth.HasValue)
  315. {
  316. win.Width = Math.Min(config.WindowWidth.Value, SystemParameters.VirtualScreenWidth - left);
  317. }
  318. // Set height
  319. if (config.WindowHeight.HasValue)
  320. {
  321. win.Height = Math.Min(config.WindowHeight.Value, SystemParameters.VirtualScreenHeight - top);
  322. }
  323. }
  324. }
  325. win.LocationChanged += ApplicationWindow_LocationChanged;
  326. win.StateChanged += ApplicationWindow_LocationChanged;
  327. win.SizeChanged += ApplicationWindow_LocationChanged;
  328. ApplicationWindow = win;
  329. ApplicationWindow.Show();
  330. ApplicationWindow.Owner = HiddenWindow;
  331. SyncHiddenWindowLocation();
  332. }
  333. /// <summary>
  334. /// Handles the LocationChanged event of the ApplicationWindow control.
  335. /// </summary>
  336. /// <param name="sender">The source of the event.</param>
  337. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  338. void ApplicationWindow_LocationChanged(object sender, EventArgs e)
  339. {
  340. SyncHiddenWindowLocation();
  341. }
  342. /// <summary>
  343. /// Syncs the hidden window location.
  344. /// </summary>
  345. public void SyncHiddenWindowLocation()
  346. {
  347. HiddenWindow.Width = ApplicationWindow.Width;
  348. HiddenWindow.Height = ApplicationWindow.Height;
  349. HiddenWindow.Top = ApplicationWindow.Top;
  350. HiddenWindow.Left = ApplicationWindow.Left;
  351. HiddenWindow.WindowState = ApplicationWindow.WindowState;
  352. ApplicationWindow.Activate();
  353. }
  354. /// <summary>
  355. /// Loads the kernel.
  356. /// </summary>
  357. protected async void LoadKernel()
  358. {
  359. // Without this the app will shutdown after the splash screen closes
  360. ShutdownMode = ShutdownMode.OnExplicitShutdown;
  361. Kernel = InstantiateKernel();
  362. try
  363. {
  364. var now = DateTime.UtcNow;
  365. await Kernel.Init();
  366. Logger.Info("Kernel.Init completed in {0} seconds.", (DateTime.UtcNow - now).TotalSeconds);
  367. ShutdownMode = System.Windows.ShutdownMode.OnLastWindowClose;
  368. OnKernelLoaded();
  369. InstantiateMainWindow().Show();
  370. ShowApplicationWindow();
  371. await ApplicationWindow.LoadInitialUI().ConfigureAwait(false);
  372. }
  373. catch (Exception ex)
  374. {
  375. Logger.ErrorException("Error launching application", ex);
  376. MessageBox.Show("There was an error launching Media Browser: " + ex.Message);
  377. // Shutdown the app with an error code
  378. Shutdown(1);
  379. }
  380. }
  381. /// <summary>
  382. /// Called when [kernel loaded].
  383. /// </summary>
  384. /// <returns>Task.</returns>
  385. protected void OnKernelLoaded()
  386. {
  387. Kernel.ConfigurationUpdated += Kernel_ConfigurationUpdated;
  388. ConfigureClickOnceStartup();
  389. PropertyChanged += AppPropertyChanged;
  390. // Update every 10 seconds
  391. ClockTimer = new Timer(ClockTimerCallback, null, 0, 10000);
  392. // Update every 30 minutes
  393. ServerConfigurationTimer = new Timer(ServerConfigurationTimerCallback, null, 0, 1800000);
  394. CurrentTheme = UIKernel.Instance.Themes.First();
  395. foreach (var resource in CurrentTheme.GetGlobalResources())
  396. {
  397. Resources.MergedDictionaries.Add(resource);
  398. }
  399. }
  400. /// <summary>
  401. /// Raises the <see cref="E:System.Windows.Application.Startup" /> event.
  402. /// </summary>
  403. /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param>
  404. protected override void OnStartup(StartupEventArgs e)
  405. {
  406. bool createdNew;
  407. SingleInstanceMutex = new Mutex(true, @"Local\" + GetType().Assembly.GetName().Name, out createdNew);
  408. if (!createdNew)
  409. {
  410. SingleInstanceMutex = null;
  411. Shutdown();
  412. return;
  413. }
  414. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  415. LoadKernel();
  416. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  417. }
  418. /// <summary>
  419. /// Handles the UnhandledException event of the CurrentDomain control.
  420. /// </summary>
  421. /// <param name="sender">The source of the event.</param>
  422. /// <param name="e">The <see cref="UnhandledExceptionEventArgs" /> instance containing the event data.</param>
  423. void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  424. {
  425. var exception = (Exception)e.ExceptionObject;
  426. Logger.ErrorException("UnhandledException", exception);
  427. MessageBox.Show("Unhandled exception: " + exception.Message);
  428. }
  429. /// <summary>
  430. /// Called when [property changed].
  431. /// </summary>
  432. /// <param name="info">The info.</param>
  433. public void OnPropertyChanged(String info)
  434. {
  435. if (PropertyChanged != null)
  436. {
  437. try
  438. {
  439. PropertyChanged(this, new PropertyChangedEventArgs(info));
  440. }
  441. catch (Exception ex)
  442. {
  443. Logger.ErrorException("Error in event handler", ex);
  444. }
  445. }
  446. }
  447. /// <summary>
  448. /// Handles the SessionEnding event of the SystemEvents control.
  449. /// </summary>
  450. /// <param name="sender">The source of the event.</param>
  451. /// <param name="e">The <see cref="SessionEndingEventArgs" /> instance containing the event data.</param>
  452. void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  453. {
  454. // Try to shut down gracefully
  455. Shutdown();
  456. }
  457. /// <summary>
  458. /// Raises the <see cref="E:System.Windows.Application.Exit" /> event.
  459. /// </summary>
  460. /// <param name="e">An <see cref="T:System.Windows.ExitEventArgs" /> that contains the event data.</param>
  461. protected override void OnExit(ExitEventArgs e)
  462. {
  463. var win = ApplicationWindow;
  464. if (win != null)
  465. {
  466. // Save window position
  467. var config = UIKernel.Instance.Configuration;
  468. config.WindowState = win.WindowState;
  469. config.WindowTop = win.Top;
  470. config.WindowLeft = win.Left;
  471. config.WindowWidth = win.Width;
  472. config.WindowHeight = win.Height;
  473. UIKernel.Instance.SaveConfiguration();
  474. }
  475. ReleaseMutex();
  476. base.OnExit(e);
  477. Kernel.Dispose();
  478. }
  479. /// <summary>
  480. /// Releases the mutex.
  481. /// </summary>
  482. private void ReleaseMutex()
  483. {
  484. if (SingleInstanceMutex == null)
  485. {
  486. return;
  487. }
  488. SingleInstanceMutex.ReleaseMutex();
  489. SingleInstanceMutex.Close();
  490. SingleInstanceMutex.Dispose();
  491. SingleInstanceMutex = null;
  492. }
  493. /// <summary>
  494. /// Apps the property changed.
  495. /// </summary>
  496. /// <param name="sender">The sender.</param>
  497. /// <param name="e">The <see cref="PropertyChangedEventArgs" /> instance containing the event data.</param>
  498. async void AppPropertyChanged(object sender, PropertyChangedEventArgs e)
  499. {
  500. if (e.PropertyName.Equals("ServerConfiguration"))
  501. {
  502. if (string.IsNullOrEmpty(ServerConfiguration.WeatherLocation))
  503. {
  504. CurrentWeather = null;
  505. }
  506. else
  507. {
  508. try
  509. {
  510. CurrentWeather = await ApiClient.GetWeatherInfoAsync(ServerConfiguration.WeatherLocation);
  511. }
  512. catch (HttpException ex)
  513. {
  514. Logger.ErrorException("Error downloading weather information", ex);
  515. }
  516. }
  517. }
  518. }
  519. /// <summary>
  520. /// Clocks the timer callback.
  521. /// </summary>
  522. /// <param name="stateInfo">The state info.</param>
  523. private void ClockTimerCallback(object stateInfo)
  524. {
  525. CurrentTime = DateTime.Now;
  526. }
  527. /// <summary>
  528. /// Servers the configuration timer callback.
  529. /// </summary>
  530. /// <param name="stateInfo">The state info.</param>
  531. private async void ServerConfigurationTimerCallback(object stateInfo)
  532. {
  533. try
  534. {
  535. ServerConfiguration = await ApiClient.GetServerConfigurationAsync();
  536. }
  537. catch (HttpException ex)
  538. {
  539. Logger.ErrorException("Error refreshing server configuration", ex);
  540. }
  541. }
  542. /// <summary>
  543. /// Logouts the user.
  544. /// </summary>
  545. /// <returns>Task.</returns>
  546. public async Task LogoutUser()
  547. {
  548. CurrentUser = null;
  549. await Dispatcher.InvokeAsync(() => Navigate(CurrentTheme.GetLoginPage()));
  550. }
  551. /// <summary>
  552. /// Navigates the specified page.
  553. /// </summary>
  554. /// <param name="page">The page.</param>
  555. public void Navigate(Page page)
  556. {
  557. _remoteImageCache = new FileSystemRepository(UIKernel.Instance.ApplicationPaths.RemoteImageCachePath);
  558. ApplicationWindow.Navigate(page);
  559. }
  560. /// <summary>
  561. /// Navigates to settings page.
  562. /// </summary>
  563. public void NavigateToSettingsPage()
  564. {
  565. Navigate(new SettingsPage());
  566. }
  567. /// <summary>
  568. /// Navigates to internal player page.
  569. /// </summary>
  570. public void NavigateToInternalPlayerPage()
  571. {
  572. Navigate(CurrentTheme.GetInternalPlayerPage());
  573. }
  574. /// <summary>
  575. /// Navigates to image viewer.
  576. /// </summary>
  577. /// <param name="imageUrl">The image URL.</param>
  578. /// <param name="caption">The caption.</param>
  579. public void OpenImageViewer(Uri imageUrl, string caption)
  580. {
  581. var tuple = new Tuple<Uri, string>(imageUrl, caption);
  582. OpenImageViewer(new[] { tuple });
  583. }
  584. /// <summary>
  585. /// Navigates to image viewer.
  586. /// </summary>
  587. /// <param name="images">The images.</param>
  588. public void OpenImageViewer(IEnumerable<Tuple<Uri, string>> images)
  589. {
  590. new ImageViewerWindow(images).ShowModal(ApplicationWindow);
  591. }
  592. /// <summary>
  593. /// Navigates to item.
  594. /// </summary>
  595. /// <param name="item">The item.</param>
  596. public void NavigateToItem(BaseItemDto item)
  597. {
  598. if (item.IsRoot.HasValue && item.IsRoot.Value)
  599. {
  600. NavigateToHomePage();
  601. }
  602. else if (item.IsFolder)
  603. {
  604. Navigate(CurrentTheme.GetListPage(item));
  605. }
  606. else
  607. {
  608. Navigate(CurrentTheme.GetDetailPage(item));
  609. }
  610. }
  611. /// <summary>
  612. /// Displays the weather.
  613. /// </summary>
  614. public void DisplayWeather()
  615. {
  616. CurrentTheme.DisplayWeather();
  617. }
  618. /// <summary>
  619. /// Navigates to home page.
  620. /// </summary>
  621. public void NavigateToHomePage()
  622. {
  623. Navigate(CurrentTheme.GetHomePage());
  624. }
  625. /// <summary>
  626. /// Shows a notification message that will disappear on it's own
  627. /// </summary>
  628. /// <param name="text">The text.</param>
  629. /// <param name="caption">The caption.</param>
  630. /// <param name="icon">The icon.</param>
  631. public void ShowNotificationMessage(string text, string caption = null, MessageBoxIcon icon = MessageBoxIcon.None)
  632. {
  633. ApplicationWindow.ShowModalMessage(text, caption: caption, icon: icon);
  634. }
  635. /// <summary>
  636. /// Shows a notification message that will disappear on it's own
  637. /// </summary>
  638. /// <param name="text">The text.</param>
  639. /// <param name="caption">The caption.</param>
  640. /// <param name="icon">The icon.</param>
  641. public void ShowNotificationMessage(UIElement text, string caption = null, MessageBoxIcon icon = MessageBoxIcon.None)
  642. {
  643. ApplicationWindow.ShowModalMessage(text, caption: caption, icon: icon);
  644. }
  645. /// <summary>
  646. /// Shows a modal message box and asynchronously returns a MessageBoxResult
  647. /// </summary>
  648. /// <param name="text">The text.</param>
  649. /// <param name="caption">The caption.</param>
  650. /// <param name="button">The button.</param>
  651. /// <param name="icon">The icon.</param>
  652. /// <returns>MessageBoxResult.</returns>
  653. public MessageBoxResult ShowModalMessage(string text, string caption = null, MessageBoxButton button = MessageBoxButton.OK, MessageBoxIcon icon = MessageBoxIcon.None)
  654. {
  655. return ApplicationWindow.ShowModalMessage(text, caption: caption, button: button, icon: icon);
  656. }
  657. /// <summary>
  658. /// Shows a modal message box and asynchronously returns a MessageBoxResult
  659. /// </summary>
  660. /// <param name="text">The text.</param>
  661. /// <param name="caption">The caption.</param>
  662. /// <param name="button">The button.</param>
  663. /// <param name="icon">The icon.</param>
  664. /// <returns>MessageBoxResult.</returns>
  665. public MessageBoxResult ShowModalMessage(UIElement text, string caption = null, MessageBoxButton button = MessageBoxButton.OK, MessageBoxIcon icon = MessageBoxIcon.None)
  666. {
  667. return ApplicationWindow.ShowModalMessage(text, caption: caption, button: button, icon: icon);
  668. }
  669. /// <summary>
  670. /// Shows the error message.
  671. /// </summary>
  672. /// <param name="message">The message.</param>
  673. /// <param name="caption">The caption.</param>
  674. public void ShowErrorMessage(string message, string caption = null)
  675. {
  676. caption = caption ?? "Error";
  677. ShowModalMessage(message, caption: caption, button: MessageBoxButton.OK, icon: MessageBoxIcon.Error);
  678. }
  679. /// <summary>
  680. /// Shows the default error message.
  681. /// </summary>
  682. public void ShowDefaultErrorMessage()
  683. {
  684. ShowErrorMessage("There was an error processing the request", "Error");
  685. }
  686. /// <summary>
  687. /// The _remote image cache
  688. /// </summary>
  689. private FileSystemRepository _remoteImageCache;
  690. /// <summary>
  691. /// Gets the remote image async.
  692. /// </summary>
  693. /// <param name="url">The URL.</param>
  694. /// <returns>Task{Image}.</returns>
  695. public async Task<Image> GetRemoteImageAsync(string url)
  696. {
  697. var bitmap = await GetRemoteBitmapAsync(url);
  698. return new Image { Source = bitmap };
  699. }
  700. /// <summary>
  701. /// Gets the remote image async.
  702. /// </summary>
  703. /// <param name="url">The URL.</param>
  704. /// <returns>Task{BitmapImage}.</returns>
  705. /// <exception cref="System.ArgumentNullException">url</exception>
  706. public Task<BitmapImage> GetRemoteBitmapAsync(string url)
  707. {
  708. if (string.IsNullOrEmpty(url))
  709. {
  710. throw new ArgumentNullException("url");
  711. }
  712. Logger.Info("Image url: " + url);
  713. return Task.Run(async () =>
  714. {
  715. var cachePath = _remoteImageCache.GetResourcePath(url.GetMD5().ToString());
  716. await _remoteImageCache.WaitForLockAsync(cachePath).ConfigureAwait(false);
  717. var releaseLock = true;
  718. try
  719. {
  720. using (var stream = new FileStream(cachePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
  721. {
  722. return await GetRemoteBitmapAsync(stream).ConfigureAwait(false);
  723. }
  724. }
  725. catch (FileNotFoundException)
  726. {
  727. // Doesn't exist. No biggie
  728. releaseLock = false;
  729. }
  730. finally
  731. {
  732. if (releaseLock)
  733. {
  734. _remoteImageCache.ReleaseLock(cachePath);
  735. }
  736. }
  737. try
  738. {
  739. using (var httpStream = await UIKernel.Instance.ApiClient.GetImageStreamAsync(url + "&x=1"))
  740. {
  741. return await GetRemoteBitmapAsync(httpStream, cachePath);
  742. }
  743. }
  744. finally
  745. {
  746. _remoteImageCache.ReleaseLock(cachePath);
  747. }
  748. });
  749. }
  750. /// <summary>
  751. /// Gets the image async.
  752. /// </summary>
  753. /// <param name="sourceStream">The source stream.</param>
  754. /// <param name="cachePath">The cache path.</param>
  755. /// <returns>Task{BitmapImage}.</returns>
  756. private async Task<BitmapImage> GetRemoteBitmapAsync(Stream sourceStream, string cachePath = null)
  757. {
  758. byte[] bytes;
  759. using (var ms = new MemoryStream())
  760. {
  761. await sourceStream.CopyToAsync(ms).ConfigureAwait(false);
  762. bytes = ms.ToArray();
  763. }
  764. if (!string.IsNullOrEmpty(cachePath))
  765. {
  766. using (var fileStream = new FileStream(cachePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
  767. {
  768. await fileStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  769. }
  770. }
  771. using (Stream stream = new MemoryStream(bytes))
  772. {
  773. var bitmapImage = new BitmapImage
  774. {
  775. CreateOptions = BitmapCreateOptions.DelayCreation
  776. };
  777. bitmapImage.BeginInit();
  778. bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
  779. bitmapImage.StreamSource = stream;
  780. bitmapImage.EndInit();
  781. bitmapImage.Freeze();
  782. return bitmapImage;
  783. }
  784. }
  785. /// <summary>
  786. /// Handles the ConfigurationUpdated event of the Kernel control.
  787. /// </summary>
  788. /// <param name="sender">The source of the event.</param>
  789. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  790. void Kernel_ConfigurationUpdated(object sender, EventArgs e)
  791. {
  792. if (!LastRunAtStartupValue.HasValue || LastRunAtStartupValue.Value != Kernel.Configuration.RunAtStartup)
  793. {
  794. ConfigureClickOnceStartup();
  795. }
  796. }
  797. /// <summary>
  798. /// Configures the click once startup.
  799. /// </summary>
  800. private void ConfigureClickOnceStartup()
  801. {
  802. try
  803. {
  804. ClickOnceHelper.ConfigureClickOnceStartupIfInstalled(PublisherName, ProductName, SuiteName, Kernel.Configuration.RunAtStartup, UninstallerFileName);
  805. LastRunAtStartupValue = Kernel.Configuration.RunAtStartup;
  806. }
  807. catch (Exception ex)
  808. {
  809. Logger.ErrorException("Error configuring ClickOnce", ex);
  810. }
  811. }
  812. public void Restart()
  813. {
  814. Dispatcher.Invoke(ReleaseMutex);
  815. Kernel.Dispose();
  816. System.Windows.Forms.Application.Restart();
  817. Dispatcher.Invoke(Shutdown);
  818. }
  819. public void ReloadLogger()
  820. {
  821. LogFilePath = Path.Combine(Kernel.ApplicationPaths.LogDirectoryPath, "Server-" + DateTime.Now.Ticks + ".log");
  822. NlogManager.AddFileTarget(LogFilePath, Kernel.Configuration.EnableDebugLevelLogging);
  823. }
  824. /// <summary>
  825. /// Gets the bitmap image.
  826. /// </summary>
  827. /// <param name="uri">The URI.</param>
  828. /// <returns>BitmapImage.</returns>
  829. /// <exception cref="System.ArgumentNullException">uri</exception>
  830. public BitmapImage GetBitmapImage(string uri)
  831. {
  832. if (string.IsNullOrEmpty(uri))
  833. {
  834. throw new ArgumentNullException("uri");
  835. }
  836. return GetBitmapImage(new Uri(uri));
  837. }
  838. /// <summary>
  839. /// Gets the bitmap image.
  840. /// </summary>
  841. /// <param name="uri">The URI.</param>
  842. /// <returns>BitmapImage.</returns>
  843. /// <exception cref="System.ArgumentNullException">uri</exception>
  844. public BitmapImage GetBitmapImage(Uri uri)
  845. {
  846. if (uri == null)
  847. {
  848. throw new ArgumentNullException("uri");
  849. }
  850. var bitmap = new BitmapImage
  851. {
  852. CreateOptions = BitmapCreateOptions.DelayCreation,
  853. CacheOption = BitmapCacheOption.OnDemand,
  854. UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable)
  855. };
  856. bitmap.BeginInit();
  857. bitmap.UriSource = uri;
  858. bitmap.EndInit();
  859. RenderOptions.SetBitmapScalingMode(bitmap, BitmapScalingMode.Fant);
  860. return bitmap;
  861. }
  862. /// <summary>
  863. /// Gets or sets a value indicating whether this instance can self update.
  864. /// </summary>
  865. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  866. public bool CanSelfUpdate
  867. {
  868. get { return ClickOnceHelper.IsNetworkDeployed; }
  869. }
  870. /// <summary>
  871. /// Checks for update.
  872. /// </summary>
  873. /// <param name="cancellationToken">The cancellation token.</param>
  874. /// <param name="progress">The progress.</param>
  875. /// <returns>Task{CheckForUpdateResult}.</returns>
  876. public Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  877. {
  878. return new ApplicationUpdateCheck().CheckForApplicationUpdate(cancellationToken, progress);
  879. }
  880. /// <summary>
  881. /// Updates the application.
  882. /// </summary>
  883. /// <param name="cancellationToken">The cancellation token.</param>
  884. /// <param name="progress">The progress.</param>
  885. /// <returns>Task.</returns>
  886. public Task UpdateApplication(CancellationToken cancellationToken, IProgress<double> progress)
  887. {
  888. return new ApplicationUpdater().UpdateApplication(cancellationToken, progress);
  889. }
  890. }
  891. }