public static IQueryable<ArtistForAlbum> WhereHasArtistParticipationStatus(this IQueryable<ArtistForAlbum> query, Artist artist, ArtistAlbumParticipationStatus participation) {

			if (participation == ArtistAlbumParticipationStatus.Everything || artist == null)
				return query;

			var musicProducerTypes = new[] {ArtistType.Producer, ArtistType.Circle, ArtistType.OtherGroup};

			if (musicProducerTypes.Contains(artist.ArtistType)) {

				var producerRoles = ArtistRoles.Composer | ArtistRoles.Arranger;

				switch (participation) {
					case ArtistAlbumParticipationStatus.OnlyMainAlbums:
						return query.Where(a => !a.IsSupport && ((a.Roles == ArtistRoles.Default) || ((a.Roles & producerRoles) != ArtistRoles.Default)) && a.Album.ArtistString.Default != ArtistHelper.VariousArtists);
					case ArtistAlbumParticipationStatus.OnlyCollaborations:
						return query.Where(a => a.IsSupport || ((a.Roles != ArtistRoles.Default) && ((a.Roles & producerRoles) == ArtistRoles.Default)) || a.Album.ArtistString.Default == ArtistHelper.VariousArtists);
					default:
						return query;
				}

			} else {

				switch (participation) {
					case ArtistAlbumParticipationStatus.OnlyMainAlbums:
						return query.Where(a => !a.IsSupport);
					case ArtistAlbumParticipationStatus.OnlyCollaborations:
						return query.Where(a => a.IsSupport);
					default:
						return query;
				}
				
			}

		}
        public ArtistWithArchivedVersionsContract(Artist artist, ContentLanguagePreference languagePreference)
            : base(artist, languagePreference)
        {
            ParamIs.NotNull(() => artist);

            ArchivedVersions = artist.ArchivedVersionsManager.Versions.Select(a => new ArchivedArtistVersionContract(a)).ToArray();
        }
Exemplo n.º 3
0
        public HomeModule()
        {
            Get["/"] = _ => {
            var allCDs = CD.GetAllCDs();
            return View["index.cshtml", allCDs];
              };
            // view the mainpage, taking all the CDs as model
            Get["/cd/new"] = _ => {
            return View["addCD.cshtml"];
            };
            //if you get CD/new, take to add CD form//
            Post["/cdAdded"] = _ => {
             var newCD = new CD(Request.Form["cd-title"], Request.Form["cd-artist"], Request.Form["cd-year"], Request.Form["cd-cover"]);
             var newArtist = new Artist(Request.Form["cd-artist"]);
             newArtist.AddArtistCD(newCD);
             return View["cdAdded.cshtml", newCD];
               };

               Get["/searchbyartist"] = _ => {
             return View["searchByArtist.cshtml"];
               };

               Post["/searchresults"] = _ => {
            var selectedArtist = Artist.Find(Request.Form["artist-name"]);
            List<CD> resultCDs = selectedArtist.GetAllArtistsCDs();
            return View["searchResults.cshtml", resultCDs];
              };
        }
Exemplo n.º 4
0
 public ArtistViewModel(Artist a)
     : base(a)
 {
     artist = a;
     TypeImage = "\xe13d";
     InitLogo(string.Format("artist_{0}.jpg", Id));
 }
Exemplo n.º 5
0
        public void AddOwnedArtist_AlreadyAdded()
        {
            var artist = new Artist { Id = 1 };

            user.AddOwnedArtist(artist);
            user.AddOwnedArtist(artist);
        }
   public int AddArtist(ArtistLite al)
   {
       int result = 1;
       Artist a = new Artist();
       a.ArtistName = al.ArtistName;
       a.ArtistEmail = al.Email;
       a.ArtistWebPage = al.WebPage;
       a.ArtistDateEntered = DateTime.Now;


       try
       {

           st.Artists.Add(a);
           st.SaveChanges();
       }
       catch (Exception ex)
       {
           result = 0;
           throw ex;
       }

       return result;
      
   }
		public EntryRefWithCommonPropertiesContract(Artist entry, ContentLanguagePreference languagePreference)
			: base(entry, languagePreference) {

			ArtistString = null;
			EntryTypeName = ArtistTypeNames.ResourceManager.GetString(entry.ArtistType.ToString());

		}
        public Artist Save(Artist artist)
        {
            Artist artistDB = null;
            if (artist == null)
            {
                throw new ArgumentException("Cannot save null artist");
            }
            try
            {
                StartTx();
                if (artist.Id == null)
                {
                    artistDB = artistDao.Persist(artist);
                }
                else
                {
                    artistDB = artistDao.ById(artist.Id);
                    if (artistDB.Deleted)
                    {
                        throw new EntityNotFoundException();
                    }
                    artistDB = artistDao.Update(artist);
                }
                CommitTx();
            }
            catch (Exception e)
            {
                RollbackTx();
                throw e;
            }

            return artistDB;
        }
Exemplo n.º 9
0
        public ActionResult AddArtist(ArtistModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    Artist artist = new Artist();
                    artist.ArtistId = model.yearDropDownId;
                    artist.ArtistFirstName = model.FirstName;
                    artist.ArtistLastName = model.LastName;

                    dataService.ArtistService.AddNew(artist);
                    ViewBag.ThankYou = model.FirstName + " " + model.LastName + " has been successfully added.";
                    return View("ThankYou");

                }
                catch (Exception e)
                {
                    ViewBag.ErrorMessage = e.InnerException;
                    return View("Error");

                }
            }
            else
            {
                ViewBag.ErrorMessage = "Invalid Model State";
                return View("Error");
            }
        }
Exemplo n.º 10
0
        public IHttpActionResult PutArtist(int id, Artist artist)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != artist.ArtistId)
            {
                return BadRequest();
            }

            //db.Entry(artist).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ArtistExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
Exemplo n.º 11
0
		public ArtistReport(Artist artist, ArtistReportType reportType, User user, string hostname, string notes)
			: base(user, hostname, notes) {

			Artist = artist;
			ReportType = reportType;

		}
Exemplo n.º 12
0
		public void SetUp() {

			artist = CreateEntry.Producer(name: "Tripshots");
			repository = new FakeArtistRepository(artist);

			foreach (var name in artist.Names)
				repository.Save(name);

			user = CreateEntry.User(name: "Miku");
			repository.Save(user);
			permissionContext = new FakePermissionContext(user);
			imagePersister = new InMemoryImagePersister();

			queries = new ArtistQueries(repository, permissionContext, new FakeEntryLinkFactory(), imagePersister, MemoryCache.Default);

			newArtistContract = new CreateArtistContract {
				ArtistType = ArtistType.Producer,
				Description = string.Empty,
				Names = new[] {
					new LocalizedStringContract("Tripshots", ContentLanguageSelection.English)
				},
				WebLink = new WebLinkContract("http://tripshots.net/", "Website", WebLinkCategory.Official)
			};

		}
