예제 #1
0
파일: MongoHelper.cs 프로젝트: GNCPay/core
 public bool Delete(string objectName, dynamic _id)
 {
     FindAndRemoveArgs arg = new FindAndRemoveArgs();
     arg.Query = Query.EQ("_id", _id);
     FindAndModifyResult result = Database.GetCollection(objectName).FindAndRemove(arg);
     return result.Ok;
 }
 public void Delete(Material material)
 {
     var materials = db.GetCollection<Material>("Materials");
     var query = Query.And(Query.EQ("Name", material.Name));
     var findAndRemoveArguments = new FindAndRemoveArgs();
     findAndRemoveArguments.Query = query;
     materials.FindAndRemove(findAndRemoveArguments);
 }
 public void Delete(Product product)
 {
     var products = db.GetCollection<Product>("Products");
     var query = Query.And(Query.EQ("Price", product.Price), Query.EQ("Name", product.Name));
     var findAndRemoveArguments = new FindAndRemoveArgs();
     findAndRemoveArguments.Query = query;
     products.FindAndRemove(findAndRemoveArguments);
 }
 public void Delete(Client client)
 {
     var clients = db.GetCollection<Client>("Clients");
     var query = Query.And(
         Query.EQ("Name", client.Name),
         Query.EQ("Address", client.Address),
         Query.EQ("Contact", client.Contact),
         Query.EQ("Email", client.Email),
         Query.EQ("Mobile", client.Mobile));
     var findAndRemoveArguments = new FindAndRemoveArgs();
     findAndRemoveArguments.Query = query;
     clients.FindAndRemove(findAndRemoveArguments);
 }
 public void TestFindAndRemoveWithMaxTime()
 {
     if (_primary.Supports(FeatureId.MaxTime))
     {
         using (var failpoint = new FailPoint(FailPointName.MaxTimeAlwaysTimeout, _server, _primary))
         {
             if (failpoint.IsSupported())
             {
                 failpoint.SetAlwaysOn();
                 var args = new FindAndRemoveArgs { MaxTime = TimeSpan.FromMilliseconds(1) };
                 Assert.Throws<ExecutionTimeoutException>(() => _collection.FindAndRemove(args));
             }
         }
     }
 }
        public void TestFindAndRemoveWithFields()
        {
            _collection.RemoveAll();
            _collection.Insert(new BsonDocument { { "x", 1 }, { "y", 1 } });
            _collection.Insert(new BsonDocument { { "x", 1 }, { "y", 2 } });

            var args = new FindAndRemoveArgs
            {
                Query = Query.EQ("x", 1),
                SortBy = SortBy.Ascending("y"),
                Fields = Fields.Include("_id")
            };
            var result = _collection.FindAndRemove(args);
            Assert.AreEqual(1, result.ModifiedDocument.ElementCount);
            Assert.AreEqual("_id", result.ModifiedDocument.GetElement(0).Name);
        }
        public void TestFindAndRemoveNoMatchingDocument()
        {
            _collection.RemoveAll();

            var args = new FindAndRemoveArgs
            {
                Query = Query.EQ("inprogress", false),
                SortBy = SortBy.Descending("priority")
            };
            var result = _collection.FindAndRemove(args);

            Assert.IsTrue(result.Ok);
            Assert.IsNull(result.ErrorMessage);
            Assert.IsNull(result.ModifiedDocument);
            Assert.IsNull(result.GetModifiedDocumentAs<FindAndModifyClass>());
        }
        public void TestFindAndRemove()
        {
            _collection.RemoveAll();
            _collection.Insert(new BsonDocument { { "x", 1 }, { "y", 1 } });
            _collection.Insert(new BsonDocument { { "x", 1 }, { "y", 2 } });

            var args = new FindAndRemoveArgs
            {
                Query = Query.EQ("x", 1),
                SortBy = SortBy.Ascending("y")
            };
            var result = _collection.FindAndRemove(args);
            Assert.AreEqual(1, result.ModifiedDocument["y"].ToInt32());
            Assert.AreEqual(1, _collection.Count());
        }
