Example #1
0
        public async Task <string> CreateOrUpdateAsync(Song song, CancellationToken cancelToken)
        {
            try
            {
                var songDb = await Find(song, cancelToken);

                if (songDb == null)
                {
                    var document = new SongDocument(song);
                    await songCollection.InsertOneAsync(document, null, cancelToken);

                    return(document._id.ToString());
                }
                else
                {
                    if (!songDb.Equals(song))
                    {
                        var id = await UpdateAsync(song, cancelToken);

                        if (id != songDb._id.ToString())
                        {
                            throw new Top100Exception(ReasonType.Conflict);
                        }
                    }
                    return(songDb._id.ToString());
                }
            }
            catch (MongoException e)
            {
                Console.WriteLine($"Mongo Exception in Insert.  ex={e}");
                throw new Top100Exception(ReasonType.Unknown);
            }
        }
Example #2
0
        private async Task <SongDocument> Find(Song song, CancellationToken cancelToken)
        {
            SongDocument result = null;

            var builder = Builders <SongDocument> .Filter;
            var filter  = builder.Empty;

            //var titleFilter = builder.Eq(x => x.Song.Title, song.Title);
            //filter = builder.And(titleFilter, filter);

            //var artistFilter = builder.Eq(x => x.Song.Artist, song.Artist);
            //filter = builder.And(artistFilter, filter);

            var numberFilter = builder.Eq(x => x.Song.Number, song.Number);

            filter = builder.And(numberFilter, filter);

            var yearFilter = builder.Eq(x => x.Song.Year, song.Year);

            filter = builder.And(yearFilter, filter);

            //var ownFilter = builder.Eq(x => x.Song.Own, song.Own);
            //filter = builder.And(ownFilter, filter);

            try
            {
                var cursor = songCollection.Find(filter);
                if (await cursor.CountDocumentsAsync(cancelToken) == 1)
                {
                    result = await cursor.FirstAsync(cancelToken);
                }
            }
            catch (MongoException ex)
            {
                Console.WriteLine($"ERROR:  error in find.  ex={ex}");
            }

            return(result);
        }