/// <summary> /// Metodo encargado de buscarcanciones en una carpeta para su importaci'on en la biblioteca de usuario /// </summary> /// <param name="directoryPath">Ruta de acceso a directorio</param> public void ImportSongsToLibrary(String directoryPath) { List<TrackInfo> tracksToInsert = new List<TrackInfo>(); SessionManager sessionManager= SessionManager.Instance; string unknownFrame = "Unknown"; string[] musicFiles = Directory.GetFiles(directoryPath, "*.mp3"); foreach (string musicFile in musicFiles) { UserTrackRepository userTrackRepository = new UserTrackRepository(); TrackRepository trackRepository = new TrackRepository(); using (var mp3 = new Mp3File(musicFile)) { TrackInfo currentTrack = new TrackInfo() {TrackId = Guid.NewGuid()}; if (mp3.HasTags) { Id3Tag tag = mp3.GetTag(Id3TagFamily.FileStartTag); if (tag != null) { currentTrack.Title = tag.Title.IsAssigned ? tag.Title.Value : unknownFrame; currentTrack.AlbumTitle = tag.Album.IsAssigned ? tag.Album.Value : unknownFrame; currentTrack.ArtistTitle = tag.Artists.IsAssigned ? tag.Artists : unknownFrame; currentTrack.Genre = getGenre(tag.Genre.Value); if (tag.Lyrics.Count != 0) { currentTrack.Lyric = tag.Lyrics[0].IsAssigned ? tag.Lyrics[0].Lyrics : ""; } else { currentTrack.Lyric = ""; } if (tag.Year.IsAssigned) { int year; if (Int32.TryParse(tag.Year.Value, out year)) { currentTrack.Year = year; } } } else { currentTrack.Title = unknownFrame; currentTrack.AlbumTitle =unknownFrame; currentTrack.ArtistTitle = unknownFrame; currentTrack.Genre = unknownFrame; currentTrack.Lyric = ""; currentTrack.Year = 0; } currentTrack.SongPath = musicFile; currentTrack.TrackId = Guid.NewGuid(); tracksToInsert.Add(currentTrack); } else { currentTrack.Title =unknownFrame; currentTrack.AlbumTitle = unknownFrame; currentTrack.ArtistTitle =unknownFrame; currentTrack.Genre = unknownFrame; currentTrack.Lyric = ""; currentTrack.SongPath = musicFile; currentTrack.TrackId= Guid.NewGuid(); currentTrack.Year = 0; tracksToInsert.Add(currentTrack); } } } this.userTracks.AddRange(tracksToInsert); this.InsertIntoDatabase(tracksToInsert); }
public void GetAll() { ITrackRepository repository = new TrackRepository(_context); var entities = repository.GetTracksAll("%aero%"); Assert.IsTrue(entities.Count() > 0); }
static void Main(string[] args) { var syncData = new SyncData(); var configXmlProvider = new ConfigXmlProvider(syncData); var webHelper = new WebHelperService(); var configSettings = new ConfigSettings(configXmlProvider); var logger = new ErrorLoggingService(webHelper, configSettings); try { var trackXmlParser = new TrackXmlParser(); var trackXmlProvider = new TrackXmlProvider(syncData); var trackRepository = new TrackRepository(trackXmlParser, trackXmlProvider); var cloudService = new AzureService(syncData); var taggingService = new TagLibService(); var service = new Service(trackRepository, cloudService, logger, syncData, taggingService); service.Run(); } catch (Exception ex) { logger.Log(ex); } }
public UnitOfWork(bool test = false) { if (!test && !Test) { AccountTypes = new AccountTypeRepository(new AccountTypeOracleContext()); Employees = new EmployeeRepository(new EmployeeOracleContext()); AttachedTracks = new AttachedTrackRepository(new AttachedTrackOracleContext()); Routes = new RouteRepository(new RouteOracleContext()); Sectors = new SectorRepository(new SectorOracleContext()); Statuses = new StatusRepository(new StatusOracleContext()); Tracks = new TrackRepository(new TrackOracleContext()); //TrackRoutes = new TrackRouteRepository(new TrackRouteOracleContext()); Trams = new TramRepository(new TramOracleContext()); TramRoutes = new TramRouteRepository(new TramRouteOracleContext()); Tasks = new TaskRepository(new TaskOracleContext()); } else { AccountTypes = new AccountTypeRepository(new AccountTypeTestContext()); Employees = new EmployeeRepository(new EmployeeTestContext()); Tracks = new TrackRepository(new TrackTestContext()); Sectors = new SectorRepository(new SectorTestContext()); Trams = new TramRepository(new TramTestContext()); Routes = new RouteRepository(new RouteTestContext()); AttachedTracks = new AttachedTrackRepository(new AttachedTrackTestContext()); TramRoutes = new TramRouteRepository(new TramRouteTestContext()); TrackRoutes = new TrackRouteRepository(new TrackRouteTestContext()); TramStatuses = new TramStatusRepository(new TramStatusTestContext()); } }
public TrackPage(TrackViewModel tvm) { InitializeComponent(); if (tvm == null) { SetControlsVisible(Visibility.Hidden); return; } var trackRepo = new TrackRepository(); var previewSource = trackRepo.GetPreviewSource(tvm.TrackId); this.DataContext = _vm = new TrackPageViewModel { Artist = tvm.Artist, Title = tvm.Title, Image = tvm.Image, AudioTrack = previewSource, Playtime = tvm.PlayTime, Popularity = tvm.Popularity, DiscNumber = tvm.DiscNumber, LicensorName = tvm.LicensorName, LabelName = tvm.LabelName, ReleaseDate = tvm.ReleaseDate, PackageType = tvm.PackageType, Price = tvm.Price }; StopTrack(); }
public TestInvoice() { _ChinookEntities = new ChinookEntities(); _InvoiceRepo = new InvoiceRepository(_ChinookEntities); _CustomerRepo = new CustomerRepository(_ChinookEntities); _TrackRepo = new TrackRepository(_ChinookEntities); }
public int?StartOrResumeTrack(string authKey, int routeListId) { try { using (var uow = UnitOfWorkFactory.CreateWithoutRoot("[ADS]Старт записи трека")) { if (!CheckAuth(authKey)) { return(null); } var track = TrackRepository.GetTrackForRouteList(uow, routeListId); if (track != null) { return(track.Id); } track = new Track(); track.RouteList = uow.GetById <RouteList>(routeListId); track.Driver = EmployeeRepository.GetDriverByAuthKey(uow, authKey); track.StartDate = DateTime.Now; uow.Save(track); uow.Commit(); return(track.Id); } } catch (Exception e) { logger.Error(e); } return(null); }
public async Task Update_given_existing_track_Updates_properties() { var context = new Mock <ISlotCarContext>(); var entity = new Track { Id = 42 }; context.Setup(c => c.Tracks.FindAsync(42)).ReturnsAsync(entity); using (var repository = new TrackRepository(context.Object)) { var track = new TrackUpdateDTO { Id = 42, Name = "name", LengthInMeters = 12.5, BestLap = TimeSpan.FromSeconds(6.3), MaxCars = 4 }; await repository.Update(track); } Assert.Equal("name", entity.Name); Assert.Equal(12.5, entity.LengthInMeters); Assert.Equal(TimeSpan.FromSeconds(6.3).Ticks, entity.BestLapInTicks); Assert.Equal(4, entity.MaxCars); }
public RepositoryManager(ShuflContext context) { AlbumRepository = new AlbumRepository(context); AlbumArtistRepository = new AlbumArtistRepository(context); AlbumImageRepository = new AlbumImageRepository(context); ArtistRepository = new ArtistRepository(context); ArtistImageRepository = new ArtistImageRepository(context); ArtistGenreRepository = new ArtistGenreRepository(context); GenreRepository = new GenreRepository(context); GroupRepository = new GroupRepository(context); GroupAlbumRepository = new GroupAlbumRepository(context); GroupAlbumRatingRepository = new GroupAlbumRatingRepository(context); GroupInviteRepository = new GroupInviteRepository(context); GroupMemberRepository = new GroupMemberRepository(context); GroupPlaylistRepository = new GroupPlaylistRepository(context); GroupPlaylistRatingRepository = new GroupPlaylistRatingRepository(context); PasswordResetRepository = new PasswordResetRepository(context); PlaylistRepository = new PlaylistRepository(context); PlaylistImageRepository = new PlaylistImageRepository(context); TrackRepository = new TrackRepository(context); TrackArtistRepository = new TrackArtistRepository(context); UserRepository = new UserRepository(context); UserImageRepository = new UserImageRepository(context); UserVerificationRepository = new UserVerificationRepository(context); }
/// <summary> /// Reads a quiz formatted as XML. /// </summary> /// <param name="trackRepository">The track repository.</param> /// <param name="xml">The XML.</param> /// <returns>A quiz.</returns> public Quiz FromXml(TrackRepository trackRepository, string xml) { string quizName = null; DateTime creationDate = DateTime.UtcNow; IEnumerable<Round> rounds; // Read quiz XML try { XDocument document = XDocument.Parse(xml); XElement quizNode = document.Element("quiz"); XAttribute nameAttribute = quizNode.Attribute("name"); if (nameAttribute != null) quizName = nameAttribute.Value; rounds = quizNode.Descendants("round") .Select(roundNode => new Round( roundNode.Attribute("name").Value, (PlayMode)Int32.Parse(roundNode.Attribute("playmode").Value), roundNode.Descendants("track") .Select(trackNode => trackRepository[trackNode.Value]) )); } catch (TrackNotFoundException ex) { throw new XmlException("Quiz contains a track not present in the track repository. " + ex.Filename); } catch (Exception ex) { throw new XmlException("Unable to read quiz.", ex); } // Create the quiz return new Quiz(quizName, creationDate, rounds); }
public void DeleteOneTrack() { Track trackDelete = new Track { Id = 3, Name = "Pepe", Image = "", Hour = 2, MinSeconds = 30.1 }; listTrack.Add(trackDelete); var options = new DbContextOptionsBuilder <BetterCalmContext>() .UseInMemoryDatabase(databaseName: "MSP.BetterCalmDatabase").Options; var context = new BetterCalmContext(options); listTrack.ForEach(track => context.Add(track)); context.SaveChanges(); repository = new TrackRepository(context); repository.Delete(trackDelete); context.Database.EnsureDeleted(); Track getTrack = repository.Get(3); Assert.AreEqual(null, getTrack); }
public static async void Run([TimerTrigger("*/10 * * * * *")] TimerInfo myTimer, TraceWriter log) { try { List <TrackAuth> tracks = await TrackRepository.GetRateLimitedTracks(); int count = 0; foreach (var track in tracks) { int postsLastHour = await PostRepository.PostsLastHourCount(track.RowKey); if (postsLastHour <= track.rate_limit) { track.rate_limit_exceeded = false; TrackRepository.UpdateTrack(track); count++; } } log.Info($"Removed rate limit on {count} tracks."); } catch (Exception e) { log.Error(e.Message); } }
public UnitOfWork(IDbFactory dbFactory) { this.dbFactory = dbFactory; Levels = new LevelRepository(dbFactory); Locations = new LocationRepository(dbFactory); Tracks = new TrackRepository(dbFactory); Seminars = new SeminarRepository(dbFactory); }
public TestCustomer() { _ChinookEntities = new ChinookEntities(); _CustomerRepo = new CustomerRepository(_ChinookEntities); _TrackRepo = new TrackRepository(_ChinookEntities); _PlayListRepo = new PlaylistRepository(_ChinookEntities); }
public void ViewTracks(IMainController _mainController, IShowTracksView inForm) { TrackRepository _trackRepository = TrackRepository.GetInstance(); List <Track> tracks = _trackRepository.GetAllActiveTracks(); inForm.ShowModaless(_mainController, tracks); }
/// <summary> /// Loads the track repository. /// </summary> /// <returns></returns> public async Task LoadTrackRepository() { StorageFolder musicPath = KnownFolders.MusicLibrary; StorageFile file = await musicPath.GetFileAsync("ttq_repository.xml"); using (Stream stream = await file.OpenStreamForReadAsync()) _trackRepository = TrackRepository.FromXml(stream); }
public LastFMImportJob() { _context = new ApplicationDbContext(); _userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(_context)); _artistRepository = new ArtistRepository(_context); _albumRepository = new AlbumRepository(_context); _trackRepository = new TrackRepository(_context); }
/// <summary> /// DeleteTrackButton action /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <remarks> /// Delete indicated track /// </remarks> private void DeleteTrackButton_Click(object sender, RoutedEventArgs e) { var trackRepo = new TrackRepository(); Track track = displayTracks.SelectedItem as Track; trackRepo.DeleteTrack(track.TrackId); this.NavigationService.Navigate(new DisplayTrackPage(track.ArtistId)); }
public void TrackDataProviderTests() { TestConstants.Prepare(); using (var pluginHost = new Plugins()) { pluginHost.PluginDirectory = TestConstants.SimulatorsBinFolder; pluginHost.Load(); Assert.Greater(pluginHost.Simulators.Count, 0); var testSim = pluginHost.Simulators[0]; var w = new Stopwatch(); w.Start(); var mem = GC.GetTotalMemory(true); var trackRepo = new TrackRepository(testSim.TrackProvider); var tracks = trackRepo.GetIds().Count(); w.Stop(); Debug.WriteLine("[TIME] Retrieving ID list (" + tracks + ") costs " + w.ElapsedMilliseconds + "ms"); w.Reset(); w.Start(); var Spa = trackRepo.GetByFile("67_SPA.GDB"); Assert.AreNotEqual(null, Spa); Debug.WriteLine(Spa.Name + " " + Spa.Length); w.Stop(); Debug.WriteLine("[TIME] Retrieving Spa 1967 costs " + w.ElapsedMilliseconds + "ms"); w.Reset(); // Building all tracks can take seconds. /*w.Start(); * foreach(var track in trackRepo.GetAll()) * Debug.WriteLine(track.Name + "=" + track.Length); * w.Stop(); * Debug.WriteLine("[TIME] Retrieving all tracks costs " + w.ElapsedMilliseconds + "ms");*/ w.Start(); Spa = trackRepo.GetByFile("67_SPA.GDB"); Assert.AreNotEqual(null, Spa); Debug.WriteLine(Spa.Name + " " + Spa.Length); w.Stop(); Debug.WriteLine("[TIME] Retrieving Spa 1967 costs " + w.ElapsedMilliseconds + "ms"); Assert.LessOrEqual(w.ElapsedMilliseconds, 1); w.Reset(); var dmem = GC.GetTotalMemory(true) - mem; Debug.WriteLine(dmem); w.Reset(); } }
public void Test_AddingSameTrackReferenceTwice() { TrackRepository trackRepository = TrackRepository.GetInstance(); Track track = new Track(trackRepository.GetNewID(), "Monza", "Italy", 1000); trackRepository.AddTrack(track); trackRepository.AddTrack(track); }
public async Task <IActionResult> OnGetAsync(string id) { var user = await _userManager.GetUserAsync(User); CurrentUser = user ?? throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); Track = await TrackRepository.GetTrackVerifyOwner(id, user.Id); return(Page()); }
public UnitOfWork() { ArticleRepo = new ArtisteRepository(_ChinookEntities); CustomerRepo = new CustomerRepository(_ChinookEntities); EmployeeRepo = new EmployeeRepository(_ChinookEntities); InvoiceRepo = new InvoiceRepository(_ChinookEntities); PlaylistRepo = new PlaylistRepository(_ChinookEntities); TrackRepo = new TrackRepository(_ChinookEntities); }
public void TrackDataProviderTests() { TestConstants.Prepare(); using (var pluginHost = new Plugins()) { pluginHost.PluginDirectory = TestConstants.SimulatorsBinFolder; pluginHost.Load(); Assert.Greater(pluginHost.Simulators.Count, 0); var testSim = pluginHost.Simulators[0]; var w = new Stopwatch(); w.Start(); var mem = GC.GetTotalMemory(true); var trackRepo = new TrackRepository(testSim.TrackProvider); var tracks = trackRepo.GetIds().Count(); w.Stop(); Debug.WriteLine("[TIME] Retrieving ID list (" + tracks + ") costs " + w.ElapsedMilliseconds + "ms"); w.Reset(); w.Start(); var Spa = trackRepo.GetByFile("67_SPA.GDB"); Assert.AreNotEqual(null, Spa); Debug.WriteLine(Spa.Name + " " + Spa.Length); w.Stop(); Debug.WriteLine("[TIME] Retrieving Spa 1967 costs " + w.ElapsedMilliseconds + "ms"); w.Reset(); // Building all tracks can take seconds. /*w.Start(); foreach(var track in trackRepo.GetAll()) Debug.WriteLine(track.Name + "=" + track.Length); w.Stop(); Debug.WriteLine("[TIME] Retrieving all tracks costs " + w.ElapsedMilliseconds + "ms");*/ w.Start(); Spa = trackRepo.GetByFile("67_SPA.GDB"); Assert.AreNotEqual(null, Spa); Debug.WriteLine(Spa.Name + " " + Spa.Length); w.Stop(); Debug.WriteLine("[TIME] Retrieving Spa 1967 costs " + w.ElapsedMilliseconds + "ms"); Assert.LessOrEqual(w.ElapsedMilliseconds, 1); w.Reset(); var dmem = GC.GetTotalMemory(true) - mem; Debug.WriteLine(dmem); w.Reset(); } }
public void Dispose_disposes_context() { var context = new Mock <ISlotCarContext>(); using (var repository = new TrackRepository(context.Object)) { } context.Verify(c => c.Dispose()); }
EditTrackRepository CreateEditRepository(TrackRepository repo) { if (!this.configsReader.HasConfig(repo.ConfigName)) return null; return new EditTrackRepository() { Name = repo.Name, ConfigName = repo.ConfigName, RepoConfig = repo.ConfigName != null ? this.configsReader[repo.ConfigName] : null, Token = repo.Token, LocalPath = repo.LocalPath, }; }
public UnitOfWork(DatabaseContext context) { _context = context; //no olvidar inicializar Artisit = new ArtitsRepository(_context); Tracks = new TrackRepository(_context); playlist = new Repository <Playlist>(_context); Genre = new Repository <Genre>(_context); MediaType = new Repository <MediaType>(_context); Album = new Repository <Album>(_context); }
public async Task DotMemoryUnitTest() { var repo = new TrackRepository(); await repo.GetAllAsync(); dotMemory.Check(memory => Assert.Equal(1, memory.GetObjects(where => where.Type.Is <Track>()).ObjectsCount)); GC.KeepAlive(repo); // prevent objects from GC if this is implied by test logic }
private (AppDbContext, ITrackRepository) Initialize(string DbName) { var options = new DbContextOptionsBuilder <AppDbContext>() .UseInMemoryDatabase(databaseName: DbName) .Options; var context = new AppDbContext(options); var query = new TrackRepository(context); return(context, query); }
EditTrackRepository CreateEditRepository(TrackRepository repo) { return(new EditTrackRepository() { Name = repo.Name, ConfigName = repo.ConfigName, RepoConfig = repo.ConfigName != null ? this.configsReader[repo.ConfigName] : null, Token = repo.Token, LocalPath = repo.LocalPath, }); }
public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "track/{trackId}/follow")] HttpRequest req, string trackId, TraceWriter log) { try { // check postId and trackId provided if (!Tools.IsValidGuid(trackId)) { return(new UnauthorizedResult()); } string authToken = req.Headers["Authorization"]; if (authToken == null) { return(new UnauthorizedResult()); } // validate authKey AuthClaim authClaim = AuthRepository.ValidateAuthClaim(authToken); if (authClaim == null) { return(new UnauthorizedResult()); } // get the track TrackAuth track = await TrackRepository.GetTrack(trackId); if (track == null || (track.is_private && track.PartitionKey != authClaim.user_id)) { return(new UnauthorizedResult()); } // trackFollow body string requestBody = new StreamReader(req.Body).ReadToEnd(); TrackFollowDTO dto = JsonConvert.DeserializeObject <TrackFollowDTO>(requestBody); // insert or update the follow TrackFollow trackFollow = new TrackFollow(); trackFollow.feed_follow_type = dto.feed?.ToLower() == "all" || dto.feed?.ToLower() == "none" ? dto.feed.ToLower() : null; trackFollow.notifications_follow_type = dto.notifications?.ToLower() == "all" || dto.notifications?.ToLower() == "none" ? dto.notifications.ToLower() : null; trackFollow.criteria = dto.criteria; trackFollow.user_id = authClaim.user_id; trackFollow.track_id = track.RowKey; FollowRepository.InsertOrReplaceTrackFollow(trackFollow); return(new OkResult()); } catch (Exception e) { log.Error(e.Message); return(new UnauthorizedResult()); } }
public async void LoadTracks() { tracks = await TrackRepository.GetTracksAlbum(album.idAlbum); foreach (var track in tracks) { track.indexRow = tracks.IndexOf(track) + 1; } ListView_tracks.ItemsSource = tracks; }
public UnitOfWork(DatabaseContext context) { _context = context; // no olvidar inicializar todos los repositorios que se van a utilizar en este unit of work Artists = new ArtistRepository(_context); Tracks = new TrackRepository(_context); Playlists = new Repository <Playlist>(_context); Genres = new Repository <Genre>(_context); MediaTypes = new Repository <MediaType>(_context); Albums = new Repository <Album>(_context); }
protected void OnButtonFromTrackClicked(object sender, EventArgs e) { var track = TrackRepository.GetTrackForRouteList(UoW, Entity.Id); if (track == null) { ServicesConfig.InteractiveService.ShowMessage(ImportanceLevel.Warning, "Невозможно расчитать растояние, так как в маршрутном листе нет трека", ""); return; } Entity.ConfirmedDistance = (decimal)track.TotalDistance.Value; }
public void TrackRepositoryGetTracks_PathWithNoData_ReturnZeroLengthList_Test() { var repository = new TrackRepository("unidentified"); var result = repository.GetTracks(); Assert.IsNotNull(result); Assert.AreEqual(0, result.Count); Assert.IsTrue(Directory.Exists("unidentified")); Directory.Delete("unidentified", true); }
public void TrackRepositoryGetTracks_CorrectPath_ReturnCorrectlySavedData_Test() { var repository = new TrackRepository("trackrepo"); var result = repository.GetTracks(); Assert.IsNotNull(result); Assert.AreEqual(_testList.Count, result.Count); for (int i = 0; i < _testList.Count; i++) { Assert.AreEqual(_testList[i].CreatedDateTime, result[i].CreatedDateTime); Assert.AreEqual(_testList[i].Artist, result[i].Artist); Assert.AreEqual(_testList[i].Duration, result[i].Duration); Assert.AreEqual(_testList[i].Id, result[i].Id); Assert.AreEqual(_testList[i].OwnerId, result[i].OwnerId); Assert.AreEqual(_testList[i].Title, result[i].Title); } }
/// <summary> /// Metodo encargado de inicializar la biblioteca, carga los datos de las canciones desde la base de datos /// </summary> public void InitializeLibrary() { FileManager fileManager =new FileManager(); fileManager.CreateUserDirectory(); SessionManager sessionManager = SessionManager.Instance; TrackRepository trackRepo = new TrackRepository(); UserTrackRepository userTrackRepo =new UserTrackRepository(); List<Track> userStoredTracks= trackRepo.GetTraksByUserId(sessionManager.UserId); foreach (var userTrack in userStoredTracks) { TrackInfo trackInfo =new TrackInfo() {Title = userTrack.Title,TrackId = userTrack.TrackID,AlbumTitle = userTrack.Album.Title, ArtistTitle = userTrack.Album.Artist.Title,SongPath = userTrack.Path,Year = userTrack.Album.ReleaseYear, Lyric = userTrack.Lyrics,Genre = userTrack.Genre}; trackInfo.isSynced = userTrackRepo.GetUserTrackByPK(sessionManager.UserId,trackInfo.TrackId).IsSync; this.userTracks.Add(trackInfo); } trackRepo.Dispose(); userTrackRepo.Dispose(); }
public void TrackRepositorySaveTracks_CorrectPath_SuccessfullyEnd_Test() { var repository = new TrackRepository("trackrepo"); repository.SaveTracks(_testList); }
/// <summary> /// Metodo encargado de interactuar con la capa de datos para realizar las inserciones en la base de datos local /// </summary> /// <param name="tracksToInsert">Lista de tracks por ingresar</param> private void InsertIntoDatabase(List<TrackInfo> tracksToInsert) { ArtistRepository artistRepo = new ArtistRepository(); AlbumRepository albumRepo =new AlbumRepository(); TrackRepository trackRepo =new TrackRepository(); UserTrackRepository usertracksRepo = new UserTrackRepository(); foreach (TrackInfo trackInfo in tracksToInsert) { Artist trackArtist = GetArtistByTitle(trackInfo.ArtistTitle); if (trackArtist == null) { //Creates new artist and insert into database trackArtist = new Artist() {ArtistID = Guid.NewGuid(), Title = trackInfo.ArtistTitle}; artistRepo.Add(trackArtist); artistRepo.SaveChanges(); } else { //artistRepo.Attach(trackArtist); } Album trackAlbum = GetAlbumByTitleAndArtistTitle(trackInfo.AlbumTitle,trackArtist.Title); if (trackAlbum == null) { //Set trackAlbum as new Album trackAlbum= new Album() {AlbumID = Guid.NewGuid(),ArtistID = trackArtist.ArtistID,Title = trackInfo.AlbumTitle, ReleaseYear = trackInfo.Year}; albumRepo.Add(trackAlbum); albumRepo.SaveChanges(); } else { //albumRepo.Attach(trackAlbum); } //Creates new track Track newTrack=new Track() {AlbumID = trackAlbum.AlbumID,Title = trackInfo.Title, Genre =trackInfo.Genre,Lyrics = trackInfo.Lyric,Path = trackInfo.SongPath,TrackID = trackInfo.TrackId}; usertracksRepo.Add(new UserTrack() {UserID = SessionManager.Instance.UserId,TrackID = trackRepo.Add(newTrack).TrackID,IsSync = false}); //artistRepo.SaveChanges(); trackRepo.SaveChanges(); } usertracksRepo.SaveChanges(); artistRepo.Dispose(); trackRepo.Dispose(); usertracksRepo.Dispose(); }