예제 #9
0
        public async void FindAndRemoveTest()
        {
            string entryMessage1 = "entry 1";
            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List<Entry> results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);

            var searchQuery = Query.EQ("Message", entryMessage1);

            var update = Update.Set("Message", MONGO_EDITED_TEXT);
            var sortBy = SortBy.Descending("TimeStamp");
            IMongoFields fields = Fields.Null;
            FindAndRemoveArgs findAndRemoveArgs = new FindAndRemoveArgs();
            findAndRemoveArgs.Query = searchQuery;
            findAndRemoveArgs.SortBy = sortBy;

            FindAndModifyResult findAndModifyResult = await _asyncUpdaterT.FindAndRemoveAsync(MONGO_COLLECTION_1_NAME, findAndRemoveArgs);

            Assert.IsTrue(findAndModifyResult.Ok);
            Assert.IsNull(findAndModifyResult.ErrorMessage);
            Assert.IsNotNull(findAndModifyResult.ModifiedDocument); 

            results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(0, results.Count());/*we deleted the entry via FindAndRemove...*/
        }
        public void FindAndRemoveTest2()
        {
            _AsyncDelegateUpdaterT.AsyncFindAndRemoveCompleted -= new FindAndRemoveCompletedEvent(_updaterAsyncT_AsyncFindAndRemoveCompleted);

            string entryMessage1 = "entry 1";
            AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);

            List<Entry> results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);

            var searchQuery = Query.EQ("Message", entryMessage1);

            var update = Update.Set("Message", MONGO_EDITED_TEXT);
            var sortBy = SortBy.Descending("TimeStamp");
            IMongoFields fields = Fields.Null;
            FindAndRemoveArgs findAndRemoveArgs = new FindAndRemoveArgs();
            findAndRemoveArgs.Query = searchQuery;
            findAndRemoveArgs.SortBy = sortBy;
            _AsyncDelegateUpdaterT.FindAndRemoveAsync(MONGO_COLLECTION_1_NAME, findAndRemoveArgs);
            Thread.Sleep(2000); // wait 2 seconds to show that event handler will not pick up callback

            Assert.IsNull(_writeConcernResult);

            results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(0, results.Count());/*we deleted the entry via FindAndRemove...*/
        }
        public void TestFindAndRemoveWithWriteConcernError()
        {
            _collection.RemoveAll();
            _collection.Insert(new BsonDocument("x", 1));
            var collectionSettings = new MongoCollectionSettings
            {
                WriteConcern = new WriteConcern(9)
            };
            var collection = _database.GetCollection(_collection.Name, collectionSettings);
            var args = new FindAndRemoveArgs
            {
                Query = Query.EQ("x", 1)              
            };

            Action action = () => collection.FindAndRemove(args);

            var exception = action.ShouldThrow<MongoWriteConcernException>().Which;
            var commandResult = exception.Result;
            var result = commandResult["value"].AsBsonDocument;
            result["x"].Should().Be(1);
            _collection.Count().Should().Be(0);
        }
예제 #12
0
        public void TestFindAndRemoveWithWriteConcernError()
        {
            RequireServer.Where(clusterTypes: ClusterTypes.ReplicaSet);
            _collection.RemoveAll();
            _collection.Insert(new BsonDocument { { "_id", 1 }, { "x", 1 } });
            var collectionSettings = new MongoCollectionSettings
            {
                WriteConcern = new WriteConcern(9)
            };
            var collection = _database.GetCollection(_collection.Name, collectionSettings);
            var args = new FindAndRemoveArgs
            {
                Query = Query.EQ("x", 1)              
            };

            BsonDocument modifiedDocument;
            if (_server.BuildInfo.Version >= new Version(3, 2, 0))
            {
                Action action = () => collection.FindAndRemove(args);

                var exception = action.ShouldThrow<MongoWriteConcernException>().Which;
                var commandResult = exception.Result;
                modifiedDocument = commandResult["value"].AsBsonDocument;
            }
            else
            {
                var result = collection.FindAndRemove(args);

                modifiedDocument = result.ModifiedDocument;
            }

            modifiedDocument.Should().Be("{ _id : 1, x : 1 }");
            _collection.Count().Should().Be(0);
        }