Exemplo n.º 13
0
		public void Create() {

			var result = queries.Create(newArtistContract);

			Assert.IsNotNull(result, "result");
			Assert.AreEqual("Tripshots", result.Name, "Name");

			artist = repository.Load(result.Id);

			Assert.IsNotNull(artist, "Artist was saved to repository");
			Assert.AreEqual("Tripshots", artist.DefaultName, "Name");
			Assert.AreEqual(ContentLanguageSelection.English, artist.Names.SortNames.DefaultLanguage, "Default language should be English");
			Assert.AreEqual(1, artist.WebLinks.Count, "Weblinks count");

			var archivedVersion = repository.List<ArchivedArtistVersion>().FirstOrDefault();

			Assert.IsNotNull(archivedVersion, "Archived version was created");
			Assert.AreEqual(artist, archivedVersion.Artist, "Archived version artist");
			Assert.AreEqual(ArtistArchiveReason.Created, archivedVersion.Reason, "Archived version reason");

			var activityEntry = repository.List<ActivityEntry>().FirstOrDefault();

			Assert.IsNotNull(activityEntry, "Activity entry was created");
			Assert.AreEqual(artist, activityEntry.EntryBase, "Activity entry's entry");
			Assert.AreEqual(EntryEditEvent.Created, activityEntry.EditEvent, "Activity entry event type");

		}
Exemplo n.º 14
0
		private string CreateMessageBody(Artist[] followedArtists, User user, IEntryWithNames entry, IEntryLinkFactory entryLinkFactory, bool markdown) {
			
			var entryTypeName = entry.EntryType.ToString().ToLowerInvariant();
			var entryName = entry.Names.SortNames[user.DefaultLanguageSelection];
			var url = entryLinkFactory.GetFullEntryUrl(entry);

			string entryLink;
			if (markdown) {
				entryLink = MarkdownHelper.CreateMarkdownLink(url, entryName);
			} else {
				entryLink = string.Format("{0} ( {1} )", entryName, url);
			}

			string msg;

			if (followedArtists.Length == 1) {

				var artistName = followedArtists.First().TranslatedName[user.DefaultLanguageSelection];
				msg = string.Format("A new {0}, '{1}', by {2} was just added.",
					entryTypeName, entryLink, artistName);

			} else {

				msg = string.Format("A new {0}, '{1}', by multiple artists you're following was just added.",
					entryTypeName, entryLink);

			}

			msg += "\nYou're receiving this notification because you're following the artist(s).";
			return msg;

		}
Exemplo n.º 15
0
		public EntryForApiContract(Artist artist, ContentLanguagePreference languagePreference, IEntryThumbPersister thumbPersister, bool ssl, 
			EntryOptionalFields includedFields)
			: this(artist, languagePreference) {

			ArtistType = artist.ArtistType;			
			CreateDate = artist.CreateDate;
			Status = artist.Status;

			if (includedFields.HasFlag(EntryOptionalFields.MainPicture) && artist.Picture != null) {
				MainPicture = new EntryThumbForApiContract(new EntryThumb(artist, artist.PictureMime), thumbPersister, ssl);					
			}

			if (includedFields.HasFlag(EntryOptionalFields.Names)) {
				Names = artist.Names.Select(n => new LocalizedStringContract(n)).ToArray();				
			}

			if (includedFields.HasFlag(EntryOptionalFields.Tags)) {
				Tags = artist.Tags.Usages.Select(u => new TagUsageForApiContract(u)).ToArray();				
			}

			if (includedFields.HasFlag(EntryOptionalFields.WebLinks)) {
				WebLinks = artist.WebLinks.Select(w => new ArchivedWebLinkContract(w)).ToArray();				
			}

		}
Exemplo n.º 16
0
        private void addArtistButton_Click(object sender, System.EventArgs e)
        {
            var repository = new CDCatalogRepository();
            var formHelper = new FormHelper();

            if (!formHelper.TextBoxHasContents(addArtistTxtBoxArtistName))
            {
                MessageBox.Show("Please enter an artist name.", "Input validation error");
                addArtistTxtBoxArtistName.Focus();
            }
            else
            {
                var newArtist = addArtistTxtBoxArtistName.Text.Trim();
                var artists = repository.SearchArtistByArtistNameExclusive(newArtist);

                if (artists.Count > 0)
                {
                    MessageBox.Show("You wanted to add " + newArtist + ", but " + artists[0].ArtistName + " already exsists.", "Artist must be unique");
                    addArtistTxtBoxArtistName.Focus();
                }
                else
                {
                    CreatedArtist = repository.CreateArtist(addArtistTxtBoxArtistName.Text.Trim());
                    this.Close();
                }
            }
        }
Exemplo n.º 17
0
        // PUT api/Artist/5
        public HttpResponseMessage PutArtist(int id, Artist artist)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != artist.Id)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            db.Entry(artist).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }
Exemplo n.º 18
0
 public PlayListElems(Artist aid, Album alid, TrackList trid)
 {
     artistName = (string)aid.artistName;
     albumName = (string)alid.albumName;
     trackNum = (string)trid.trackNum;
     trackName = (string)trid.trackName;
 }
Exemplo n.º 19
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ArtistEvent atd = new ArtistEvent();

            atd.EventID = Convert.ToInt32( ddlTourDate.SelectedValue );

            Artist art = new Artist();

            if (ddlArtist1.SelectedValue != unknownValue && !string.IsNullOrEmpty( ddlArtist1.SelectedValue ))
            {
                art = new Artist(ddlArtist1.SelectedValue);
                atd.ArtistID = art.ArtistID;
                atd.RankOrder = 1;
                atd.Create();

                if (ddlArtist2.SelectedValue != unknownValue && !string.IsNullOrEmpty(ddlArtist2.SelectedValue))
                {
                    art = new Artist(ddlArtist2.SelectedValue);
                    atd.ArtistID = art.ArtistID;
                    atd.RankOrder = 2;
                    atd.Create();

                    if (ddlArtist3.SelectedValue != unknownValue && !string.IsNullOrEmpty(ddlArtist3.SelectedValue))
                    {
                        art = new Artist(ddlArtist3.SelectedValue);
                        atd.ArtistID = art.ArtistID;
                        atd.ArtistID = Convert.ToInt32(ddlArtist3.SelectedValue);
                        atd.RankOrder = 3;
                        atd.Create();
                    }

                }

            }
        }
Exemplo n.º 20
0
		public void Setup() {

			artist = new Artist(TranslatedString.Create("Minato")) { Id = 1, ArtistType = ArtistType.Producer };
			song = new Song(new LocalizedString("Soar", ContentLanguageSelection.English));
			lyrics = song.CreateLyrics(ContentLanguageSelection.Japanese, "Miku!", "miku");

		}
Exemplo n.º 21
0
		public ArtistForUser(User user, Artist artist)
			: this() {

			User = user;
			Artist = artist;

		}
Exemplo n.º 22
0
 public PlayListElems(Artist aid, Album alid, TrackList trid)
 {
     ArtistName = (string)aid.ArtistName;
     AlbumName = (string)alid.AlbumName;
     TrackNum = (string)trid.TrackNum;
     TrackName = (string)trid.TrackName;
 }
Exemplo n.º 23
0
		private IArtistWithSupport CreateArtist(ArtistType artistType, string name) {

			var p = new Artist { ArtistType = artistType };
			p.Names.Add(new ArtistName(p, new LocalizedString(name, ContentLanguageSelection.English)));
			return p.AddAlbum(new Album());

		}
Exemplo n.º 24
0
        public HttpResponseMessage Update(int id, Artist artist)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != artist.Id)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            this.uow.ArtistsRepository.Update(artist);

            try
            {
                this.uow.Commit();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK, new ArtistApi(artist));
        }
