Advertisement
Guest User

Untitled

a guest
Feb 8th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.00 KB | None | 0 0
  1. public static class IWindowManagerExtensions
  2. {
  3. /// <summary>
  4. /// Opens an Alert modal window
  5. /// </summary>
  6. public static void Alert(this IWindowManager windowManager, string title, string message)
  7. {
  8. TelerikWindowManager.Alert(title, message);
  9. }
  10.  
  11. /// <summary>
  12. /// Opens an Alert modal window
  13. /// </summary>
  14. public static void Alert(this IWindowManager windowManager, DialogParameters dialogParameters)
  15. {
  16. TelerikWindowManager.Alert(dialogParameters);
  17. }
  18.  
  19. /// <summary>
  20. /// Opens a Confirm modal window
  21. /// </summary>
  22. public static void Confirm(this IWindowManager windowManager, string title, string message, System.Action onOK, System.Action onCancel = null)
  23. {
  24. TelerikWindowManager.Confirm(title, message, onOK, onCancel);
  25. }
  26.  
  27. /// <summary>
  28. /// Opens a Confirm modal window
  29. /// </summary>
  30. public static void Confirm(this IWindowManager windowManager, DialogParameters dialogParameters)
  31. {
  32. TelerikWindowManager.Confirm(dialogParameters);
  33. }
  34.  
  35. /// <summary>
  36. /// Opens a Prompt modal window
  37. /// </summary>
  38. public static void Prompt(this IWindowManager windowManager, string title, string message, string defaultPromptResultValue, Action<string> onOK)
  39. {
  40. TelerikWindowManager.Prompt(title, message, defaultPromptResultValue, onOK);
  41. }
  42.  
  43. /// <summary>
  44. /// Opens a Prompt modal window
  45. /// </summary>
  46. public static void Prompt(this IWindowManager windowManager, DialogParameters dialogParameters)
  47. {
  48. TelerikWindowManager.Prompt(dialogParameters);
  49. }
  50. }
  51.  
  52. public class TelerikWindowManager : WindowManager
  53. {
  54. public override bool? ShowDialog(object rootModel, object context = null, IDictionary<string, object> settings = null)
  55. {
  56. var viewType = ViewLocator.LocateTypeForModelType(rootModel.GetType(), null, null);
  57. if (typeof(RadWindow).IsAssignableFrom(viewType)
  58. || typeof(UserControl).IsAssignableFrom(viewType))
  59. {
  60. var radWindow = CreateRadWindow(rootModel, true, context, settings);
  61. radWindow.ShowDialog();
  62. return radWindow.DialogResult;
  63. }
  64.  
  65. return base.ShowDialog(rootModel, context, settings);
  66. }
  67.  
  68. public override void ShowWindow(object rootModel, object context = null, IDictionary<string, object> settings = null)
  69. {
  70. var viewType = ViewLocator.LocateTypeForModelType(rootModel.GetType(), null, null);
  71. if (typeof(RadWindow).IsAssignableFrom(viewType)
  72. || typeof(UserControl).IsAssignableFrom(viewType))
  73. {
  74. NavigationWindow navWindow = null;
  75.  
  76. if (Application.Current != null && Application.Current.MainWindow != null)
  77. {
  78. navWindow = Application.Current.MainWindow as NavigationWindow;
  79. }
  80.  
  81. if (navWindow != null)
  82. {
  83. var window = CreatePage(rootModel, context, settings);
  84. navWindow.Navigate(window);
  85. }
  86. else
  87. {
  88. CreateRadWindow(rootModel, false, context, settings).Show();
  89. }
  90. return;
  91. }
  92. base.ShowWindow(rootModel, context, settings);
  93. }
  94.  
  95.  
  96. /// <summary>
  97. /// Creates a window.
  98. /// </summary>
  99. /// <param name="rootModel">The view model.</param>
  100. /// <param name="isDialog">Whethor or not the window is being shown as a dialog.</param>
  101. /// <param name="context">The view context.</param>
  102. /// <param name="settings">The optional popup settings.</param>
  103. /// <returns>The window.</returns>
  104. protected virtual RadWindow CreateRadWindow(object rootModel, bool isDialog, object context, IDictionary<string, object> settings)
  105. {
  106. var view = EnsureRadWindow(rootModel, ViewLocator.LocateForModel(rootModel, null, context), isDialog);
  107. ViewModelBinder.Bind(rootModel, view, context);
  108.  
  109. var haveDisplayName = rootModel as IHaveDisplayName;
  110. if (haveDisplayName != null && !ConventionManager.HasBinding(view, RadWindow.HeaderProperty))
  111. {
  112. var binding = new Binding("DisplayName") { Mode = BindingMode.TwoWay };
  113. view.SetBinding(RadWindow.HeaderProperty, binding);
  114. }
  115.  
  116. ApplyRadWindowSettings(view, settings);
  117.  
  118. new RadWindowConductor(rootModel, view);
  119.  
  120. return view;
  121. }
  122.  
  123. bool ApplyRadWindowSettings(object target, IEnumerable<KeyValuePair<string, object>> settings)
  124. {
  125. if (settings != null)
  126. {
  127. var type = target.GetType();
  128.  
  129. foreach (var pair in settings)
  130. {
  131. var propertyInfo = type.GetProperty(pair.Key);
  132.  
  133. if (propertyInfo != null)
  134. {
  135. propertyInfo.SetValue(target, pair.Value, null);
  136. }
  137. }
  138.  
  139. return true;
  140. }
  141.  
  142. return false;
  143. }
  144.  
  145. /// <summary>
  146. /// Makes sure the view is a window is is wrapped by one.
  147. /// </summary>
  148. /// <param name="model">The view model.</param>
  149. /// <param name="view">The view.</param>
  150. /// <param name="isDialog">Whethor or not the window is being shown as a dialog.</param>
  151. /// <returns>The window.</returns>
  152. protected virtual RadWindow EnsureRadWindow(object model, object view, bool isDialog)
  153. {
  154. var window = view as RadWindow;
  155.  
  156. if (window == null)
  157. {
  158. var contentElement = view as FrameworkElement;
  159. if (contentElement == null)
  160. throw new ArgumentNullException("view");
  161.  
  162. window = new RadWindow
  163. {
  164. Content = view,
  165. SizeToContent = true,
  166. };
  167.  
  168. AdjustWindowAndContentSize(window, contentElement);
  169.  
  170. window.SetValue(View.IsGeneratedProperty, true);
  171.  
  172. var owner = GetActiveWindow();
  173. if (owner != null)
  174. {
  175. window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
  176. window.Owner = owner;
  177. }
  178. else
  179. {
  180. window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
  181. }
  182. }
  183. else
  184. {
  185. var owner = GetActiveWindow();
  186. if (owner != null && isDialog)
  187. {
  188. window.Owner = owner;
  189. }
  190. }
  191.  
  192. return window;
  193. }
  194.  
  195. /// <summary>
  196. /// Initializes Window size with values extracted by the view.
  197. ///
  198. /// Note:
  199. /// The real size of the content will be smaller than provided values.
  200. /// The form has the header (title) and border so they will take place.
  201. ///
  202. /// </summary>
  203. /// <param name="window">The RadWindow</param>
  204. /// <param name="view">The view</param>
  205. private static void AdjustWindowAndContentSize(RadWindow window, FrameworkElement view)
  206. {
  207. window.MinWidth = view.MinWidth;
  208. window.MaxWidth = view.MaxWidth;
  209. window.Width = view.Width;
  210. window.MinHeight = view.MinHeight;
  211. window.MaxHeight = view.MaxHeight;
  212. window.Height = view.Height;
  213.  
  214. // Resetting view's settings
  215. view.Width = view.Height = Double.NaN;
  216. view.MinWidth = view.MinHeight = 0;
  217. view.MaxWidth = view.MaxHeight = int.MaxValue;
  218.  
  219. // Stretching content to the Window
  220. view.VerticalAlignment = VerticalAlignment.Stretch;
  221. view.HorizontalAlignment = HorizontalAlignment.Stretch;
  222. }
  223.  
  224. /// <summary>
  225. /// Infers the owner of the window.
  226. /// </summary>
  227. /// <returns>The owner.</returns>
  228. protected virtual Window GetActiveWindow()
  229. {
  230. if (Application.Current == null)
  231. {
  232. return null;
  233. }
  234.  
  235. var active = Application.Current
  236. .Windows.OfType<Window>()
  237. .FirstOrDefault(x => x.IsActive);
  238.  
  239. return active ?? Application.Current.MainWindow;
  240. }
  241.  
  242. public static void Alert(string title, string message)
  243. {
  244. RadWindow.Alert(new DialogParameters { Header = title, Content = message });
  245. }
  246.  
  247. public static void Alert(DialogParameters dialogParameters)
  248. {
  249. RadWindow.Alert(dialogParameters);
  250. }
  251.  
  252. public static void Confirm(string title, string message, System.Action onOK, System.Action onCancel = null)
  253. {
  254. var dialogParameters = new DialogParameters
  255. {
  256. Header = title,
  257. Content = message
  258. };
  259. dialogParameters.Closed += (sender, args) =>
  260. {
  261. var result = args.DialogResult;
  262. if (result.HasValue && result.Value)
  263. {
  264. onOK();
  265. return;
  266. }
  267.  
  268. if (onCancel != null)
  269. onCancel();
  270. };
  271. Confirm(dialogParameters);
  272. }
  273.  
  274. public static void Confirm(DialogParameters dialogParameters)
  275. {
  276. RadWindow.Confirm(dialogParameters);
  277. }
  278.  
  279. public static void Prompt(string title, string message, string defaultPromptResultValue, Action<string> onOK)
  280. {
  281. var dialogParameters = new DialogParameters
  282. {
  283. Header = title,
  284. Content = message,
  285. DefaultPromptResultValue = defaultPromptResultValue,
  286. };
  287. dialogParameters.Closed += (o, args) =>
  288. {
  289. if (args.DialogResult.HasValue && args.DialogResult.Value)
  290. onOK(args.PromptResult);
  291. };
  292.  
  293. Prompt(dialogParameters);
  294. }
  295.  
  296. public static void Prompt(DialogParameters dialogParameters)
  297. {
  298. RadWindow.Prompt(dialogParameters);
  299. }
  300.  
  301. }
  302.  
  303. public RadWindowConductor(object model, RadWindow view)
  304. {
  305. this.model = model;
  306. this.view = view;
  307.  
  308. var activatable = model as IActivate;
  309. if (activatable != null)
  310. {
  311. activatable.Activate();
  312. }
  313.  
  314. var deactivatable = model as IDeactivate;
  315. if (deactivatable != null)
  316. {
  317. view.Closed += Closed;
  318. deactivatable.Deactivated += Deactivated;
  319. }
  320.  
  321. var guard = model as IGuardClose;
  322. if (guard != null)
  323. {
  324. view.PreviewClosed += PreviewClosed;
  325. }
  326. }
  327.  
  328. private void Closed(object sender, EventArgs e)
  329. {
  330. view.Closed -= Closed;
  331. view.PreviewClosed -= PreviewClosed;
  332.  
  333. if (deactivateFromViewModel)
  334. {
  335. return;
  336. }
  337.  
  338. var deactivatable = (IDeactivate)model;
  339.  
  340. deactivatingFromView = true;
  341. deactivatable.Deactivate(true);
  342. deactivatingFromView = false;
  343. }
  344.  
  345. private void Deactivated(object sender, DeactivationEventArgs e)
  346. {
  347. if (!e.WasClosed)
  348. {
  349. return;
  350. }
  351.  
  352. ((IDeactivate)model).Deactivated -= Deactivated;
  353.  
  354. if (deactivatingFromView)
  355. {
  356. return;
  357. }
  358.  
  359. deactivateFromViewModel = true;
  360. actuallyClosing = true;
  361. view.Close();
  362. actuallyClosing = false;
  363. deactivateFromViewModel = false;
  364. }
  365.  
  366. private void PreviewClosed(object sender, WindowPreviewClosedEventArgs e)
  367. {
  368. if (e.Cancel == true)
  369. {
  370. return;
  371. }
  372.  
  373. var guard = (IGuardClose)model;
  374.  
  375. if (actuallyClosing)
  376. {
  377. actuallyClosing = false;
  378. return;
  379. }
  380.  
  381. bool runningAsync = false, shouldEnd = false;
  382.  
  383. guard.CanClose(canClose =>
  384. {
  385. Execute.OnUIThread(() =>
  386. {
  387. if (runningAsync && canClose)
  388. {
  389. actuallyClosing = true;
  390. view.Close();
  391. }
  392. else
  393. {
  394. e.Cancel = !canClose;
  395. }
  396.  
  397. shouldEnd = true;
  398. });
  399. });
  400.  
  401. if (shouldEnd)
  402. {
  403. return;
  404. }
  405.  
  406. e.Cancel = true;
  407. runningAsync = true;
  408. }
  409. }
  410.  
  411. [Export, PartCreationPolicy(CreationPolicy.NonShared)]
  412. [ExportController("NewUserViewModel")]
  413. public class NewUserViewModel : FeatureWindowBase
  414. {
  415. #region Fields
  416. private User _creatingUser;
  417. private User _userToAdd;
  418. #endregion
  419.  
  420. #region Properties
  421.  
  422. public bool IsOpen;
  423.  
  424. public User UserToAdd
  425. {
  426. get
  427. {
  428. return _userToAdd;
  429.  
  430. }
  431. set
  432. {
  433. _userToAdd = value;
  434. NotifyOfPropertyChange(() => UserToAdd);
  435. }
  436. }
  437.  
  438. public IEnumerable<Entity> AddedUsers => new List<Entity>() { UserToAdd };
  439.  
  440. #endregion
  441.  
  442.  
  443. #region Constructors
  444.  
  445. [ImportingConstructor]
  446. public NewUserViewModel(IWindowManager windowManager,
  447. IEventAggregator eventAggregator,
  448. IEntityManagerProvider<BearPawEntities> entityManagerProvider,
  449. IGlobalCache globalCache) :
  450. base(windowManager, eventAggregator, entityManagerProvider, globalCache)
  451. {
  452. }
  453.  
  454. #endregion
  455.  
  456. protected override void OnViewLoaded(object view)
  457. {
  458. base.OnViewLoaded(view);
  459.  
  460. // un-comment the following if you want to use the Global Cache
  461. SetupGlobalCache<User>(Manager);
  462. _creatingUser = Manager.Users.FirstOrDefault(u => u.UserName ==
  463. Manager.AuthenticationContext.Principal.Identity
  464. .Name);
  465.  
  466. UserToAdd = new User()
  467. {
  468. CreatedBy = _creatingUser,
  469. CreatedDate = DateTime.Now,
  470. ModifiedBy = _creatingUser,
  471. ModifiedDate = DateTime.Now
  472. };
  473.  
  474. DisplayName = "Add New User";
  475. IsOpen = true;
  476. }
  477.  
  478. #region Methods
  479.  
  480.  
  481. public async Task CreateUser()
  482. {
  483. try
  484. {
  485.  
  486. var newAuth = new UserAuthentication()
  487. {
  488. Password = Security.CreateSaltedPasswordForNewUser("LetMeIn"),
  489. Salt = Security.LastSalt,
  490. CreatedBy = _creatingUser,
  491. CreatedDate = DateTime.Now,
  492. ModifiedBy = _creatingUser,
  493. ModifiedDate = DateTime.Now
  494. };
  495.  
  496.  
  497. Security.ClearLastSalt();
  498.  
  499. Manager.AddEntity(newAuth);
  500. UserToAdd.UserAuthentication = newAuth;
  501.  
  502. Manager.AddEntity(UserToAdd);
  503.  
  504. var saveResponse = await Manager.TrySaveChangesAsync();
  505.  
  506. if (saveResponse.Ok)
  507. {
  508. TryClose(true);
  509. }
  510. }
  511. catch (Exception)
  512. {
  513. throw;
  514. }
  515. }
  516.  
  517. #endregion
  518.  
  519. }
  520.  
  521. protected override void Configure()
  522. {
  523. IdeaBlade.Core.Composition.CompositionHost.IgnorePatterns.Add("xunit.*");
  524. IdeaBlade.Core.Composition.CompositionHost.IgnorePatterns.Add("BearPaw.Client.*");
  525. IdeaBlade.Core.Composition.CompositionHost.IgnorePatterns.Add("BearPaw.Clients.*");
  526. IdeaBlade.Core.Composition.CompositionHost.IgnorePatterns.Add("Caliburn.*");
  527. IdeaBlade.Core.Composition.CompositionHost.IgnorePatterns.Add("JetBrains.*");
  528. IdeaBlade.Core.Composition.CompositionHost.IgnorePatterns.Add("FluentAssertions.*");
  529.  
  530. var conventions = new RegistrationBuilder();
  531. conventions.ForTypesDerivedFrom<IBearPawFeature>()
  532. .Export()
  533. .SetCreationPolicy(CreationPolicy.NonShared);
  534.  
  535.  
  536. _container = new CompositionContainer(
  537. new AggregateCatalog(
  538. AssemblySource.Instance.Select(x=> new AssemblyCatalog(x, conventions)).OfType<ComposablePartCatalog>()
  539. )
  540. );
  541.  
  542. var batch = new CompositionBatch();
  543.  
  544. batch.AddExportedValue<IWindowManager>(new TelerikWindowManager());
  545. batch.AddExportedValue<IEventAggregator>(new EventAggregator());
  546. batch.AddExportedValue<IEntityManagerProvider<BearPawEntities>>(new MainEntityManagerProvider());
  547. batch.AddExportedValue<IEntityManagerProvider<BearPawReportingEntities>>(new ReportingEntityManagerProvider());
  548. batch.AddExportedValue(_container);
  549.  
  550. // This is essential to enable Telerik's conventions
  551. TelerikConventions.Install();
  552.  
  553. AddKeyBindingTriggers();
  554.  
  555. VisualStudio2013Palette.LoadPreset(VisualStudio2013Palette.ColorVariation.Dark);
  556. VisualStudio2013Palette.Palette.BasicColor = Color.FromArgb(255, 77, 77, 82);
  557.  
  558.  
  559. _container.Compose(batch);
  560. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement