コード例 #1
0
        public void Update <TEntity>(TEntity entity)
            where TEntity : class
        {
            IMongoCollection <TEntity> mongoCollection = (IMongoCollection <TEntity>)GetCollection(typeof(TEntity));

            mongoCollection.WithWriteConcern(WriteConcern.Acknowledged).ReplaceOne(DynamicLambdaBuilder.GetIdLE(entity, typeof(PersistenceIdAttribute)), entity);
        }
コード例 #2
0
        /// <summary>
        ///     Adds a user to the `users` collection
        /// </summary>
        /// <param name="title">The name of the user.</param>
        /// <param name="content">The email of the user.</param>
        /// <param name="author">The clear-text password, which will be hashed before storing.</param>
        /// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
        /// <returns></returns>
        public async Task <PostResponse> AddPostAsync(string title, string content, string author, string preview,
                                                      CancellationToken cancellationToken = default)
        {
            try
            {
                var post = new Post()
                {
                    Title    = title,
                    Contents = content,
                    Preview  = preview,
                    Author   = author,

                    CreatedOn = DateTime.Now
                };

                await _postsCollection.WithWriteConcern(WriteConcern.W1).InsertOneAsync(post);

                return(new PostResponse(post));
            }
            catch (Exception ex)
            {
                return(ex.Message.StartsWith("MongoError: E11000 duplicate key error")
                    ? new PostResponse(false, "A user with the given email already exists.")
                    : new PostResponse(false, ex.Message));
            }
        }
コード例 #3
0
        /// <summary>
        ///     Adds a comment.
        /// </summary>
        /// <param name="user"></param>
        /// <param name="movieId"></param>
        /// <param name="comment"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>The Movie associated with the comment.</returns>
        public async Task <Movie> AddCommentAsync(User user, ObjectId movieId, string comment,
                                                  CancellationToken cancellationToken = default)
        {
            try
            {
                var newComment = new Comment
                {
                    Date    = DateTime.UtcNow,
                    Text    = comment,
                    Name    = user.Name,
                    Email   = user.Email,
                    MovieId = movieId
                };

                // Implement InsertOneAsync() to insert a
                // new comment into the comments collection.
                await _commentsCollection
                .WithWriteConcern(WriteConcern.WMajority)
                .InsertOneAsync(newComment, cancellationToken: cancellationToken);

                return(await _moviesRepository.GetMovieAsync(movieId.ToString(), cancellationToken));
            }
            catch
            {
                return(null);
            }
        }
コード例 #4
0
        /// <summary>
        ///     Adds a user to the `users` collection
        /// </summary>
        /// <param name="name">The name of the user.</param>
        /// <param name="email">The email of the user.</param>
        /// <param name="password">The clear-text password, which will be hashed before storing.</param>
        /// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
        /// <returns></returns>
        public async Task <UserResponse> AddUserAsync(string name, string email, string password,
                                                      CancellationToken cancellationToken = default)
        {
            try
            {
                var user = new User()
                {
                    Name           = name,
                    Email          = email,
                    HashedPassword = PasswordHashOMatic.Hash(password),
                };

                await _usersCollection.WithWriteConcern(WriteConcern.W1).InsertOneAsync(user);

                //
                // // TODO Ticket: Durable Writes
                // // To use a more durable Write Concern for this operation, add the
                // // .WithWriteConcern() method to your InsertOneAsync call.

                var newUser = await GetUserAsync(user.Email, cancellationToken);

                return(new UserResponse(newUser));
            }
            catch (Exception ex)
            {
                return(ex.Message.StartsWith("MongoError: E11000 duplicate key error")
                    ? new UserResponse(false, "A user with the given email already exists.")
                    : new UserResponse(false, ex.Message));
            }
        }