Exemplo n.º 25
0
		private void Seed(ISessionFactory sessionFactory) {
			
			using (var session = sessionFactory.OpenSession())
			using (var tx = session.BeginTransaction()) {
				
				Producer = new Artist(TranslatedString.Create("Junk")) { Id = ProducerId };
				session.Save(Producer);

				Producer2 = new Artist(TranslatedString.Create("Junky"));
				session.Save(Producer2);

				Producer3 = new Artist(TranslatedString.Create("Keeno"));
				session.Save(Producer3);

				var tag = new Tag("Electronic");
				session.Save(tag);

				Song = new Song(new LocalizedString("Nebula", ContentLanguageSelection.English)) {
					Id = SongId, SongType = SongType.Original, FavoritedTimes = 1, PVServices = PVServices.Youtube, CreateDate = new DateTime(2012, 6, 1)
				};
				Song.Lyrics.Add(new LyricsForSong(Song, ContentLanguageSelection.English, "Here be lyrics", string.Empty));
				Song.Tags.Usages.Add(new SongTagUsage(Song, tag));
				session.Save(Song);

				Song2 = new Song(new LocalizedString("Tears of Palm", ContentLanguageSelection.English)) {
					Id = Song2Id, SongType = SongType.Original, PVServices = PVServices.Youtube, CreateDate = new DateTime(2012, 6, 1)
				};
				Song2.Lyrics.Add(new LyricsForSong(Song2, ContentLanguageSelection.Romaji, "Here be lyrics", string.Empty));
				session.Save(Song2);

				Song3 = new Song(new LocalizedString("Crystal Tears", ContentLanguageSelection.English)) {
					Id = SongWithArtistId, FavoritedTimes = 39, CreateDate = new DateTime(2012, 1, 1)
				};
				Song3.AddArtist(Producer);
				session.Save(Song3);

				Song4 = new Song(new LocalizedString("Azalea", ContentLanguageSelection.English)) {
					CreateDate = new DateTime(2012, 1, 1)
				};
				Song4.AddArtist(Producer);
				session.Save(Song4);

				Song5 = new Song(new LocalizedString("Melancholic", ContentLanguageSelection.English)) {
					CreateDate = new DateTime(2012, 1, 1)
				};
				Song5.AddArtist(Producer2);
				session.Save(Song5);

				Song6 = new Song(new LocalizedString("Tears", ContentLanguageSelection.English)) {
					CreateDate = new DateTime(2012, 1, 1)
				};
				Song6.AddArtist(Producer3);
				session.Save(Song6);

				tx.Commit();

			}

		}
Exemplo n.º 26
0
        private static void AddArtists()
        {
            var artist1 = new Artist { Name = "Artist1", Country = "Bulgaria", DateOfBirth = DateTime.Now };
            var artist2 = new Artist { Name = "Artist2", Country = "Germany", DateOfBirth = DateTime.Now };

            MusicStoreClient.Add(artist1);
            MusicStoreClient.Add(artist2);
        }
Exemplo n.º 27
0
        public static AlbumResponse GetAlbumsForArtist(Artist a)
        {
            string url = string.Format("{0}artist.getAlbums?artistCode={1}&sort=desc&country=us&format=json&apikey={2}", BaseUrl, a.artistCode, Credentials.PlayMeApiKey);
            string result = ExecuteGetCommand(url);

            AlbumResponseWrapper r = (AlbumResponseWrapper)JsonConvert.Import(typeof(AlbumResponseWrapper), result);
            return r.response;
        }
Exemplo n.º 28
0
        public void Create(Artist artist)
        {
            using (var session = _sessionManager.OpenSession())
            {
                session.Session.Set<Artist>().Add(artist);

            }
        }
Exemplo n.º 29
0
 public HttpResult Put(Artist request)
 {
     Db.Update(request);
     return new HttpResult(HttpStatusCode.NoContent)
     {
         Headers = { { HttpHeaders.Location, Request.AbsoluteUri.CombineWith(request.ArtistId.ToString()) } }
     };
 }
Exemplo n.º 30
0
 public API(string apiKey)
 {
     Key = apiKey;
       Track = new Track();
       Artist = new Artist();
       Album = new Album();
       Discography = new Discography();
 }
Exemplo n.º 31
0
 public Artist Agregar(Artist artist)
 {
     return(db.Create(artist));
 }
Exemplo n.º 32
0
 public void Remove(Artist artist)
 {
     context.Artists.Remove(artist);
     context.SaveChanges();
 }
Exemplo n.º 33
0
        public Entry ConvertPerson(Person tmdbPerson)
        {
            // checks
            if (tmdbPerson == null)
            {
                return(DefaultEntry.Instance);
            }

            if (string.IsNullOrEmpty(tmdbPerson.Name))
            {
                return(DefaultEntry.Instance);
            }

            if (!tmdbPerson.Birthday.HasValue)
            {
                return(DefaultEntry.Instance);
            }

            if (string.IsNullOrEmpty(tmdbPerson.ProfilePath))
            {
                return(DefaultEntry.Instance);
            }

            if (tmdbPerson.Popularity < MinPopularity)
            {
                return(DefaultEntry.Instance);
            }

            // build basic values
            var id     = Id.FromArtistNumber(tmdbPerson.Id);
            var artist = new Artist(id)
            {
                Biography     = tmdbPerson.Biography,
                Birthday      = tmdbPerson.Birthday.Value,
                Deathday      = tmdbPerson.Deathday,
                ImdbId        = tmdbPerson.ImdbId,
                MainImagePath = tmdbPerson.ProfilePath,
                Name          = tmdbPerson.Name,
                NickNames     = new List <string>(tmdbPerson.AlsoKnownAs),
                Popularity    = tmdbPerson.Popularity,
            };

            // TODO: create the connections

            //foreach (var cast in tmdbPerson.MovieCredits.Cast.Where(c => c.!string.IsNullOrEmpty(c.PosterPath)))
            //{
            //    var id = cast.MediaType == "tv"
            //        ? nameof(TvSeries) + IdSeparator + cast.Id
            //        : nameof(Movie) + IdSeparator + cast.Id;

            //    artist.Connections.Add(new Connection
            //    {
            //        ConnectedId = id,
            //        Type = ConnectionType.Actor,
            //        Label = cast.Character
            //    });
            //}

            //foreach (var cast in tmdbPerson.CombinedCredits.Crew.Where(c => !string.IsNullOrEmpty(c.PosterPath)))
            //{
            //    ConnectionType type;
            //    if (_handledCrewJobs.TryGetValue(cast.Job, out type))
            //    {
            //        artist.Connections.Add(new Connection
            //        {
            //            ConnectedId = nameof(Movie) + IdSeparator + cast.Id,
            //            Type = type,
            //            Label = cast.Job
            //        });
            //    }
            //    else
            //    {
            //        artist.Connections.Add(new Connection
            //        {
            //            ConnectedId = nameof(Movie) + IdSeparator + cast.Id,
            //            Type = ConnectionType.Crew,
            //            Label = cast.Job
            //        });
            //    }
            //}

            return(artist);
        }
Exemplo n.º 34
0
        public ActionResult Add()
        {
            var artist = new Artist();

            return(View(artist));
        }
Exemplo n.º 35
0
        public Piece Create(
            int recordNumber,
            string title,
            string accessionNumber,
            int?creationDay,
            int?creationMonth,
            int?creationYear,
            Country countryOfOrigin,
            string stateOfOrigin,
            string cityOfOrigin,
            double?height,
            double?width,
            double?depth,
            UnitOfMeasure unitOfMeasure,
            decimal?estimatedValue,
            string subject,
            int?copyrightYear,
            string copyrightOwner,
            string insurancePolicyNumber,
            DateTime?insuranceExpirationDate,
            decimal?insuanceAmount,
            string insuranceCarrier,
            bool isFramed,
            bool isArchived,
            Artist artist,
            Medium medium,
            Genre genre,
            Subgenre subgenre,
            SubjectMatter subjectMatter,
            Acquisition acquisition,
            Location currentLocation,
            Location permanentLocation,
            Collection collection,
            string lastModifiedByUserId,
            DateTime lastModified,
            int museumId)
        {
            var piece = new Piece();

            piece.RecordNumber            = recordNumber;
            piece.Title                   = title;
            piece.AccessionNumber         = accessionNumber;
            piece.CreationDay             = creationDay;
            piece.CreationMonth           = creationMonth;
            piece.CreationYear            = creationYear;
            piece.CountryOfOrigin         = countryOfOrigin;
            piece.StateOfOrigin           = stateOfOrigin;
            piece.CityOfOrigin            = cityOfOrigin;
            piece.Height                  = height;
            piece.Width                   = width;
            piece.Depth                   = depth;
            piece.UnitOfMeasure           = unitOfMeasure;
            piece.EstimatedValue          = estimatedValue;
            piece.Subject                 = subject;
            piece.CopyrightYear           = copyrightYear;
            piece.CopyrightOwner          = copyrightOwner;
            piece.InsurancePolicyNumber   = insurancePolicyNumber;
            piece.InsuranceExpirationDate = insuranceExpirationDate;
            piece.InsuranceAmount         = insuanceAmount;
            piece.InsuranceCarrier        = insuranceCarrier;
            piece.IsFramed                = isFramed;
            piece.IsArchived              = isArchived;
            piece.Artist                  = artist;
            piece.Medium                  = medium;
            piece.Genre                   = genre;
            piece.Subgenre                = subgenre;
            piece.SubjectMatter           = subjectMatter;
            piece.Acquisition             = acquisition;
            piece.CurrentLocation         = currentLocation;
            piece.PermanentLocation       = permanentLocation;
            piece.Collection              = collection;
            piece.ApplicationUserId       = lastModifiedByUserId;
            piece.LastModified            = lastModified;
            piece.MuseumId                = museumId;

            return(piece);
        }
Exemplo n.º 36
0
        private static async void LoadAdditionInfoAboutSongs()
        {
            var songs = await DataManager.GetSongsWithoutArtistType();

            foreach (var song in songs)
            {
                var response = await LastFm.Client.Track.GetInfoAsync(song.SongName, song.ArtistName);

                if (!response.Success || response.Content.AlbumName == null)
                {
                    continue;
                }

                Artist artist = null;
                while (artist == null)
                {
                    try
                    {
                        artist = await Artist.GetAsync(response.Content.ArtistMbid);
                    }
                    catch (Exception ex)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(2));
                    }
                }

                await Task.Delay(500);

                var lastAlbum = await LastFm.Client.Album.GetInfoAsync(song.ArtistName, response.Content.AlbumName);

                Release album = null;
                while (album == null)
                {
                    try
                    {
                        var release = await Release.GetAsync(lastAlbum.Content.Mbid);

                        if (release == null)
                        {
                            break;
                        }
                        album = release;
                    }
                    catch (Exception ex)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(2));
                    }
                }

                DateTime?songDate = null;
                if (album?.Date != null)
                {
                    int year;
                    if (int.TryParse(album.Date, out year))
                    {
                        songDate = new DateTime(year, 1, 1);
                    }
                    else
                    {
                        try
                        {
                            songDate = DateTime.Parse(album.Date);
                        }
                        catch (Exception ex)
                        {
                            // ignored
                        }
                    }
                }

                DateTime?artistBeginDate = null;
                if (artist.LifeSpan?.Begin != null)
                {
                    int year;
                    if (int.TryParse(artist.LifeSpan.Begin, out year))
                    {
                        artistBeginDate = new DateTime(year, 1, 1);
                    }
                    else
                    {
                        try
                        {
                            artistBeginDate = DateTime.Parse(artist.LifeSpan.Begin);
                        }
                        catch (Exception ex)
                        {
                            // ignored
                        }
                    }
                }

                var filter = Builders <DbEntry> .Filter.Eq(x => x.Id, song.Id);

                var updateQuery = Builders <DbEntry> .Update.Set(x => x.ArtistType, artist.ArtistType)
                                  .Set(x => x.ArtistBeginYear, artistBeginDate).Set(x => x.SongDate, songDate);

                var result = await DataManager.Collection.UpdateOneAsync(filter, updateQuery);

                Console.Out.WriteLine(song.ArtistName + " - " + song.SongName);
                await Task.Delay(TimeSpan.FromSeconds(2));
            }

            Console.Out.WriteLine("Done!");
        }
Exemplo n.º 37
0
 public void get_artist_by_unknown_id_should_return_404()
 {
     var result = Artist.InvalidGet(1000000);
 }
Exemplo n.º 38
0
    // Start is called before the first frame update
    //Grab all the painters assigned to the Painting to create probabilities
    void Start()
    {
        artist = new Artist(paintingPrefab);

        //InvokeRepeating("ShowNextPainting", 0, 3);
    }
Exemplo n.º 39
0
 public ArtistResource(Artist artist)
 {
     _artist = artist;
 }
Exemplo n.º 40
0
 public Artist EditarArtista(Artist artist)
 {
     return(db.Update(artist, artist.Id));
 }
