-
Notifications
You must be signed in to change notification settings - Fork 3
/
DatabaseFacade.cs
1015 lines (893 loc) · 35.4 KB
/
DatabaseFacade.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © 2011-2013 Yanick Castonguay
//
// This file is part of MPfm.
//
// MPfm is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// MPfm is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with MPfm. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MPfm.Library.Database.Interfaces;
using MPfm.Library.Objects;
using MPfm.Player.Objects;
using MPfm.Sound.AudioFiles;
namespace MPfm.Library.Database
{
/// <summary>
/// The DatabaseFacade class implements the SQLiteGateway class.
/// It acts as a facade to select, insert, update and delete data from the
/// MPfm database.
/// </summary>
public class DatabaseFacade : IDatabaseFacade
{
private readonly ISQLiteGateway _gateway;
/// <summary>
/// Default constructor for the DatabaseFacade class.
/// </summary>
/// <param name="databaseFilePath">Database file path</param>
public DatabaseFacade(string databaseFilePath)
{
#if IOS || ANDROID || MACOSX || LINUX
_gateway = new MonoSQLiteGateway(databaseFilePath);
#else
_gateway = new SQLiteGateway(databaseFilePath);
#endif
}
/// <summary>
/// Executes an SQL statement.
/// </summary>
/// <param name="sql">SQL statement to execute</param>
public void ExecuteSQL(string sql)
{
_gateway.Execute(sql);
}
/// <summary>
/// Resets the library.
/// </summary>
public void ResetLibrary()
{
// Delete all table content
_gateway.Delete("AudioFiles");
_gateway.Delete("PlaylistFiles");
_gateway.Delete("Loops");
_gateway.Delete("Markers");
}
#region Audio Files
/// <summary>
/// Selects all audio files from the database.
/// </summary>
/// <returns>List of AudioFiles</returns>
public List<AudioFile> SelectAudioFiles()
{
List<AudioFile> audioFiles = _gateway.Select<AudioFile>("SELECT * FROM AudioFiles");
return audioFiles;
}
public List<AudioFile> SelectAudioFiles(AudioFileFormat format, string artistName, string albumTitle, string search)
{
StringBuilder sql = new StringBuilder();
sql.AppendLine("SELECT * FROM AudioFiles ");
if(format != AudioFileFormat.All || !String.IsNullOrEmpty(artistName) || !String.IsNullOrEmpty(albumTitle) || !String.IsNullOrEmpty(search))
{
sql.AppendLine(" WHERE ");
int count = 0;
if(format != AudioFileFormat.All)
{
count++;
sql.AppendLine(" [FileType] = '" + FormatSQLValue(format.ToString()) + "'");
}
if(!String.IsNullOrEmpty(artistName))
{
count++;
if(count > 1)
{
sql.AppendLine(" AND ");
}
sql.AppendLine(" [ArtistName] = '" + FormatSQLValue(artistName) + "' ");
}
if(!String.IsNullOrEmpty(albumTitle))
{
count++;
if(count > 1)
{
sql.AppendLine(" AND ");
}
sql.AppendLine(" [AlbumTitle] = '" + FormatSQLValue(albumTitle) + "' ");
}
if(!String.IsNullOrEmpty(search))
{
}
}
List<AudioFile> audioFiles = _gateway.Select<AudioFile>(sql.ToString());
return audioFiles;
}
/// <summary>
/// Selects a specific audio file from the database by its identifier.
/// </summary>
/// <param name="audioFileId">Audio file unique identifier</param>
/// <returns>AudioFile</returns>
public AudioFile SelectAudioFile(Guid audioFileId)
{
AudioFile audioFile = _gateway.SelectOne<AudioFile>("SELECT * FROM AudioFiles WHERE AudioFileId = '" + audioFileId.ToString() + "'");
return audioFile;
}
/// <summary>
/// Inserts a new audio file into the database.
/// </summary>
/// <param name="audioFile">AudioFile to insert</param>
public void InsertAudioFile(AudioFile audioFile)
{
_gateway.Insert<AudioFile>(audioFile, "AudioFiles");
}
///// <summary>
///// Inserts new audio files into the database.
///// </summary>
///// <param name="audioFiles">List of AudioFiles to insert</param>
//public void InsertAudioFiles(List<AudioFile> audioFiles)
//{
// // Insert song
// //Insert("AudioFiles", "AudioFileId", audioFiles);
// string tableName = "AudioFiles";
// string idFieldName = "AudioFileId";
// // Get empty result set
// string baseQuery = "SELECT * FROM " + tableName;
// DataTable table = Select(baseQuery + " WHERE " + idFieldName + " = ''");
// // Loop through objects
// foreach (AudioFile audioFile in audioFiles)
// {
// // Add new row to data table
// DataRow newRow = table.NewRow();
// table.Rows.Add(newRow);
// ConvertLibrary.ToRow(ref newRow, audioFile);
// }
// // Insert new row into database
// UpdateDataTableTransaction(table, baseQuery);
//}
/// <summary>
/// Updates an existing audio file to the database.
/// </summary>
/// <param name="audioFile">AudioFile to update</param>
public void UpdateAudioFile(AudioFile audioFile)
{
_gateway.Update<AudioFile>(audioFile, "AudioFiles", "AudioFileId", audioFile.Id.ToString());
}
/// <summary>
/// Deletes an audio file from the database.
/// </summary>
/// <param name="audioFileId">AudioFile to delete</param>
public void DeleteAudioFile(Guid audioFileId)
{
_gateway.Delete("AudioFiles", "AudioFileId", audioFileId);
}
/// <summary>
/// Deletes audio files from the database based on their file path.
/// </summary>
/// <param name="basePath">Base audio file path</param>
public void DeleteAudioFiles(string basePath)
{
_gateway.Delete("AudioFiles", "FilePath LIKE '" + FormatSQLValue(basePath) + "%'");
}
/// <summary>
/// Returns the distinct list of artist names from the database.
/// </summary>
/// <returns>List of distinct artist names</returns>
public List<string> SelectDistinctArtistNames()
{
return SelectDistinctArtistNames(AudioFileFormat.All);
}
/// <summary>
/// Returns the distinct list of artist names from the database, using the sound format
/// filter passed in the soundFormat parameter.
/// </summary>
/// <param name="audioFileFormat">Audio file format filter</param>
/// <returns>List of distinct artist names</returns>
public List<string> SelectDistinctArtistNames(AudioFileFormat audioFileFormat)
{
// Create list
List<string> artists = new List<string>();
// Set query
string sql = "SELECT DISTINCT ArtistName FROM AudioFiles ORDER BY ArtistName";
// Check for audio file format filter
if (audioFileFormat != AudioFileFormat.All)
{
sql = "SELECT DISTINCT ArtistName FROM AudioFiles WHERE FileType = '" + audioFileFormat.ToString() + "' ORDER BY ArtistName";
}
// Select distinct
IEnumerable<object> list = _gateway.SelectList(sql);
foreach (object obj in list)
{
artists.Add(obj.ToString());
}
return artists;
}
/// <summary>
/// Returns the distinct list of album titles per artist from the database.
/// </summary>
/// <returns>List of distinct album titles per artist</returns>
public Dictionary<string, List<string>> SelectDistinctAlbumTitles()
{
return SelectDistinctAlbumTitles(AudioFileFormat.All, string.Empty);
}
/// <summary>
/// Returns the distinct list of album titles per artist from the database.
/// </summary>
/// <returns>List of distinct album titles per artist</returns>
public Dictionary<string, List<string>> SelectDistinctAlbumTitles(AudioFileFormat audioFileFormat)
{
return SelectDistinctAlbumTitles(audioFileFormat, string.Empty);
}
/// <summary>
/// Returns the distinct list of album titles per artist from the database, using the sound format
/// filter passed in the soundFormat parameter.
/// </summary>
/// <param name="audioFileFormat">Audio file format filter</param>
/// <param name="artistName">Artist name filter</param>
/// <returns>List of distinct album titles per artist</returns>
public Dictionary<string, List<string>> SelectDistinctAlbumTitles(AudioFileFormat audioFileFormat, string artistName)
{
// Create dictionary
Dictionary<string, List<string>> albums = new Dictionary<string, List<string>>();
// Set query
StringBuilder sql = new StringBuilder();
sql.AppendLine("SELECT DISTINCT ArtistName, AlbumTitle FROM AudioFiles ");
if (audioFileFormat != AudioFileFormat.All && !String.IsNullOrEmpty(artistName))
{
sql.AppendLine(" WHERE FileType = '" + audioFileFormat.ToString() + "' AND ArtistName = '" + FormatSQLValue(artistName) + "'");
}
else if (audioFileFormat != AudioFileFormat.All)
{
sql.AppendLine(" WHERE FileType = '" + audioFileFormat.ToString() + "' ");
}
else if(!String.IsNullOrEmpty(artistName))
{
sql.AppendLine(" WHERE ArtistName = '" + FormatSQLValue(artistName) + "' ");
}
sql.AppendLine(" ORDER BY ArtistName");
// Select distinct
List<Tuple<object, object>> listTuple = _gateway.SelectTuple(sql.ToString());
foreach (Tuple<object, object> tuple in listTuple)
{
// Get values
string artistNameDistinct = tuple.Item1.ToString();
string albumTitleDistinct = tuple.Item2.ToString();
// Add value to dictionary
if (albums.ContainsKey(artistNameDistinct))
{
albums[artistNameDistinct].Add(albumTitleDistinct);
}
else
{
albums.Add(artistNameDistinct, new List<string>() { albumTitleDistinct });
}
}
return albums;
}
/// <summary>
/// Returns the list of file paths in the Song table.
/// </summary>
/// <returns>List of file paths</returns>
public IEnumerable<string> SelectFilePaths()
{
IEnumerable<object> listObjects = _gateway.SelectList("SELECT FilePath FROM AudioFiles");
return listObjects.Select(x => x.ToString());
}
///// <summary>
///// Returns the distinct list of album titles with the path of at least one song of the album from the database,
///// using the sound format filter passed in the soundFormat parameter. This is useful for displaying album art
///// for example (no need to return all songs from every album).
///// </summary>
///// <param name="audioFileFormat">Audio file format filter (use Unknown to skip filter)</param>
///// <returns>List of distinct album titles with file paths</returns>
//public Dictionary<string, string> SelectDistinctAlbumTitlesWithFilePaths(AudioFileFormat audioFileFormat)
//{
// // Create dictionary
// Dictionary<string, string> albums = new Dictionary<string, string>();
// // Set query
// string sql = "SELECT DISTINCT AlbumTitle, FilePath FROM AudioFiles";
// if (audioFileFormat != AudioFileFormat.All)
// {
// sql = "SELECT DISTINCT AlbumTitle, FilePath FROM AudioFiles WHERE FileType = '" + audioFileFormat.ToString() + "' ORDER BY ArtistName";
// }
// // Select distinct
// DataTable table = Select(sql);
// // Convert into a list of strings
// for (int a = 0; a < table.Rows.Count; a++)
// {
// // Get values
// string albumTitle = table.Rows[a]["AlbumTitle"].ToString();
// string filePath = table.Rows[a]["FilePath"].ToString();
// // Add item to dictionary
// if (!albums.ContainsKey(albumTitle))
// {
// albums.Add(albumTitle, filePath);
// }
// }
// return albums;
//}
/// <summary>
/// Updates the play count of an audio file and sets the last playback datetime.
/// </summary>
/// <param name="audioFileId">AudioFile identifier</param>
public void UpdatePlayCount(Guid audioFileId)
{
// Get play count
AudioFile audioFile = SelectAudioFile(audioFileId);
// Check if the audiofile was found
if (audioFile == null)
{
throw new Exception("Error; The audiofile was not found!");
}
string lastPlayed = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
_gateway.Execute("UPDATE AudioFiles SET PlayCount = " + (audioFile.PlayCount + 1).ToString() + ", LastPlayedDateTime = '" + lastPlayed + "' WHERE AudioFileId = '" + audioFileId.ToString() + "'");
}
#endregion
#region Folders
/// <summary>
/// Selects a folder from a path.
/// </summary>
/// <param name="path">Path to the folder</param>
/// <returns>Folder</returns>
public Folder SelectFolderByPath(string path)
{
Folder folder = _gateway.SelectOne<Folder>("SELECT * FROM Folders WHERE FolderPath = '" + FormatSQLValue(path) + "'");
return folder;
}
/// <summary>
/// Selects a folders.
/// </summary>
/// <returns>List of folders</returns>
public List<Folder> SelectFolders()
{
List<Folder> folders = _gateway.Select<Folder>("SELECT * FROM Folders");
return folders;
}
/// <summary>
/// Inserts a folder in the database. Configuration for library location.
/// </summary>
/// <param name="folderPath">Path of the folder to add</param>
/// <param name="recursive">If resursive</param>
public void InsertFolder(string folderPath, bool recursive)
{
// Insert new folder
Folder folder = new Folder();
folder.FolderPath = folderPath;
folder.IsRecursive = recursive;
_gateway.Insert<Folder>(folder, "Folders");
}
/// <summary>
/// Deletes a specific folder.
/// </summary>
/// <param name="folderId">FolderId</param>
public void DeleteFolder(Guid folderId)
{
// Delete folder
_gateway.Delete("Folders", "FolderId", folderId);
}
/// <summary>
/// Deletes all folders.
/// </summary>
public void DeleteFolders()
{
// Delete all folders
_gateway.Delete("Folders");
}
#endregion
#region Equalizers
/// <summary>
/// Select all EQ presets from the database.
/// </summary>
/// <returns>List of EQPresets</returns>
public List<EQPreset> SelectEQPresets()
{
List<EQPreset> eqs = _gateway.Select<EQPreset>("SELECT * FROM EQPresets");
return eqs;
}
/// <summary>
/// Selects an EQ preset from the database.
/// </summary>
/// <param name="name">EQ preset name</param>
/// <returns>EQPreset</returns>
public EQPreset SelectEQPreset(string name)
{
EQPreset preset = _gateway.SelectOne<EQPreset>("SELECT * FROM EQPresets WHERE Name = '" + FormatSQLValue(name) + "'");
return preset;
}
/// <summary>
/// Inserts a new EQ preset into the database.
/// </summary>
/// <param name="eq">EQ preset to insert</param>
public void InsertEqualizer(EQPreset eq)
{
_gateway.Insert<EQPreset>(eq, "EQPresets");
}
/// <summary>
/// Updates an existing EQ preset in the database.
/// </summary>
/// <param name="eq">EQ preset to update</param>
public void UpdateEqualizer(EQPreset eq)
{
_gateway.Update<EQPreset>(eq, "EQPresets", "EQPresetId", eq.EQPresetId);
}
/// <summary>
/// Deletes an EQ preset from the database.
/// </summary>
/// <param name="eqPresetId">EQ preset identifier</param>
public void DeleteEqualizer(Guid eqPresetId)
{
// Delete item
_gateway.Delete("EQPresets", "EQPresetId", eqPresetId);
}
#endregion
#region Markers
/// <summary>
/// Selects all markers from the database.
/// </summary>
/// <returns>List of Markers</returns>
public List<Marker> SelectMarkers()
{
List<Marker> markers = _gateway.Select<Marker>("SELECT * FROM Markers");
return markers;
}
/// <summary>
/// Selects markers related to an audio file from the database.
/// </summary>
/// <param name="audioFileId">AudioFile identifier</param>
/// <returns>List of Markers</returns>
public List<Marker> SelectMarkers(Guid audioFileId)
{
List<Marker> markers = _gateway.Select<Marker>("SELECT * FROM Markers");
return markers;
}
/// <summary>
/// Selects a marker from the database.
/// </summary>
/// <param name="markerId">Marker Id</param>
/// <returns>Marker</returns>
public Marker SelectMarker(Guid markerId)
{
Marker marker = _gateway.SelectOne<Marker>("SELECT * FROM Markers WHERE MarkerId = '" + markerId.ToString() + "'");
return marker;
}
/// <summary>
/// Inserts a new marker into the database.
/// </summary>
/// <param name="dto">Marker to insert</param>
public void InsertMarker(Marker dto)
{
_gateway.Insert<Marker>(dto, "Markers");
}
/// <summary>
/// Updates an existing marker from the database.
/// </summary>
/// <param name="dto">Marker to update</param>
public void UpdateMarker(Marker dto)
{
_gateway.Update<Marker>(dto, "Markers", "MarkerId", dto.MarkerId.ToString());
}
/// <summary>
/// Deletes a marker from the database.
/// </summary>
/// <param name="markerId">Marker to delete</param>
public void DeleteMarker(Guid markerId)
{
// Delete marker
_gateway.Delete("Markers", "MarkerId", markerId);
}
#endregion
#region Loops
/// <summary>
/// Selects all loops from the database.
/// </summary>
/// <returns>List of Loops</returns>
public List<Loop> SelectLoops()
{
List<Loop> loops = _gateway.Select<Loop>("SELECT * FROM Loops");
return loops;
}
/// <summary>
/// Selects loops related to an audio file from the database.
/// </summary>
/// <param name="audioFileId">AudioFile identifier</param>
/// <returns>List of Loops</returns>
public List<Loop> SelectLoops(Guid audioFileId)
{
List<Loop> loops = _gateway.Select<Loop>("SELECT * FROM Loops WHERE AudioFileId = '" + audioFileId.ToString() + "' ORDER BY LengthBytes");
return loops;
}
/// <summary>
/// Selects a loop from the database.
/// </summary>
/// <param name="loopId">Loop identifier</param>
/// <returns>Loop</returns>
public Loop SelectLoop(Guid loopId)
{
Loop loop = _gateway.SelectOne<Loop>("SELECT * FROM Loops WHERE LoopId = '" + loopId.ToString() + "'");
return loop;
}
/// <summary>
/// Inserts a new loop into the database.
/// </summary>
/// <param name="dto">Loop to insert</param>
public void InsertLoop(Loop dto)
{
_gateway.Insert<Loop>(dto, "Loops");
}
/// <summary>
/// Updates an existing loop from the database.
/// </summary>
/// <param name="dto">Loop to update</param>
public void UpdateLoop(Loop dto)
{
_gateway.Update<Loop>(dto, "Loops", "LoopId", dto.LoopId.ToString());
}
/// <summary>
/// Deletes a loop from the database.
/// </summary>
/// <param name="loopId">Loop to delete</param>
public void DeleteLoop(Guid loopId)
{
// Delete loop
_gateway.Delete("Loops", "LoopId", loopId);
}
#endregion
#region Playlists
///// <summary>
///// Selects all the playlists from the database.
///// </summary>
///// <returns>List of playlists</returns>
//public static List<Playlist> SelectPlaylists()
//{
// List<Playlist> playlists = null;
// try
// {
// // Open the connection
// using (MPFM_EF context = new MPFM_EF())
// {
// playlists = context.Playlists.OrderBy(x => x.PlaylistName).ToList();
// }
// }
// catch (Exception ex)
// {
// Tracing.Log("MPfm.Library (DataAccess) -- Error in SelectPlaylists(): " + ex.Message);
// throw ex;
// }
// return playlists;
//}
///// <summary>
///// Selects a playlist from the database, using its identifier.
///// </summary>
///// <param name="playlistId">Playlist identifier</param>
///// <returns>Playlist</returns>
//public static Playlist SelectPlaylist(Guid playlistId)
//{
// Playlist playlist = null;
// try
// {
// // Open the connection
// using (MPFM_EF context = new MPFM_EF())
// {
// string strId = playlistId.ToString();
// playlist = context.Playlists.FirstOrDefault(x => x.PlaylistId == strId);
// }
// }
// catch (Exception ex)
// {
// Tracing.Log("MPfm.Library (DataAccess) -- Error in SelectPlaylist(): " + ex.Message);
// throw ex;
// }
// return playlist;
//}
///// <summary>
///// Selects a playlist from the database, using its name.
///// </summary>
///// <param name="playlistName">Playlist name</param>
///// <returns>Playlist</returns>
//public static Playlist SelectPlaylist(string playlistName)
//{
// Playlist playlist = null;
// try
// {
// // Open the connection
// using (MPFM_EF context = new MPFM_EF())
// {
// playlist = context.Playlists.FirstOrDefault(x => x.PlaylistName.ToUpper() == playlistName.ToUpper());
// }
// }
// catch (Exception ex)
// {
// Tracing.Log("MPfm.Library (DataAccess) -- Error in SelectPlaylist(): " + ex.Message);
// throw ex;
// }
// return playlist;
//}
///// <summary>
///// Checks if a playlist exists in the database, using its name.
///// </summary>
///// <param name="playlistName">Playlist name</param>
///// <returns>True if the playlist exists</returns>
//public static bool PlaylistExists(string playlistName)
//{
// // Check if playlist exists
// if (SelectPlaylist(playlistName) != null)
// {
// return true;
// }
// return false;
//}
///// <summary>
///// Inserts a playlist into the database.
///// </summary>
///// <param name="playlist">Playlist to insert</param>
//public static void InsertPlaylist(Playlist playlist)
//{
// try
// {
// // Open the connection
// using (MPFM_EF context = new MPFM_EF())
// {
// // Add to database
// context.AddToPlaylists(playlist);
// context.SaveChanges();
// }
// }
// catch (Exception ex)
// {
// Tracing.Log("MPfm.Library (DataAccess) -- Error in InsertPlaylist(): " + ex.Message);
// throw ex;
// }
//}
///// <summary>
///// Updates a playlist in the database.
///// </summary>
///// <param name="playlist">Playlist to update</param>
//public static void UpdatePlaylist(Playlist playlist)
//{
// try
// {
// // Open the connection
// using (MPFM_EF context = new MPFM_EF())
// {
// Playlist playlistToModify = context.Playlists.FirstOrDefault(x => x.PlaylistId == playlist.PlaylistId);
// if (playlistToModify != null)
// {
// playlistToModify.PlaylistName = playlist.PlaylistName;
// context.SaveChanges();
// }
// }
// }
// catch (Exception ex)
// {
// Tracing.Log("MPfm.Library (DataAccess) -- Error in UpdatePlaylist(): " + ex.Message);
// throw ex;
// }
//}
///// <summary>
///// Deletes a playlist from the database.
///// </summary>
///// <param name="playlistId">Playlist identifier to delete</param>
//public static void DeletePlaylist(Guid playlistId)
//{
// try
// {
// // Open the connection
// using (MPFM_EF context = new MPFM_EF())
// {
// ExecuteSql(context, "DELETE FROM Playlists WHERE PlaylistId = @PlaylistId", new SQLiteParameter("PlaylistId", playlistId.ToString()));
// }
// }
// catch (Exception ex)
// {
// Tracing.Log("MPfm.Library (DataAccess) -- Error in DeletePlaylist(): " + ex.Message);
// throw ex;
// }
//}
#endregion
#region Settings
/// <summary>
/// Selects all settings.
/// </summary>
/// <returns>List of settings</returns>
public List<Setting> SelectSettings()
{
List<Setting> settings = _gateway.Select<Setting>("SELECT * FROM Settings");
return settings;
}
/// <summary>
/// Selects a setting by its name.
/// </summary>
/// <param name="name">Setting name</param>
/// <returns>Setting object</returns>
public Setting SelectSetting(string name)
{
Setting setting = _gateway.SelectOne<Setting>("SELECT * FROM Settings WHERE SettingName = '" + FormatSQLValue(name) + "'");
return setting;
}
/// <summary>
/// Inserts a new setting into the database.
/// </summary>
/// <param name="name">Setting name</param>
/// <param name="value">Setting value</param>
public void InsertSetting(string name, string value)
{
// Create setting
Setting setting = new Setting();
setting.SettingName = name;
setting.SettingValue = value;
// Insert setting
InsertSetting(setting);
}
/// <summary>
/// Inserts a new setting into the database.
/// </summary>
/// <param name="dto">Setting to insert</param>
public void InsertSetting(Setting dto)
{
_gateway.Insert<Setting>(dto, "Settings");
}
/// <summary>
/// Updates an existing setting from the database.
/// </summary>
/// <param name="dto">Setting to update</param>
public void UpdateSetting(Setting dto)
{
_gateway.Update<Setting>(dto, "Settings", "SettingId", dto.SettingId.ToString());
}
/// <summary>
/// Deletes a setting from the database.
/// </summary>
/// <param name="settingId">Setting to delete</param>
public void DeleteSetting(Guid settingId)
{
// Delete loop
_gateway.Delete("Settings", "SettingId", settingId);
}
#endregion
#region Playlist Files
/// <summary>
/// Selects all playlist files.
/// </summary>
/// <returns>List of playlist files</returns>
public List<PlaylistFile> SelectPlaylistFiles()
{
List<PlaylistFile> playlistFiles = _gateway.Select<PlaylistFile>("SELECT * FROM PlaylistFiles");
return playlistFiles;
}
/// <summary>
/// Inserts a new playlist file into the database.
/// </summary>
/// <param name="dto">Playlist file</param>
public void InsertPlaylistFile(PlaylistFile dto)
{
_gateway.Insert<PlaylistFile>(dto, "PlaylistFiles");
}
/// <summary>
/// Deletes a playlist file from the database.
/// </summary>
/// <param name="filePath">Playlist file path to delete</param>
public void DeletePlaylistFile(string filePath)
{
// Delete loop
_gateway.Delete("PlaylistFiles", "FilePath = '" + FormatSQLValue(filePath) + "'");
}
#endregion
#region History
/// <summary>
/// Returns the number of times the audio file has been played.
/// </summary>
/// <param name="audioFileId">Audio file identifier</param>
/// <returns>Play count</returns>
public int GetAudioFilePlayCountFromHistory(Guid audioFileId)
{
// Declare variables
int playCount = 0;
// Execute scalar query
string query = "SELECT COUNT(*) FROM History WHERE AudioFileId = '" + audioFileId.ToString() + "'";
object value = _gateway.ExecuteScalar(query);
// Check value for null
if (value == DBNull.Value)
{
// No play count
return 0;
}
else
{
try
{
// Try to cast into an integer
playCount = (int)value;
}
catch
{
// Return no play count
return 0;
}
}
return playCount;
}
/// <summary>
/// Returns the last time the audio file has been played.
/// The value is null if the file has never been played.
/// </summary>
/// <param name="audioFileId">Audio file identifier</param>
/// <returns>Nullable date/time</returns>
public DateTime? GetAudioFileLastPlayedFromHistory(Guid audioFileId)
{
// Declare variables
DateTime? lastPlayed = null;
// Execute scalar query
string query = "SELECT TOP 1 FROM History WHERE AudioFileId = '" + audioFileId.ToString() + "' ORDER BY EventDateTime";
object value = _gateway.ExecuteScalar(query);
// Check value for null
if (value == DBNull.Value)
{
// No last played value
return null;
}
else
{
try
{
// Try to cast into a DateTime
DateTime valueDateTime;
bool success = DateTime.TryParse(value.ToString(), out valueDateTime);
if (success)
{
lastPlayed = valueDateTime;
}
}
catch
{
// No last played value
return null;
}
}
return lastPlayed;
}
/// <summary>
/// Inserts an history item into the database using the current datetime.
/// </summary>
/// <param name="audioFileId">Audio file identifier</param>
public void InsertHistory(Guid audioFileId)
{
// Create history object
History history = new History();
history.AudioFileId = audioFileId;
history.EventDateTime = DateTime.Now;
// Insert history
_gateway.Insert<History>(history, "History");
}
/// <summary>
/// Inserts an history item into the database.
/// </summary>
/// <param name="audioFileId">Audio file identifier</param>
/// <param name="eventDateTime">Event date/time</param>
public void InsertHistory(Guid audioFileId, DateTime eventDateTime)
{
// Create history object
History history = new History();
history.AudioFileId = audioFileId;
history.EventDateTime = eventDateTime;
// Insert history
_gateway.Insert<History>(history, "History");