コード例 #5
0
        /// <summary>
        ///     Adds a user to the `users` collection
        /// </summary>
        /// <param name="name">The name of the user.</param>
        /// <param name="email">The email of the user.</param>
        /// <param name="password">The clear-text password, which will be hashed before storing.</param>
        /// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
        /// <returns></returns>
        public async Task <UserResponse> AddUserAsync(string name, string email, string password,
                                                      CancellationToken cancellationToken = default)
        {
            try
            {
                var user = new User();
                // TODO Ticket: User Management
                // Create a user with the "Name", "Email", and "HashedPassword" fields.
                // DO NOT STORE CLEAR-TEXT PASSWORDS! Instead, use the helper class
                // we have created for you: PasswordHashOMatic.Hash(password)

                user = new User()
                {
                    Name = name, Email = email, HashedPassword = PasswordHashOMatic.Hash(password)
                };

                //var insertOptions = new MongoInsertOptions { CheckElementNames = false };

                await _usersCollection.WithWriteConcern(WriteConcern.WMajority).InsertOneAsync(user, cancellationToken);

                // TODO Ticket: Durable Writes
                // // To use a more durable Write Concern for this operation, add the
                // // .WithWriteConcern() method to your InsertOneAsync call.

                var newUser = await GetUserAsync(user.Email, cancellationToken);

                return(new UserResponse(newUser));
            }
            catch (Exception ex)
            {
                return(ex.Message.StartsWith("MongoError: E11000 duplicate key error")
                    ? new UserResponse(false, "A user with the given email already exists.")
                    : new UserResponse(false, ex.Message));
            }
        }
コード例 #6
0
        public void Add <TEntity>(TEntity entity)
            where TEntity : class
        {
            IMongoCollection <TEntity> entityCollection = (IMongoCollection <TEntity>)GetCollection(typeof(TEntity));

            entityCollection.WithWriteConcern(WriteConcern.Acknowledged).InsertOne(entity);
        }
コード例 #7
0
        public void AddAsTransaction <TEntity>(IEnumerable <TEntity> entityList) where TEntity : class
        {
            IMongoCollection <TEntity> entityCollection     = (IMongoCollection <TEntity>)GetCollection(typeof(TEntity));
            IClientSessionHandle       clientSessionHandler = MongoDatabase.Client.StartSession();

            entityCollection.WithWriteConcern(WriteConcern.Acknowledged)
            .InsertMany(clientSessionHandler, entityList);
        }
コード例 #8
0
        public void RemoveAsTransaction <TEntity>(Expression <Func <TEntity, bool> > filter)
            where TEntity : class
        {
            IMongoCollection <TEntity> mongoCollection      = (IMongoCollection <TEntity>)GetCollection(typeof(TEntity));
            IClientSessionHandle       clientSessionHandler = MongoDatabase.Client.StartSession();

            mongoCollection.WithWriteConcern(WriteConcern.Acknowledged)
            .DeleteMany(clientSessionHandler, filter);
        }
コード例 #9
0
        public void Update <TEntity>(Expression <Func <TEntity, bool> > cond, TEntity entity)
            where TEntity : class
        {
            IMongoCollection <TEntity> mongoCollection =
                (IMongoCollection <TEntity>)GetCollection(typeof(TEntity));

            mongoCollection.WithWriteConcern(WriteConcern.Acknowledged).
            ReplaceOne(cond, entity);
        }
コード例 #10
0
 private void PersistRegistration(Type eventType, string subscriberInputQueue, IMongoCollection <BsonDocument> collection, FilterDefinition <BsonDocument> criteria, UpdateDefinition <BsonDocument> update)
 {
     var safeModeResult = collection.WithWriteConcern(WriteConcern.Acknowledged).UpdateOne(
         criteria,
         update,
         new UpdateOptions()
     {
         IsUpsert = true,
     });
 }
コード例 #11
0
ファイル: DeleteOneTest.cs プロジェクト: RavenZZ/MDRelation
 protected override void Execute(IMongoCollection<BsonDocument> collection, bool async)
 {
     var collectionWithWriteConcern = collection.WithWriteConcern(_writeConcern);
     if (async)
     {
         collectionWithWriteConcern.DeleteOneAsync(_filter).GetAwaiter().GetResult();
     }
     else
     {
         collectionWithWriteConcern.DeleteOne(_filter);
     }
 }