Exemplo n.º 41
0
        /// <summary>
        /// Merge one Artist into another one
        /// </summary>
        /// <param name="ArtistToMerge">The Artist to be merged</param>
        /// <param name="artistToMergeInto">The Artist to merge into</param>
        /// <returns></returns>
        public async Task <OperationResult <Artist> > MergeArtists(Artist ArtistToMerge, Artist artistToMergeInto, bool doDbUpdates = false)
        {
            SimpleContract.Requires <ArgumentNullException>(ArtistToMerge != null, "Invalid Artist");
            SimpleContract.Requires <ArgumentNullException>(artistToMergeInto != null, "Invalid Artist");

            var result = false;
            var now    = DateTime.UtcNow;

            var sw = new Stopwatch();

            sw.Start();

            artistToMergeInto.RealName      = ArtistToMerge.RealName ?? artistToMergeInto.RealName;
            artistToMergeInto.MusicBrainzId = ArtistToMerge.MusicBrainzId ?? artistToMergeInto.MusicBrainzId;
            artistToMergeInto.ITunesId      = ArtistToMerge.ITunesId ?? artistToMergeInto.ITunesId;
            artistToMergeInto.AmgId         = ArtistToMerge.AmgId ?? artistToMergeInto.AmgId;
            artistToMergeInto.SpotifyId     = ArtistToMerge.SpotifyId ?? artistToMergeInto.SpotifyId;
            artistToMergeInto.Thumbnail     = ArtistToMerge.Thumbnail ?? artistToMergeInto.Thumbnail;
            artistToMergeInto.Profile       = ArtistToMerge.Profile ?? artistToMergeInto.Profile;
            artistToMergeInto.BirthDate     = ArtistToMerge.BirthDate ?? artistToMergeInto.BirthDate;
            artistToMergeInto.BeginDate     = ArtistToMerge.BeginDate ?? artistToMergeInto.BeginDate;
            artistToMergeInto.EndDate       = ArtistToMerge.EndDate ?? artistToMergeInto.EndDate;
            if (!string.IsNullOrEmpty(ArtistToMerge.ArtistType) && !ArtistToMerge.ArtistType.Equals("Other", StringComparison.OrdinalIgnoreCase))
            {
                artistToMergeInto.ArtistType = ArtistToMerge.ArtistType;
            }
            artistToMergeInto.BioContext = ArtistToMerge.BioContext ?? artistToMergeInto.BioContext;
            artistToMergeInto.DiscogsId  = ArtistToMerge.DiscogsId ?? artistToMergeInto.DiscogsId;

            artistToMergeInto.Tags = artistToMergeInto.Tags.AddToDelimitedList(ArtistToMerge.Tags.ToListFromDelimited());
            var altNames = ArtistToMerge.AlternateNames.ToListFromDelimited().ToList();

            altNames.Add(ArtistToMerge.Name);
            altNames.Add(ArtistToMerge.SortName);
            artistToMergeInto.AlternateNames = artistToMergeInto.AlternateNames.AddToDelimitedList(altNames);
            artistToMergeInto.URLs           = artistToMergeInto.URLs.AddToDelimitedList(ArtistToMerge.URLs.ToListFromDelimited());
            artistToMergeInto.ISNI           = artistToMergeInto.ISNI.AddToDelimitedList(ArtistToMerge.ISNI.ToListFromDelimited());
            artistToMergeInto.LastUpdated    = now;

            if (doDbUpdates)
            {
                string sql = null;

                sql = "UPDATE `artistGenreTable` set artistId = " + artistToMergeInto.Id + " WHERE artistId = " + ArtistToMerge.Id + ";";
                await this.DbContext.Database.ExecuteSqlCommandAsync(sql);

                sql = "UPDATE `image` set artistId = " + artistToMergeInto.Id + " WHERE artistId = " + ArtistToMerge.Id + ";";
                await this.DbContext.Database.ExecuteSqlCommandAsync(sql);

                sql = "UPDATE `userartist` set artistId = " + artistToMergeInto.Id + " WHERE artistId = " + ArtistToMerge.Id + ";";
                await this.DbContext.Database.ExecuteSqlCommandAsync(sql);

                sql = "UPDATE `track` set artistId = " + artistToMergeInto.Id + " WHERE artistId = " + ArtistToMerge.Id + ";";
                await this.DbContext.Database.ExecuteSqlCommandAsync(sql);

                try
                {
                    sql = "UPDATE `release` set artistId = " + artistToMergeInto.Id + " WHERE artistId = " + ArtistToMerge.Id + ";";
                    await this.DbContext.Database.ExecuteSqlCommandAsync(sql);
                }
                catch (Exception ex)
                {
                    this.Logger.LogWarning(ex.ToString());
                }
                var artistFolder = ArtistToMerge.ArtistFileFolder(this.Configuration, this.Configuration.LibraryFolder);
                foreach (var release in this.DbContext.Releases.Include("Artist").Where(x => x.ArtistId == ArtistToMerge.Id).ToArray())
                {
                    var originalReleaseFolder = release.ReleaseFileFolder(artistFolder);
                    await this.ReleaseFactory.Update(release, null, originalReleaseFolder);
                }

                await this.Delete(ArtistToMerge);
            }

            result = true;

            sw.Stop();
            return(new OperationResult <Artist>
            {
                Data = artistToMergeInto,
                IsSuccess = result,
                OperationTime = sw.ElapsedMilliseconds
            });
        }
Exemplo n.º 42
0
        private async Task RemoveTrackAsync(Track track)
        {
            //Track track = default;
            Album  album         = default;
            Artist artist        = default;
            var    albumDeleted  = false;
            var    artistDeleted = false;
            var    trackDeleted  = false;

            async Task RemoveTrackDbAsync()
            {
                //track = await db.Tracks.SingleAsync(x => x.Id == id);

                try
                {
                    album  = track.Album;
                    artist = album.Artist;
                    db.Tracks.Remove(track);
                    await db.SaveChangesAsync();

                    albumDeleted = album.Tracks.Count == 0;
                    if (albumDeleted)
                    {
                        db.Albums.Remove(album);
                        await db.SaveChangesAsync();

                        artistDeleted = artist.Albums.Count == 0;
                        if (artistDeleted)
                        {
                            db.Artists.Remove(artist);
                            await db.SaveChangesAsync();
                        }
                    }

                    trackDeleted = true;
                }
                catch (Exception)
                {
                    trackDeleted = false;
                }
            }

            async Task RemoveTrackVmAsync()
            {
                var artistVm = await ArtistSource.Items.SingleAsync(x => x.Id == artist.Id);

                var albumVm = await artistVm.Albums.Items.SingleAsync(x => x.Id == album.Id);

                //var trackVm = await albumVm.Tracks.Items.SingleAsync(x => x.Id == track.Id);
                albumVm.Tracks.RemoveKey(track.Id);
                if (albumDeleted)
                {
                    artistVm.Albums.RemoveKey(album.Id);
                    if (!string.IsNullOrEmpty(album.CoverCacheToken))
                    {
                        await CacheService.DeleteCacheAsync(album.CoverCacheToken);
                    }

                    if (artistDeleted)
                    {
                        _artistSource.RemoveKey(artist.Id);
                    }
                }
            }

            await RemoveTrackDbAsync();

            if (trackDeleted)
            {
                await RemoveTrackVmAsync();
            }
        }
Exemplo n.º 43
0
 public Task <List <Artist> > SearchArtist(Artist Artist)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 44
0
 /// <summary>
 /// Vérifie si cette Music est égale à l'autre Music
 /// </summary>
 /// <param name="other"> L'autre musique qui sera comparé à cette Music </param>
 /// <returns>true si égaux, false sinon </returns>
 public bool Equals(IMusic other)
 => (Title.Equals(other.Title) && Artist.Equals(other.Artist) && Date.Equals(other.Date) && Genre.Equals(other.Genre) && Infos.Equals(other.Infos) && Audio.ToString().Equals(other.Audio.ToString()) && Video.Equals(other.Video));
        public ActionResult Create()
        {
            Artist artist = new Artist();

            return(View(artist));
        }
 private ArtistResponse(bool success, string message, Artist artist) : base(success, message)
 {
     Artist = artist;
 }
Exemplo n.º 47
0
 public ArtistAddedEvent(Artist artist, bool doRefresh = true)
 {
     Artist    = artist;
     DoRefresh = doRefresh;
 }
 /// <summary>
 /// Creates a success response.
 /// </summary>
 /// <param name="artist">Saved artist.</param>
 /// <returns>Response.</returns>
 public ArtistResponse(Artist artist) : this(true, string.Empty, artist)
 {
 }