예제 #13
0
 public object FindAndRemoveAs(Type documentType, IMongoQuery query, IMongoSortBy sortBy)
 {
     var args = new FindAndRemoveArgs();
     args.Query = query;
     args.SortBy = sortBy;
     return _this.FindAndRemove(args).GetModifiedDocumentAs(documentType);
 }
        /// <summary>
        /// Deletes the role.
        /// </summary>
        /// <param name="rolename">The rolename.</param>
        /// <param name="throwOnPopulatedRole">if set to <c>true</c> [throw on populated role].</param>
        /// <returns></returns>
        public override bool DeleteRole(string rolename, bool throwOnPopulatedRole)
        {
            MongoClient client = new MongoClient(connectionString);
            MongoServer server = client.GetServer(); // connect to the mongoDB url.
            MongoDatabase ProviderDB = server.GetDatabase(pMongoProviderDatabaseName, WriteConcern.Acknowledged);

            MongoCollection<BsonDocument> roles = ProviderDB.GetCollection(pmongoProviderRolesCollectionName);

            if (!RoleExists(rolename))
            {
                throw new ProviderException("Role does not exist.");
            }

            if (throwOnPopulatedRole && GetUsersInRole(rolename).Length > 0)
            {
                throw new ProviderException("Cannot delete a populated role.");
            }

            bool bSuccess = false;
            try
            {
                // Remove the role.
                var query = Query.And(Query.EQ("ApplicationNameLowerCase", pApplicationName.ToLower()),
                    Query.EQ("RolenameLowerCase", rolename.ToLower()),
                    Query.EQ("RecordType", RecordType.RoleDefinition.ToString()));

                FindAndRemoveArgs args = new FindAndRemoveArgs();
                args.Query = query;
                args.SortBy = SortBy.Null;
                bSuccess = roles.FindAndRemove(args).Ok;

                if (bSuccess)
                {
                    // Remove users associated to the role.
                    var query2 = Query.And(Query.EQ("ApplicationNameLowerCase", pApplicationName.ToLower()),
                    Query.EQ("RolenameLowerCase", rolename.ToLower()),
                    Query.EQ("RecordType", RecordType.RoleToUser.ToString()));

                    bSuccess = roles.Remove(query2).Ok;
                }
            }
            catch (ApplicationException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "DeleteRole");
                }
            }
            finally
            {
            }

            return bSuccess;
        }
        /// <summary>
        /// Removes a user from the membership data source.
        /// </summary>
        /// <param name="username">The name of the user to delete.</param>
        /// <param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param>
        /// <returns>
        /// true if the user was successfully deleted; otherwise, false.
        /// </returns>
        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            MiniProfiler profiler = MiniProfiler.Current;
            MethodBase currentMethod = MethodBase.GetCurrentMethod();
            using (profiler.Step(String.Format("{0} : {1}", currentMethod.DeclaringType.Name, currentMethod.Name)))
            {

                MongoClient client = new MongoClient(connectionString);
                MongoServer server = client.GetServer(); // connect to the mongoDB url.
                MongoDatabase ProviderDB = server.GetDatabase(pMongoProviderDatabaseName, WriteConcern.Acknowledged);

                //Build a query to find the user id and then update with new password.
                MongoCollection<BsonDocument> users = ProviderDB.GetCollection(pmongoProviderMembershipCollectionName);

                var query = Query.And(
                   Query.EQ("ApplicationNameLowerCase", pApplicationName.ToLower()),
                   Query.EQ("UsernameLowerCase", username.ToLower())
                );

                var sortBy = SortBy.Ascending("Username");

                bool bSuccess = false;

                try
                {

                    FindAndRemoveArgs args = new FindAndRemoveArgs();
                    args.Query = query;
                    args.SortBy = SortBy.Null;
                    bSuccess = users.FindAndRemove(args).Ok;

                    if (deleteAllRelatedData)
                    {
                        // Process commands to delete all data for the user in the database.
                    }
                }
                catch (ApplicationException e)
                {
                    if (WriteExceptionsToEventLog)
                    {
                        WriteToEventLog(e, "DeleteUser");

                        throw new ProviderException(exceptionMessage);
                    }
                    else
                    {
                        throw e;
                    }
                }
                finally
                {
                }

                if (bSuccess)
                    return true;
            }

            return false;
        }