コード例 #12
0
ファイル: UpdateManyTest.cs プロジェクト: RavenZZ/MDRelation
 protected override void Execute(IMongoCollection<BsonDocument> collection, bool async)
 {
     var collectionWithWriteConcern = collection.WithWriteConcern(_writeConcern);
     if (async)
     {
         collectionWithWriteConcern.UpdateManyAsync(_filter, _update, _options).GetAwaiter().GetResult();
     }
     else
     {
         collectionWithWriteConcern.UpdateMany(_filter, _update, _options);
     }
 }
コード例 #13
0
ファイル: BulkWriteTest.cs プロジェクト: RavenZZ/MDRelation
 protected override void Execute(IMongoCollection<BsonDocument> collection, bool async)
 {
     var collectionWithWriteConcern = collection.WithWriteConcern(_writeConcern);
     if (async)
     {
         collectionWithWriteConcern.BulkWriteAsync(_requests, _options).GetAwaiter().GetResult();
     }
     else
     {
         collectionWithWriteConcern.BulkWrite(_requests, _options);
     }
 }
コード例 #14
0
        protected override void Execute(IMongoCollection <BsonDocument> collection, bool async)
        {
            var collectionWithWriteConcern = collection.WithWriteConcern(_writeConcern);

            if (async)
            {
                collectionWithWriteConcern.InsertOneAsync(_document).GetAwaiter().GetResult();
            }
            else
            {
                collectionWithWriteConcern.InsertOne(_document);
            }
        }
コード例 #15
0
        protected override void Execute(IMongoCollection <BsonDocument> collection, bool async)
        {
            var collectionWithWriteConcern = collection.WithWriteConcern(_writeConcern);

            if (async)
            {
                collectionWithWriteConcern.BulkWriteAsync(_requests, _options).GetAwaiter().GetResult();
            }
            else
            {
                collectionWithWriteConcern.BulkWrite(_requests, _options);
            }
        }
コード例 #16
0
ファイル: UpdateManyTest.cs プロジェクト: snoopy83101/Uzor001
        protected override void Execute(IMongoCollection <BsonDocument> collection, bool async)
        {
            var collectionWithWriteConcern = collection.WithWriteConcern(_writeConcern);

            if (async)
            {
                collectionWithWriteConcern.UpdateManyAsync(_filter, _update, _options).GetAwaiter().GetResult();
            }
            else
            {
                collectionWithWriteConcern.UpdateMany(_filter, _update, _options);
            }
        }
コード例 #17
0
        public void UpdateAsTransaction <TEntity, TResult>(IEnumerable <TEntity> entityList,
                                                           Expression <Func <TEntity, TResult> > filter)
            where TEntity : class
        {
            IMongoCollection <TEntity> mongoCollection =
                (IMongoCollection <TEntity>)GetCollection(typeof(TEntity));
            IClientSessionHandle clientSessionHandler = MongoDatabase.Client.StartSession();

            mongoCollection.WithWriteConcern(WriteConcern.Acknowledged)
            .BulkWrite(clientSessionHandler,
                       entityList
                       .Select(entity => new ReplaceOneModel <TEntity>(
                                   DynamicLambdaBuilder
                                   .CreateFilterForCollection(filter, entity), entity)));
        }
コード例 #18
0
        protected override void Execute(IMongoCollection <BsonDocument> collection, bool async)
        {
            if (collection.Settings.WriteConcern == null)
            {
                collection = collection.WithWriteConcern(WriteConcern.Acknowledged);
            }

            if (async)
            {
                collection.BulkWriteAsync(_requests, _options).GetAwaiter().GetResult();
            }
            else
            {
                collection.BulkWrite(_requests, _options);
            }
        }