Exemplo n.º 49
0
        private string statisticsOnCustomer(string paintName)
        {
            int maximum_search = 5;

            /*this lines added to this function to change the rate after numbers of clicks*/
            int maximum_click   = 3;
            var theChosenArtist = db.Paints.First(paint2 => paint2.PaintID == id_s).artistname;
            /*this lines added to this function to change the rate after numbers of clicks*/


            Dictionary <String, int> StatisticsOnPaintType = (Dictionary <string, int>)HttpContext.Session["d_favPaint"];

            //last edit
            Dictionary <String, int> StatisticsOnPaintType2 = (Dictionary <string, int>)HttpContext.Session["d_Rate"];

            if (StatisticsOnPaintType2 == null)
            {
                StatisticsOnPaintType2 = new Dictionary <string, int>();
            }
            if (StatisticsOnPaintType2.ContainsKey(paintName) == true)
            {
                StatisticsOnPaintType2[paintName] += 1;
                HttpContext.Session["d_favPaint"]  = StatisticsOnPaintType2;
            }
            else
            {
                StatisticsOnPaintType2.Add(paintName, 1);
                HttpContext.Session["d_favPaint"] = StatisticsOnPaintType2;
            }
            //last edit

            //origin
            if (StatisticsOnPaintType == null)
            {
                StatisticsOnPaintType = new Dictionary <string, int>();
            }
            if (StatisticsOnPaintType.ContainsKey(paintName) == true)
            {
                StatisticsOnPaintType[paintName] += 1;
                HttpContext.Session["d_favPaint"] = StatisticsOnPaintType;
            }
            else
            {
                StatisticsOnPaintType.Add(paintName, 1);
                HttpContext.Session["d_favPaint"] = StatisticsOnPaintType;
            }
            //origin


            //last edit
            if (StatisticsOnPaintType2[paintName] >= maximum_click)
            {
                Artist artist = new Artist();
                artist = db.Artists.First(a => a.ArtistName == theChosenArtist);
                artist.Rate++;
                StatisticsOnPaintType2[paintName] = 0;
                db.Entry(artist).State            = EntityState.Modified;
                db.SaveChanges();
            }
            if (StatisticsOnPaintType[paintName] >= maximum_search)
            {
                StatisticsOnPaintType[paintName] = 0;
                return(paintName);
            }
            //last edit


            /*this lines added to this function to change the rate after numbers of clicks*/

            /*<<<<< ירד לבדיקה
             * if (StatisticsOnPaintType[paintName] >= maximum_click )
             * {
             *  Artist artist = new Artist();
             *  artist = db.Artists.First(a => a.ArtistName == theChosenArtist);
             *  artist.Rate++;
             *  db.Entry(artist).State = EntityState.Modified;
             *  db.SaveChanges();
             *
             * }
             * /*this lines added to this function to change the rate after numbers of clicks*/
            /*<<<< ירד לבדיקה
             * if (StatisticsOnPaintType[paintName] >=maximum_search)
             * {
             *
             *  //init
             *  StatisticsOnPaintType[paintName] = 0;
             *  //
             *  return paintName;
             * }*/


            return(null);
        }
Exemplo n.º 50
0
 public ArtistViewModel(Artist a) : base(a)
 {
     artist    = a;
     TypeImage = "\xe13d";
     InitLogo(string.Format("artist_{0}.jpg", Id));
 }
Exemplo n.º 51
0
        public ArtistTest(ITestOutputHelper output)

        {
            _output = output;
            _artist = new Artist();
        }
Exemplo n.º 52
0
        protected override async Task OnInitializedAsync()
        {
            int id = Convert.ToInt32(Id);

            Model = await _repo.Get(EndPoints.ArtistEndpoint, id);
        }
Exemplo n.º 53
0
        public ActionResult New(int artistId)
        {
            Artist artist = Artist.Find(artistId);

            return(View());
        }
Exemplo n.º 54
0
        public static void Main(string[] args)
        {
            //Collections to work with
            List <Artist> Artists = JsonToFile <Artist> .ReadJson();

            List <Group> Groups = JsonToFile <Group> .ReadJson();

            //========================================================
            //Solve all of the prompts below using various LINQ queries
            //========================================================

            //There is only one artist in this collection from Mount Vernon, what is their name and age?
            var all = from art in Artists
                      where art.Hometown == "Mount Vernon"
                      select art;

            Console.WriteLine("The Artist's from Mount Vernon:");
            foreach (var a in all)
            {
                Console.WriteLine("Name: " + a.RealName + " Age: " + a.Age);
            }
            Console.WriteLine("--------------------------------------");

            // //Who is the youngest artist in our collection of artists?
            var    arti    = from a in Artists select a;
            Artist yunArti = Artists.First();

            foreach (var a in arti)
            {
                if (a.Age < yunArti.Age)
                {
                    yunArti = a;
                }
            }
            Console.WriteLine("The Youngest Artist is: " + yunArti.ArtistName + " Age: " + yunArti.Age);
            Console.WriteLine("--------------------------------------");



            // //Display all artists with 'William' somewhere in their real name
            Console.WriteLine("All Artists with william realname");
            foreach (var a in arti)
            {
                if (a.RealName.Contains("William"))
                {
                    Console.WriteLine(a.ArtistName + " Real Name" + a.RealName);
                }
            }

            Console.WriteLine("--------------------------------------");

            //Display the 3 oldest artist from Atlanta
            var oldest3Artists = from a in Artists
                                 where a.Hometown == "Atlanta"
                                 orderby a.Age descending
                                 select a;
            int i = 0;

            Console.WriteLine("the 3 oldest artist from Atlanta:");
            foreach (var item in oldest3Artists)
            {
                if (i <= 2)
                {
                    Console.WriteLine("Artist Name: " + item.ArtistName + " Age: " + item.Age);
                }
                else
                {
                    break;
                }
                i++;
            }

            Console.WriteLine("--------------------------------------");

            //(Optional) Display the Group Name of all groups that have members that are not from New York City
            var allGrpsNotFrmNy = from a in Artists
                                  where a.Hometown != "New York City"
                                  join g in Groups on a.GroupId equals g.Id
                                  select new { ArtistName = a.ArtistName, HomeTown = a.Hometown, GroupName = g.GroupName, };

            foreach (var ag in allGrpsNotFrmNy)
            {
                Console.WriteLine(ag.ArtistName + " " + ag.GroupName + " " + ag.HomeTown);
            }

            Console.WriteLine("--------------------------------------");


            //(Optional) Display the artist names of all members of the group 'Wu-Tang Clan'
            var allArtsNamWuTan = from a in Artists
                                  join g in Groups on a.GroupId equals g.Id
                                  where g.GroupName == "Wu-Tang Clan"
                                  select a;

            Console.WriteLine("artist names of all members of the group 'Wu-Tang Clan");
            foreach (var ag in allArtsNamWuTan)
            {
                Console.WriteLine(ag.ArtistName);
            }
        }
Exemplo n.º 55
0
 internal Artist GetArtist(XDocument document) => Artist.Create(document.RealRoot());
