SampleSmart 1.0.0.0
SampleSmart 사용 방법을 보여 주는 예제 프로젝트입니다.
로딩중...
검색중...
일치하는것 없음
PageDatabase.xaml.ViewModel.cs
이 파일의 문서화 페이지로 가기
1using System.Collections.ObjectModel;
2using System.IO;
3using Dreamine.Database.Abstractions;
4using Dreamine.Database.Abstractions.Mapping;
5using Dreamine.Database.MySql;
6using Dreamine.Database.Oracle;
7using Dreamine.Database.Sqlite;
8using Dreamine.Database.SqlServer;
9using Dreamine.MVVM.ViewModels;
10
12
21public sealed class PageDatabaseViewModel : ViewModelBase
22{
32
42 {
43 var dataDirectory = Path.Combine(AppContext.BaseDirectory, "Data");
44 Directory.CreateDirectory(dataDirectory);
45
46 var sqlitePath = Path.Combine(dataDirectory, "SampleSmart.db");
47
49 [
51 "SQLite",
52 $"Data Source={sqlitePath}",
53 connectionString => new SqliteDatabaseProvider(connectionString),
54 autoInitialize: true),
55
57 "MySQL",
58 "Server=localhost;Port=3306;Database=dreamine_sample;User ID=root;Password=password;",
59 connectionString => new MySqlDatabaseProvider(connectionString)),
60
62 "Oracle",
63 "User Id=dreamine;Password=password;Data Source=localhost:1521/XEPDB1;",
64 connectionString => new OracleDatabaseProvider(connectionString)),
65
67 "MS SQL",
68 "Server=localhost;Database=dreamine_sample;User Id=sa;Password=password;TrustServerCertificate=True;",
69 connectionString => new SqlServerDatabaseProvider(connectionString))
70 ];
71
73 }
74
83 public ObservableCollection<DatabaseSampleTabViewModel> ProviderTabs { get; }
84
94 {
96 set => SetProperty(ref _selectedProviderTab, value);
97 }
98}
99
108public sealed class DatabaseSampleTabViewModel : ViewModelBase
109{
118 private readonly Func<string, IDatabaseProvider> _providerFactory;
127 private IDatabaseProvider? _provider;
145 private string _connectionString;
154 private string _nameInput = "Dreamine";
163 private string _roleInput = "Operator";
172 private string _statusMessage = "Not initialized.";
173
215 string title,
216 string connectionString,
217 Func<string, IDatabaseProvider> providerFactory,
218 bool autoInitialize = false)
219 {
220 Title = title;
221 _connectionString = connectionString;
222 _providerFactory = providerFactory;
223
224 if (autoInitialize)
225 {
226 Initialize();
227 }
228 }
229
238 public string Title { get; }
239
248 public ObservableCollection<SampleCustomer> Customers { get; } = [];
249
258 public string ConnectionString
259 {
260 get => _connectionString;
261 set => SetProperty(ref _connectionString, value);
262 }
263
273 {
274 get => _selectedCustomer;
275 set
276 {
277 if (!SetProperty(ref _selectedCustomer, value))
278 {
279 return;
280 }
281
282 if (value is null)
283 {
284 return;
285 }
286
287 NameInput = value.Name;
288 RoleInput = value.Role;
289 }
290 }
291
300 public string NameInput
301 {
302 get => _nameInput;
303 set => SetProperty(ref _nameInput, value);
304 }
305
314 public string RoleInput
315 {
316 get => _roleInput;
317 set => SetProperty(ref _roleInput, value);
318 }
319
328 public string StatusMessage
329 {
330 get => _statusMessage;
331 set => SetProperty(ref _statusMessage, value);
332 }
333
342 public RelayCommand InitializeCommand => new(Initialize);
343
352 public RelayCommand AddCommand => new(Add);
353
362 public RelayCommand UpdateCommand => new(Update);
363
372 public RelayCommand DeleteCommand => new(Delete);
373
382 public RelayCommand RefreshCommand => new(Refresh);
383
392 private void Initialize()
393 {
394 try
395 {
397 _provider.EnsureDatabaseExists();
398 _provider.CreateTable<SampleCustomer>();
399
401 Refresh();
402 }
403 catch (Exception ex)
404 {
405 StatusMessage = $"{Title} initialize failed: {ex.Message}";
406 }
407 }
408
417 private void Add()
418 {
419 if (!TryGetProvider(out var provider))
420 {
421 return;
422 }
423
424 try
425 {
426 var name = NormalizeInput(NameInput, "New customer");
427 var role = NormalizeInput(RoleInput, "Viewer");
428
429 provider.Insert(new SampleCustomer
430 {
431 Name = name,
432 Role = role,
433 CreatedAt = DateTime.Now
434 });
435
436 StatusMessage = $"{Title}: added {name}.";
437 Refresh();
438 }
439 catch (Exception ex)
440 {
441 StatusMessage = $"{Title} add failed: {ex.Message}";
442 }
443 }
444
453 private void Update()
454 {
455 if (!TryGetProvider(out var provider))
456 {
457 return;
458 }
459
460 if (SelectedCustomer is null)
461 {
462 StatusMessage = "Select a row to update.";
463 return;
464 }
465
466 try
467 {
468 SelectedCustomer.Name = NormalizeInput(NameInput, SelectedCustomer.Name);
469 SelectedCustomer.Role = NormalizeInput(RoleInput, SelectedCustomer.Role);
470
471 provider.Update(SelectedCustomer);
472 StatusMessage = $"{Title}: updated #{SelectedCustomer.Id}.";
473 Refresh();
474 }
475 catch (Exception ex)
476 {
477 StatusMessage = $"{Title} update failed: {ex.Message}";
478 }
479 }
480
489 private void Delete()
490 {
491 if (!TryGetProvider(out var provider))
492 {
493 return;
494 }
495
496 if (SelectedCustomer is null)
497 {
498 StatusMessage = "Select a row to delete.";
499 return;
500 }
501
502 try
503 {
504 var deletedId = SelectedCustomer.Id;
505 provider.Delete(SelectedCustomer);
506 SelectedCustomer = null;
507 StatusMessage = $"{Title}: deleted #{deletedId}.";
508 Refresh();
509 }
510 catch (Exception ex)
511 {
512 StatusMessage = $"{Title} delete failed: {ex.Message}";
513 }
514 }
515
524 private void Refresh()
525 {
526 if (!TryGetProvider(out var provider))
527 {
528 return;
529 }
530
531 try
532 {
533 var rows = provider
534 .Query<SampleCustomer>("SELECT Id, Name, Role, CreatedAt FROM SampleCustomers ORDER BY Id DESC")
535 .ToArray();
536
537 Customers.Clear();
538 foreach (var row in rows)
539 {
540 Customers.Add(row);
541 }
542
543 StatusMessage = $"{Title}: loaded {Customers.Count} rows.";
544 }
545 catch (Exception ex)
546 {
547 StatusMessage = $"{Title} refresh failed: {ex.Message}";
548 }
549 }
550
559 private void AddSeedDataIfNeeded()
560 {
561 if (!TryGetProvider(out var provider))
562 {
563 return;
564 }
565
566 var count = provider.ExecuteScalar<long>("SELECT COUNT(1) FROM SampleCustomers");
567 if (count > 0)
568 {
569 return;
570 }
571
572 provider.Insert(new SampleCustomer
573 {
574 Name = "Minsu",
575 Role = "Admin",
576 CreatedAt = DateTime.Now
577 });
578
579 provider.Insert(new SampleCustomer
580 {
581 Name = "Sample Operator",
582 Role = "Operator",
583 CreatedAt = DateTime.Now
584 });
585 }
586
611 private bool TryGetProvider(out IDatabaseProvider provider)
612 {
613 if (_provider is not null)
614 {
615 provider = _provider;
616 return true;
617 }
618
619 StatusMessage = $"{Title}: initialize the provider first.";
620 provider = null!;
621 return false;
622 }
623
656 private static string NormalizeInput(string value, string fallback)
657 {
658 return string.IsNullOrWhiteSpace(value)
659 ? fallback
660 : value.Trim();
661 }
662}
663
672[DatabaseTable("SampleCustomers")]
673public sealed class SampleCustomer
674{
683 [DatabaseKey]
684 [DatabaseGenerated]
685 public int Id { get; set; }
686
695 public string Name { get; set; } = string.Empty;
696
705 public string Role { get; set; } = string.Empty;
706
715 public DateTime CreatedAt { get; set; }
716}
ObservableCollection< DatabaseSampleTabViewModel > ProviderTabs
static string NormalizeInput(string value, string fallback)
readonly Func< string, IDatabaseProvider > _providerFactory
DatabaseSampleTabViewModel(string title, string connectionString, Func< string, IDatabaseProvider > providerFactory, bool autoInitialize=false)