コード例 #19
0
ファイル: CommentsRepository.cs プロジェクト: kbaral/posts
        /// <summary>
        ///     Adds a user to the `users` collection
        /// </summary>
        /// <param name="title">The name of the user.</param>
        /// <param name="content">The email of the user.</param>
        /// <param name="author">The clear-text password, which will be hashed before storing.</param>
        /// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
        /// <returns></returns>
        public async Task <CommentResponse> AddCommentAsync(Comment comment,
                                                            CancellationToken cancellationToken = default)
        {
            try
            {
                await _commentCollection.WithWriteConcern(WriteConcern.W1).InsertOneAsync(comment);

                return(new CommentResponse(comment));
            }
            catch (Exception ex)
            {
                return(ex.Message.StartsWith("MongoError: E11000 duplicate key error")
                    ? new CommentResponse(false, "A user with the given email already exists.")
                    : new CommentResponse(false, ex.Message));
            }
        }
コード例 #20
0
        /// <inheritdoc />
        public Task Append(Message message, MessageJournalCategory category,
                           CancellationToken cancellationToken = new CancellationToken())
        {
            var entry = new MessageJournalEntryDocument
            {
                Timestamp   = message.GetJournalTimestamp(category),
                Category    = Normalize(category),
                Topic       = Normalize(message.Headers.Topic),
                MessageId   = Normalize(message.Headers.MessageId),
                MessageName = message.Headers.MessageName,
                Headers     = message.Headers.ToDictionary(h => (string)h.Key, h => h.Value),
                Content     = message.Content,
                Origination = Normalize(message.Headers.Origination),
                Destination = Normalize(message.Headers.Destination),
                RelatedTo   = Normalize(message.Headers.RelatedTo)
            };

            return(_messageJournalEntries
                   .WithWriteConcern(WriteConcern.Acknowledged)
                   .InsertOneAsync(entry, cancellationToken: cancellationToken));
        }
コード例 #21
0
        // private methods
        private void ParseCollectionOptions(BsonDocument document)
        {
            JsonDrivenHelper.EnsureAllFieldsAreValid(document, "readConcern", "readPreference", "writeConcern");

            if (document.Contains("readConcern"))
            {
                var readConcern = ReadConcern.FromBsonDocument(document["readConcern"].AsBsonDocument);
                _collection = _collection.WithReadConcern(readConcern);
            }

            if (document.Contains("readPreference"))
            {
                var readPreference = ReadPreference.FromBsonDocument(document["readPreference"].AsBsonDocument);
                _collection = _collection.WithReadPreference(readPreference);
            }

            if (document.Contains("writeConcern"))
            {
                var writeConcern = WriteConcern.FromBsonDocument(document["writeConcern"].AsBsonDocument);
                _collection = _collection.WithWriteConcern(writeConcern);
            }
        }
コード例 #22
0
        public async Task <bool> DeduplicateMessage(string clientId, DateTime timeReceived, ContextBag context)
        {
            try
            {
                await _collection.WithWriteConcern(WriteConcern.W1).WithReadPreference(ReadPreference.Primary).InsertOneAsync(new GatewayMessage()
                {
                    Id           = clientId,
                    TimeReceived = timeReceived
                }).ConfigureAwait(false);

                return(true);
            }
            catch (MongoWriteException aggEx)
            {
                // Check for "E11000 duplicate key error"
                // https://docs.mongodb.org/manual/reference/command/insert/
                if (aggEx.WriteError?.Code == 11000)
                {
                    return(false);
                }

                throw;
            }
        }