Exemplo n.º 56
0
 public override void Setup()
 {
     base.Setup();
     DefaultAct        = Act.CreateDefault();
     DefaultNewsletter = Newsletter.CreateDefault();
     DefaultSeries     = Series.CreateDefault();
     Baker             = new Artist {
         QueryHelper = QueryHelper,
         Surname     = BakerName
     };
     Drums = new Role {
         QueryHelper = QueryHelper,
         Name        = DrumsName
     };
     Location1 = new Location {
         QueryHelper = QueryHelper,
         Name        = Location1Name
     };
     Event1 = new Event {
         QueryHelper = QueryHelper,
         Date        = DateTime.Parse("2020/03/01")
     };
     Set1 = new Set {
         QueryHelper = QueryHelper,
         SetNo       = Set1SetNo
     };
     Set2 = new Set {
         QueryHelper = QueryHelper,
         SetNo       = Set2SetNo
     };
     Piece1 = new Piece {
         QueryHelper = QueryHelper,
         PieceNo     = Piece1PieceNo,
         AudioUrl    = Piece1AudioUrl,
         Duration    = Piece1Duration = new TimeSpan(0, 5, 29),
         Notes       = Piece1Notes,
         Title       = Piece1Title,
         VideoUrl    = Piece1VideoUrl
     };
     Piece1AtSet2 = new Piece {
         QueryHelper = QueryHelper,
         PieceNo     = Piece1PieceNo,
         Duration    = Piece1AtSet2Duration = new TimeSpan(0, 2, 8)
     };
     Piece2 = new Piece {
         QueryHelper = QueryHelper,
         PieceNo     = Piece2PieceNo,
         Duration    = Piece2Duration = new TimeSpan(1, 46, 3)
     };
     Credit1 = new Credit {
         QueryHelper = QueryHelper,
         CreditNo    = Credit1CreditNo
     };
     Credit2 = new Credit {
         QueryHelper = QueryHelper,
         CreditNo    = Credit2CreditNo
     };
     Session.BeginUpdate();
     Session.Persist(DefaultAct);
     Session.Persist(DefaultNewsletter);
     Session.Persist(DefaultSeries);
     Session.Persist(Baker);
     Session.Persist(Drums);
     Session.Persist(Location1);
     Event1.Location = Location1;
     Data.AddEventTypesPersisted(1, Session);
     Event1.EventType = Data.EventTypes[0];
     Session.Persist(Event1);
     Set1.Event = Event1;
     Set2.Event = Event1;
     Data.AddGenresPersisted(1, Session);
     Set1.Genre = Data.Genres[0];
     Set2.Genre = Set1.Genre;
     Session.Persist(Set1);
     Session.Persist(Set2);
     Piece1.Set       = Set1;
     Piece1AtSet2.Set = Set2;
     Piece2.Set       = Set1;
     Session.Persist(Piece1);
     Session.Persist(Piece1AtSet2);
     Session.Persist(Piece2);
     Credit1.Artist = Baker;
     Credit1.Piece  = Piece1;
     Credit1.Role   = Drums;
     Credit2.Artist = Baker;
     Credit2.Piece  = Piece1;
     Credit2.Role   = Drums;
     Session.Persist(Credit1);
     Session.Persist(Credit2);
     Session.Commit();
     Session.BeginRead();
     Location1    = QueryHelper.Read <Location>(Location1Name, Session);
     Event1       = QueryHelper.Read <Event>(Event1.SimpleKey, Location1, Session);
     Set1         = QueryHelper.Read <Set>(Set1.SimpleKey, Event1, Session);
     Set2         = QueryHelper.Read <Set>(Set2.SimpleKey, Event1, Session);
     Piece1       = QueryHelper.Read <Piece>(Piece1SimpleKey, Set1, Session);
     Piece1AtSet2 = QueryHelper.Read <Piece>(Piece1SimpleKey, Set2, Session);
     Piece2       = QueryHelper.Read <Piece>(Piece2SimpleKey, Set1, Session);
     Credit1      = QueryHelper.Read <Credit>(Credit1.SimpleKey, Piece1, Session);
     Credit2      = QueryHelper.Read <Credit>(Credit2.SimpleKey, Piece1, Session);
     Session.Commit();
 }
Exemplo n.º 57
0
        public async Task <OperationResult <Artist> > Update(Artist Artist, IEnumerable <Image> ArtistImages, string destinationFolder = null)
        {
            SimpleContract.Requires <ArgumentNullException>(Artist != null, "Invalid Artist");

            var sw = new Stopwatch();

            sw.Start();

            var artistGenreTables = Artist.Genres.Select(x => new ArtistGenre {
                ArtistId = Artist.Id, GenreId = x.GenreId
            }).ToList();
            var artistAssociatedWith = Artist.AssociatedArtists.Select(x => new ArtistAssociation {
                ArtistId = Artist.Id, AssociatedArtistId = x.AssociatedArtistId
            }).ToList();
            var result = true;

            var now = DateTime.UtcNow;
            var originalArtistFolder = Artist.ArtistFileFolder(this.Configuration, destinationFolder ?? this.Configuration.LibraryFolder);
            var originalName         = Artist.Name;
            var originalSortName     = Artist.SortName;

            Artist.LastUpdated = now;
            await this.DbContext.SaveChangesAsync();

            this.DbContext.ArtistGenres.RemoveRange((from at in this.DbContext.ArtistGenres
                                                     where at.ArtistId == Artist.Id
                                                     select at));
            Artist.Genres = artistGenreTables;
            this.DbContext.ArtistAssociations.RemoveRange((from at in this.DbContext.ArtistAssociations
                                                           where at.ArtistId == Artist.Id
                                                           select at));
            Artist.AssociatedArtists = artistAssociatedWith;
            await this.DbContext.SaveChangesAsync();

            var existingImageIds = (from ai in ArtistImages
                                    where ai.Status != Statuses.New
                                    select ai.RoadieId).ToArray();

            this.DbContext.Images.RemoveRange((from i in this.DbContext.Images
                                               where i.ArtistId == Artist.Id
                                               where !(from x in existingImageIds select x).Contains(i.RoadieId)
                                               select i));
            await this.DbContext.SaveChangesAsync();

            if (ArtistImages != null && ArtistImages.Any(x => x.Status == Statuses.New))
            {
                foreach (var ArtistImage in ArtistImages.Where(x => x.Status == Statuses.New))
                {
                    this.DbContext.Images.Add(ArtistImage);
                }
                try
                {
                    await this.DbContext.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    this.Logger.LogError(ex, ex.Serialize());
                }
            }

            var newArtistFolder = Artist.ArtistFileFolder(this.Configuration, destinationFolder ?? this.Configuration.LibraryFolder);

            if (!originalArtistFolder.Equals(newArtistFolder, StringComparison.OrdinalIgnoreCase))
            {
                this.Logger.LogTrace("Moving Artist From Folder [{0}] To  [{1}]", originalArtistFolder, newArtistFolder);
                //  Directory.Move(originalArtistFolder, Artist.ArtistFileFolder(destinationFolder ?? SettingsHelper.Instance.LibraryFolder));
                // TODO if name changed then update Artist track files to have new Artist name
            }
            this.CacheManager.ClearRegion(Artist.CacheRegion);
            sw.Stop();

            return(new OperationResult <Artist>
            {
                Data = Artist,
                IsSuccess = result,
                OperationTime = sw.ElapsedMilliseconds
            });
        }
 public IActionResult EditArtist(Artist eartist)
 {
     _artist.SetArtist(eartist);
     return(RedirectToAction("GetallArtist"));
 }