コード例 #23
0
ファイル: UsersRepository.cs プロジェクト: vinics91/mflix
        /// <summary>
        ///     Adds a user to the `users` collection
        /// </summary>
        /// <param name="name">The name of the user.</param>
        /// <param name="email">The email of the user.</param>
        /// <param name="password">The clear-text password, which will be hashed before storing.</param>
        /// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
        /// <returns></returns>
        public async Task <UserResponse> AddUserAsync(string name, string email, string password,
                                                      CancellationToken cancellationToken = default)
        {
            try
            {
                var user = new User
                {
                    Name           = name,
                    Email          = email,
                    HashedPassword = PasswordHashOMatic.Hash(password)
                };
                await _usersCollection.WithWriteConcern(new WriteConcern(1)).InsertOneAsync(user, cancellationToken);

                var newUser = await GetUserAsync(user.Email, cancellationToken);

                return(new UserResponse(newUser));
            }
            catch (Exception ex)
            {
                return(ex.Message.StartsWith("MongoError: E11000 duplicate key error")
                    ? new UserResponse(false, "A user with the given email already exists.")
                    : new UserResponse(false, ex.Message));
            }
        }
コード例 #24
0
 protected override Task ExecuteAsync(IMongoCollection <BsonDocument> collection)
 {
     return(collection.WithWriteConcern(_writeConcern).UpdateManyAsync(_filter, _update, _options));
 }
コード例 #25
0
 protected override Task ExecuteAsync(IMongoCollection <BsonDocument> collection)
 {
     return(collection.WithWriteConcern(_writeConcern).InsertManyAsync(_documents, _options));
 }
コード例 #26
0
 protected override Task ExecuteAsync(IMongoCollection<BsonDocument> collection)
 {
     return collection.WithWriteConcern(_writeConcern).BulkWriteAsync(_requests, _options);
 }
コード例 #27
0
 protected override Task ExecuteAsync(IMongoCollection<BsonDocument> collection)
 {
     return collection.WithWriteConcern(_writeConcern).UpdateOneAsync(_filter, _update, _options);
 }
コード例 #28
0
 public IMongoCollection <T> WithWriteConcern(WriteConcern writeConcern) =>
 _base.WithWriteConcern(writeConcern);
コード例 #29
0
 protected override Task ExecuteAsync(IMongoCollection<BsonDocument> collection)
 {
     return collection.WithWriteConcern(_writeConcern).DeleteOneAsync(_filter);
 }
コード例 #30
0
 protected override Task ExecuteAsync(IMongoCollection<BsonDocument> collection)
 {
     return collection.WithWriteConcern(_writeConcern).InsertOneAsync(_document);
 }
コード例 #31
0
 protected override void SetWriteConcern(WriteConcern value)
 {
     base.SetWriteConcern(value);
     _collection = _collection.WithWriteConcern(value);
 }
コード例 #32
0
 protected ComponentBase(IMongoCollection <BsonDocument> collection, string uuid = null)
 {
     _collection = collection.WithWriteConcern(WriteConcern.Acknowledged);
     Uuid        = uuid ?? Guid.NewGuid().ToString();
 }
コード例 #33
0
 public IMongoCollection <T> WithWriteConcern(WriteConcern writeConcern)
 {
     return(collection.WithWriteConcern(writeConcern));
 }
コード例 #34
0
 protected override Task ExecuteAsync(IMongoCollection <BsonDocument> collection)
 {
     return(collection.WithWriteConcern(_writeConcern).BulkWriteAsync(_requests, _options));
 }
コード例 #35
0
        public void Add <TEntity>(IEnumerable <TEntity> entityList) where TEntity : class
        {
            IMongoCollection <TEntity> entityCollection = (IMongoCollection <TEntity>)GetCollection(typeof(TEntity));

            entityCollection.WithWriteConcern(WriteConcern.Acknowledged).InsertMany(entityList);
        }
コード例 #36
0
 public IMongoCollection <T> WithWriteConcern(WriteConcern writeConcern)
 {
     return(_Repository.WithWriteConcern(writeConcern));
 }
コード例 #37
0
 protected override Task ExecuteAsync(IMongoCollection <BsonDocument> collection)
 {
     return(collection.WithWriteConcern(_writeConcern).DeleteOneAsync(_filter));
 }