Exemplo n.º 59
0
        private async Task IndexFolders(IEnumerable <GetFolderFilesResult> folders)
        {
            async Task <IndexTrackTransactionResult> IndexTrackTransactionAsync(StorageFile f, Folder folder)
            {
                var tf  = TagLib.File.Create(await UwpFileAbstraction.CreateAsync(f));
                var tag = tf.Tag;

                using (var tr = await db.Database.BeginTransactionAsync())
                {
                    try
                    {
                        var track = await CreateTrackAsync(f, tf);

                        await db.Tracks.AddAsync(track);

                        await db.SaveChangesAsync();

                        // create artist entity
                        var artistName = string.IsNullOrEmpty(tag.FirstPerformer) ? "Unknown" : tag.FirstPerformer;
                        var artist     = await db.Artists
                                         .Include(x => x.Albums)
                                         .FirstOrDefaultAsync(a => a.Name == artistName);

                        var createArtist = artist == default;

                        if (createArtist)
                        {
                            artist = new Artist()
                            {
                                Name = artistName,
                            };

                            await db.Artists.AddAsync(artist);
                        }

                        await db.SaveChangesAsync();

                        // create album entity
                        var albumTitle = string.IsNullOrEmpty(tag.Album) ? "Unknown" : tag.Album;
                        var album      = artist.Albums.FirstOrDefault(x => x.Title == albumTitle);

                        var createAlbum = album == default;

                        if (createAlbum)
                        {
                            album = new Album()
                            {
                                Title = albumTitle,
                            };

                            await db.Albums.AddAsync(album);
                        }

                        if (string.IsNullOrEmpty(album.CoverCacheToken))
                        {
                            var picData = await FindAlbumCoverAsync(tag, f.Path);

                            if (picData != default(IBuffer))
                            {
                                var cover = await CacheService.CacheAsync(picData);

                                album.CoverCacheToken = cover;
                            }
                        }

                        await db.SaveChangesAsync();

                        track.Album  = album;
                        track.Folder = folder;
                        album.Tracks.Add(track);
                        if (createAlbum)
                        {
                            album.Artist = artist;
                            artist.Albums.Add(album);
                        }

                        await db.SaveChangesAsync();

                        await tr.CommitAsync();

                        return(new IndexTrackTransactionResult()
                        {
                            Successful = true,
                            Track = track,
                            ArtistCreated = createArtist,
                            Artist = artist,
                            AlbumCreated = createAlbum,
                            Album = album
                        });
                    }
                    catch (Exception)
                    {
                        await tr.RollbackAsync();

                        return(new IndexTrackTransactionResult()
                        {
                            Successful = false
                        });
                    }
                }
            }

            var group = await folders.GroupJoinAsync(TrackSource.Items, x => x.ViewModel.Id, x => x.FolderId, (mix, dbFiles) => (mix, dbFiles.ToList()));

            await group.ForEachAsync(async g =>
            {
                var dbFiles   = g.Item2;
                var diskFiles = g.mix.Files;
                var dbFolder  = await db.Folders.SingleAsync(x => x.Id == g.mix.ViewModel.Id);

                await diskFiles.ForEachAsync(async f =>
                {
                    var trackRx = await dbFiles.FirstOrDefaultAsync(x => x.FileName == f.Name && x.Path == f.Path);

                    if (trackRx == null)
                    {
                        var result = await IndexTrackTransactionAsync(f, dbFolder);
                        if (result.Successful == false)
                        {
                            return;
                        }

                        if (result.ArtistCreated)
                        {
                            var artistVm = ArtistViewModel.Create(result.Artist);
                            _artistSource.AddOrUpdate(artistVm);
                        }
                        else
                        {
                            var artistVm = _artistSource.Lookup(result.Artist.Id).Value;
                            if (result.AlbumCreated)
                            {
                                var albumVm = AlbumViewModel.Create(artistVm, result.Album);
                                artistVm.Albums.AddOrUpdate(albumVm);
                            }
                            else
                            {
                                var albumVm = artistVm.Albums.Items.Single(x => x.Id == result.Album.Id);
                                var trackVm = TrackViewModel.Create(albumVm, result.Track);
                                albumVm.Tracks.AddOrUpdate(trackVm);
                            }
                        }
                    }
                    else
                    {
                        dbFiles.Remove(dbFiles.First(x => x.Id == trackRx.Id));
                    }
                });

                await dbFiles.ForEachAsync(async f =>
                {
                    var track = await db.Tracks.SingleAsync(x => x.Id == f.Id);
                    await RemoveTrackAsync(track);
                });
            });
        }
Exemplo n.º 60
0
        public static void SplitMetadata(string path, ref Track track, ref TrackStatistic trackStatistic, ref Album album, ref Artist artist, ref Genre genre)
        {
            if (!string.IsNullOrEmpty(path))
            {
                var fmd = new FileMetadata(path);

                // Track information
                track.Path          = path;
                track.SafePath      = path.ToSafePath();
                track.FileName      = FileUtils.NameWithoutExtension(path);
                track.Duration      = Convert.ToInt64(fmd.Duration.TotalMilliseconds);
                track.MimeType      = fmd.MimeType;
                track.BitRate       = fmd.BitRate;
                track.SampleRate    = fmd.SampleRate;
                track.TrackTitle    = MetadataUtils.SanitizeTag(fmd.Title.Value);
                track.TrackNumber   = MetadataUtils.SafeConvertToLong(fmd.TrackNumber.Value);
                track.TrackCount    = MetadataUtils.SafeConvertToLong(fmd.TrackCount.Value);
                track.DiscNumber    = MetadataUtils.SafeConvertToLong(fmd.DiscNumber.Value);
                track.DiscCount     = MetadataUtils.SafeConvertToLong(fmd.DiscCount.Value);
                track.Year          = MetadataUtils.SafeConvertToLong(fmd.Year.Value);
                track.HasLyrics     = string.IsNullOrWhiteSpace(fmd.Lyrics.Value) ? 0 : 1;
                track.NeedsIndexing = 0;

                // TrackStatistic information
                trackStatistic.Path     = path;
                trackStatistic.SafePath = path.ToSafePath();
                trackStatistic.Rating   = fmd.Rating.Value;

                // Before proceeding, get the available artists
                string albumArtist = GetFirstAlbumArtist(fmd);
                string trackArtist = GetFirstArtist(fmd); // will be used for the album if no album artist is found

                // Album information
                album.AlbumTitle  = string.IsNullOrWhiteSpace(fmd.Album.Value) ? Defaults.UnknownAlbumString : MetadataUtils.SanitizeTag(fmd.Album.Value);
                album.AlbumArtist = (albumArtist == Defaults.UnknownAlbumArtistString ? trackArtist : albumArtist);
                album.DateAdded   = DateTime.Now.Ticks;
                album.DateCreated = FileUtils.DateCreatedTicks(path);

                UpdateAlbumYear(album, MetadataUtils.SafeConvertToLong(fmd.Year.Value));

                // Artist information
                artist.ArtistName = trackArtist;

                // Genre information
                genre.GenreName = GetFirstGenre(fmd);

                // Metadata hash
                System.Text.StringBuilder sb = new System.Text.StringBuilder();

                sb.Append(album.AlbumTitle);
                sb.Append(artist.ArtistName);
                sb.Append(genre.GenreName);
                sb.Append(track.TrackTitle);
                sb.Append(track.TrackNumber);
                sb.Append(track.Year);
                track.MetaDataHash = CryptographyUtils.MD5Hash(sb.ToString());

                // File information
                track.FileSize         = FileUtils.SizeInBytes(path);
                track.DateFileModified = FileUtils.DateModifiedTicks(path);
                track.DateLastSynced   = DateTime.Now.Ticks;
            }
        }