Exemple #1
0
        /// <summary>
        /// 一行一行处理更新或者插入数据
        /// </summary>
        /// <param name="primaryKeys">主键列名</param>
        /// <param name="collectionName">表名</param>
        /// <param name="dtb">数据</param>
        /// <param name="errorMsg">错误信息</param>
        /// <returns>是否成功</returns>
        public bool UpdateOrInsertRowByRow(string primaryKeys, string collectionName, SqlDataReader dataReader, out string errorMsg)
        {
            errorMsg = string.Empty;
            if (dataReader == null || !dataReader.HasRows)
            {
                return(true);
            }

            MongoCollection collection = GetMongoCollection(collectionName);

            while (dataReader.Read())
            {
                IMongoQuery query = GetQuery(primaryKeys, dataReader);
                MongoDB.Driver.Builders.UpdateBuilder update = new MongoDB.Driver.Builders.UpdateBuilder();

                for (int i = 0; i < dataReader.FieldCount; i++)
                {
                    BsonValue bsonValue = BsonValue.Create(dataReader[i]);
                    update.AddToSet(dataReader.GetName(i), bsonValue);
                }
                WriteConcernResult result = collection.Update(query, update, UpdateFlags.Upsert);
                if (!result.Ok)
                {
                    errorMsg = result.ErrorMessage;
                    return(false);
                }
            }
            dataReader.Close();
            dataReader.Dispose();
            return(true);
        }
        private void UpdateWithVersion(TEntity item)
        {
            var versioned   = (IVersioned)item;
            int origVersion = versioned.Version;

            versioned.Version++;

            // where id = ? and (version = ? or version is null)
            IMongoQuery query = Query.And(
                Query <TEntity> .EQ(dbItem => dbItem.Id, item.Id),
                Query.Or(
                    Query.EQ("Version", origVersion),
                    Query.NotExists("Version"))
                );

            WriteConcernResult result = _collection.Update(query, Update <TEntity> .Replace(item));

            if (result.DocumentsAffected == 0)
            {
                versioned.Version--;
                string message = string.Format(
                    "Attempted to update {0} (Id={1},Version={2}) but it has been updated by another transaction or deleted.",
                    typeof(TEntity).Name, item.Id, origVersion);
                throw new StaleObjectException(message);
            }
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Insert(T model)
        {
            WriteConcernResult res = this.collection.Insert(model);

            (model as AbstractMongoModel).id_string = (model as AbstractMongoModel).id.ToString();
            return(res.Ok);
        }
        protected override void When()
        {
            var documentSource = new BatchableSource<BsonDocument>(new[] { _document });
            var operation = new InsertOpcodeOperation<BsonDocument>(CollectionNamespace, documentSource, BsonDocumentSerializer.Instance, MessageEncoderSettings);

            _result = ExecuteOperationAsync(operation).GetAwaiter().GetResult().First();
        }
Exemple #5
0
        /// <summary>
        /// 插入数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static WriteConcernResult Insert <T>(string databaseName, string collectionName, T entity)
        {
            // ClientInstance.GetDatabase(databaseName).GetCollection<T>(collectionName).InsertOne(entity);
            WriteConcernResult result = ClientInstance.GetServer().GetDatabase(databaseName).GetCollection <T>(collectionName).Insert <T>(entity);

            return(result);
        }
Exemple #6
0
    /// <summary>
    /// Synchronizes the location. Ok guys.. how do we this?
    /// </summary>
    private IEnumerator SyncLocation()
    {
        if (_playerTransform == null)
        {
            _initializer.gameObject.GetComponent <CustomNetworkManager>().SyncPlayers.Remove(InternalId);
        }
        else
        {
            MongoCollection <PlayerLocation> locations = null;
            _initializer.UpdateDatabase((MongoDatabase db) =>
            {
                locations = db.GetCollection <PlayerLocation>("PlayerLocation");
            });

            // To learn the mongo, one must become the mongo!
            yield return(locations);

            IMongoQuery findLocalEntry = Query.EQ("user_Id", _userId.Id);
            _playerLocation.SyncLocaitonAndRotation(_playerTransform);

            UpdateBuilder update = Update
                                   .Set("location.x", _playerLocation.location.x)
                                   .Set("location.y", _playerLocation.location.y)
                                   .Set("location.z", _playerLocation.location.z)

                                   .Set("rotation.w", _playerLocation.rotation.w)
                                   .Set("rotation.x", _playerLocation.rotation.x)
                                   .Set("rotation.y", _playerLocation.rotation.y)
                                   .Set("rotation.z", _playerLocation.rotation.z);

            // That's a funny name. This statement updates the database with these vals.
            WriteConcernResult result = locations.Update(findLocalEntry, update);
        }
    }
        public void Delete(object entity)
        {
            DeleteBarrierDataRequest request = (DeleteBarrierDataRequest)entity;

            try
            {
                using (PatientGoalMongoContext ctx = new PatientGoalMongoContext(_dbName))
                {
                    var q = MB.Query <MEPatientBarrier> .EQ(b => b.Id, ObjectId.Parse(request.BarrierId));

                    var uv = new List <MB.UpdateBuilder>();
                    uv.Add(MB.Update.Set(MEPatientBarrier.TTLDateProperty, System.DateTime.UtcNow.AddDays(_expireDays)));
                    uv.Add(MB.Update.Set(MEPatientBarrier.DeleteFlagProperty, true));
                    uv.Add(MB.Update.Set(MEPatientBarrier.UpdatedByProperty, ObjectId.Parse(this.UserId)));
                    uv.Add(MB.Update.Set(MEPatientBarrier.LastUpdatedOnProperty, DateTime.UtcNow));

                    IMongoUpdate       update = MB.Update.Combine(uv);
                    WriteConcernResult res    = ctx.PatientBarriers.Collection.Update(q, update);

                    AuditHelper.LogDataAudit(this.UserId,
                                             MongoCollectionName.PatientBarrier.ToString(),
                                             request.BarrierId.ToString(),
                                             Common.DataAuditType.Delete,
                                             request.ContractNumber);
                }
            }
            catch (Exception) { throw; }
        }
Exemple #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(string id)
        {
            IMongoQuery        query  = Query.EQ("_id", ObjectId.Parse(id));
            WriteConcernResult result = _contacts.Remove(query);

            return(result.DocumentsAffected == 1);
        }
Exemple #9
0
        protected virtual T Put(T t, ICriterion criterion, IContext context)
        {
            if (Collection != null)
            {
                MongoUpdate update = PutQuery(t, criterion, context);
                if (update != null && update.Query != null && update.Update != null)
                {
                    WriteConcernResult result = Collection.Update(update.Query, update.Update);
                    return(t != null ? t : Collection.FindOneAs <T>(update.Query));
                }
                else
                {
                    if (t != null)
                    {
                        Collection.Save <T>(t);
                        return(t);
                    }
                    else if (criterion != null)
                    {
                        IMongoQuery  whereQuery  = UsesMongoObjectId ? QueryByObjectId(criterion) : QueryByModelId(criterion);
                        IMongoUpdate patchUpdate = new UpdateDocument();
                        Collection.Update(whereQuery, criterion.ToMongoPatch());
                        return(Collection.FindOneAs <T>(whereQuery));
                    }
                }
            }


            return(t);
        }
        public IHttpActionResult UpdateUser(Favorites fav)
        {
            var collection = mongoDb.GetCollection <Users>("Users");

            IMongoQuery query = Query.EQ("UserName", fav.User);

            var cursor   = collection.FindOne(query);
            var res      = cursor.Favorites.Select(p => p.AsBsonArray);
            var favCount = res.Count();

            fav.Id = favCount + 1;
            //fav.Category = fav.Category.First().ToString().ToUpper() + fav.Category.Substring(1);
            BsonArray test = new BsonArray
            {
                fav.Id,
                fav.Category,
                fav.From,
                fav.To
            };

            IMongoUpdate update = Update
                                  .Push("Favorites", test);

            result = collection.Update(query, update);

            return(Ok(fav.Id + ' ' + fav.User + ' ' + fav.Category + ' ' + fav.From + ' ' + fav.To));
        }
Exemple #11
0
        public void TestThrowsWriteConcernExceptionWhenOkButHasJNoteOnPre26Servers()
        {
            var response = new BsonDocument
            {
                { "err", BsonNull.Value },
                { "code", 20 },
                { "n", 0 },
                { "connectionId", 1 },
                { "ok", 1 },
                { "jnote", "oops" }
            };

            var writeConcernResult = new WriteConcernResult(response);

            writeConcernResult.ServerInstance = _primary;
            var ex = ExceptionMapper.Map(writeConcernResult);

            if (_primary.BuildInfo.Version < new Version(2, 6, 0))
            {
                Assert.IsNull(ex);
            }
            else
            {
                Assert.IsNotNull(ex);
                Assert.IsInstanceOf <WriteConcernException>(ex);
            }
        }
Exemple #12
0
        protected override void When()
        {
            var documentSource = new BatchableSource <BsonDocument>(new[] { _document });
            var operation      = new InsertOpcodeOperation <BsonDocument>(CollectionNamespace, documentSource, BsonDocumentSerializer.Instance, MessageEncoderSettings);

            _result = ExecuteOperationAsync(operation).GetAwaiter().GetResult().First();
        }
        public bool RemoveContact(string id)
        {
            IMongoQuery        query  = Query.EQ("_id", id);
            WriteConcernResult result = _contacts.Remove(query);

            return(result.DocumentsAffected == 1);
        }
Exemple #14
0
        public bool blnUpdateDocument(string strCollectionName, IMongoQuery query, IMongoUpdate update)
        {
            const string udcErrorMethod = "blnUpdateDocument";
            bool         blnReturn      = false;

            try
            {
                if (!(string.IsNullOrWhiteSpace(strMongoDataBase)) && !(string.IsNullOrWhiteSpace(strCollectionName)))
                {
                    WriteConcernResult objWrite = objMdbServer.GetDatabase(strMongoDataBase).GetCollection(strCollectionName).Update(query, update, WriteConcern.Acknowledged);
                    blnReturn = objWrite.Ok;
                }
                else
                {
                    strException = "MongoDataBaseName and MongoCollection Name is Null or Void";
                    clsLog.blnLogError("clsMongoDBEngine", "bsonReadDocument", strException, "");
                }
            }
            catch (Exception ex)
            {
                strException = ex.Message;
                clsLog.blnLogError(udcErrorSource, udcErrorMethod, strException, "DNF Error");
            }

            return(blnReturn);
        }
        public bool Update(ObjectId id, UpdateBuilder <T> updateBuilder)
        {
            var query = Query <T> .EQ(x => x._id, id);

            LastWriteConcernResult = Collection.Update(query, updateBuilder);
            return(LastWriteConcernResult.Ok);
        }
Exemple #16
0
 /// <summary>
 /// Deletes the specified id and it's associated document from the specified collection.
 /// </summary>
 /// <param name="id">The name of the id to delete.</param>
 /// <param name="collection">The name of the collection to delete the document in.</param>
 /// <returns>True if the id/document was deleted, false if there was an error or it could not otherwise be deleted.</returns>
 public bool Delete(string id, string collection)
 {
     if (!string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(collection) && isCollectionNameValid(collection))
     {
         try
         {
             MongoCollection mongoCollection = database.GetCollection <BsonDocument>(collection);
             // Create a query to identify the document by id.
             QueryDocument query = new QueryDocument("_id", new ObjectId(id));
             // Delete the document in the collection.
             WriteConcernResult result = mongoCollection.Remove(query);
             if (result.Ok)
             {
                 // The document was deleted.
                 return(true);
             }
             else
             {
                 // There was an error deleting the document.
                 return(false);
             }
         }
         catch (Exception)
         {
             // There was an error deleting the document.
             return(false);
         }
     }
     else
     {
         // A null or empty id or collection was supplied or the collection name was invalid.
         return(false);
     }
 }
Exemple #17
0
        public void AddSourceDomainToMongoCollection()
        {
            ObjectId     oid = ObjectId.GenerateNewId();
            BsonDocument doc = new BsonDocument {
                { "_id", oid },
                { "rptGdDomainsID", 1 },      //if missing, its not a gd domain
                { "DomainID", 135123344 },    //informational for lookups on domain. Portfolio save from MSMQ uses rptGdDomainsID.
                { "DomainName", "godaddy.com" },
                { "PrivateLabelID", 1 },      //should be 0 for non-gd domains?
                { "ShopperID", "shopid123" }, //empty string for non gd domains? if null, it won't get inserted into mongo unless we specify
                { "CreateDate", DateTime.Now.ToUniversalTime() },
                { "LastCrawlDate", DateTime.Now.AddHours(1).ToUniversalTime() },
            };


            MongoDatabase localDB = MongoSrvr.GetDatabase("DRONE");
            MongoCollection <BsonDocument> srcColl = localDB.GetCollection <BsonDocument>("TestSource");
            WriteConcernResult             res     = srcColl.Insert <BsonDocument>(doc);

            Assert.IsTrue(res.Ok);

            //cleanup
            res = srcColl.Remove(Query.EQ("_id", oid), RemoveFlags.Single, WriteConcern.Acknowledged);
            Assert.IsTrue(res.Ok);

            /*
             * We know that portfolio queue processor save uses rptGdDomainsID, so if we are processing a domain w/out that id we can assume its
             * NOT a GD domain since its not in rptGdDomains.
             * If it's missing that ID, the queueprocessor can decide to use a diff datasource to store it elsewhere. This way we still get use
             * of the MSMQ even for non-GD domains and we can batch upload to MongoDB if we want
             */
        }
Exemple #18
0
        private static void RecreateDatabaseAndInstallObjects()
        {
            using (HangfireDbContext context = new HangfireDbContext(ConnectionUtils.GetConnectionString(), ConnectionUtils.GetDatabaseName()))
            {
                context.Init();

                MongoCollection[] collections =
                {
                    context.DistributedLock,
                    context.Counter,
                    context.Hash,
                    context.Job,
                    context.JobParameter,
                    context.JobQueue,
                    context.List,
                    context.Server,
                    context.Set,
                    context.State
                };

                foreach (MongoCollection collection in collections)
                {
                    WriteConcernResult result = collection.RemoveAll();
                    if (result.Ok == false)
                    {
                        throw new InvalidOperationException("Unable to cleanup database.");
                    }
                }
            }
        }
Exemple #19
0
        public bool blnInsertDocument(string strCollectionName, BsonDocument bsonDoc)
        {
            const string udcErrorMethod = "blnInsertDocument";
            bool         blnReturn      = false;

            try
            {
                if (!(string.IsNullOrWhiteSpace(strMongoDataBase)) && !(string.IsNullOrWhiteSpace(strCollectionName) && !(bsonDoc.IsBsonNull)))
                {
                    WriteConcernResult objWrite = objMdbServer.GetDatabase(strMongoDataBase).GetCollection(strCollectionName).Insert(bsonDoc);
                    blnReturn = objWrite.Ok;
                }
                else
                {
                    strException = "MongoDataBaseName, MongoCollectionName and BsonDoc is Null or Void";
                    clsLog.blnLogError(udcErrorSource, udcErrorMethod, strException, "");
                }
            }
            catch (Exception ex)
            {
                strException = ex.Message;
                clsLog.blnLogError(udcErrorSource, udcErrorMethod, strException, "DNF Error");
            }

            return(blnReturn);
        }
Exemple #20
0
        public async void RemoveAsyncTest3()
        {
            string entryMessage1 = "entry 1";

            AddMongoEntryAsyncDelegate(entryMessage1, MONGO_COLLECTION_1_NAME);
            string entryMessage2 = "entry 2";

            AddMongoEntryAsyncDelegate(entryMessage2, MONGO_COLLECTION_1_NAME);

            List <Entry> results = new List <Entry>(_reader.Read <Entry>(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));

            Assert.AreEqual(2, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);
            Assert.AreEqual(entryMessage2, results[1].Message);

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

            // remove entries with Message != entryMessage1
            WriteConcernResult result = await _databaseUpdater.RemoveAsync <Entry>(MONGO_COLLECTION_1_NAME, searchQuery, _writeConcern);

            Assert.IsNotNull(result);
            Assert.IsFalse(result.HasLastErrorMessage);
            Assert.AreEqual(1, result.DocumentsAffected);
            Assert.IsFalse(result.UpdatedExisting);
            Assert.IsNull(result.Upserted);

            results = new List <Entry>(_reader.Read <Entry>(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
            Assert.AreEqual(1, results.Count());
            Assert.AreEqual(entryMessage1, results[0].Message);
        }
Exemple #21
0
        /// <summary>
        /// 修改门店
        /// </summary>
        /// <param name="storeDTO">门店实体</param>
        public ResultDTO UpdateStoreExt(Jinher.AMP.BTP.Deploy.StoreDTO storeDTO)
        {
            try
            {
                StoreMgDTO storeMg = new StoreMgDTO();
                storeMg.FillWith(storeDTO);
                storeMg.Location = new double[] { (double)storeDTO.XAxis, (double)storeDTO.YAxis };
                WriteConcernResult wcResult = MongoCollections.Store.Save(storeMg);
                //var ub = Update.Set("Id",storeDTO.Id);
                //var storeQuery = Query<StoreMgDTO>.Where(c => c.Id == storeDTO.Id);
                //_collection.FindAndModify(storeQuery, SortBy.Null, ub);
                //_collection.Update(storeQuery,);
            }
            catch (Exception ex)
            {
                LogHelper.Error(string.Format("修改门店服务异常。storeDTO:{0}", JsonHelper.JsonSerializer(storeDTO)), ex);
                return(new ResultDTO {
                    ResultCode = 1, Message = "Error"
                });
            }



            return(new ResultDTO {
                ResultCode = 0, Message = "Success"
            });
        }
        public void TestThrowsDuplicateKeyExceptionForMongos(int code)
        {
            var response = new BsonDocument
            {
                { "ok", 1 },
                { "err", string.Format("E{0} duplicate key error index 1", code) },
                { "errObjects", new BsonArray
                  {
                      new BsonDocument
                      {
                          { "ok", 1 },
                          { "err", string.Format("E{0} duplicate key error index 1", code) },
                          { "code", code }
                      },
                      new BsonDocument
                      {
                          { "ok", 1 },
                          { "err", string.Format("E{0} duplicate key error index 2", code) },
                          { "code", code }
                      },
                  } }
            };

            var writeConcernResult = new WriteConcernResult(response);
            var ex = ExceptionMapper.Map(writeConcernResult);

            Assert.IsNotNull(ex);
            Assert.IsInstanceOf <MongoDuplicateKeyException>(ex);
        }
Exemple #23
0
        public void AddJobToMongoAndRemove()
        {
            ObjectId oid = ObjectId.GenerateNewId();
            Job      job = new Job
            {
                _id = oid
                ,
                ScriptFileName = "scriptname.bteq"
                ,
                ProjectName = "TestRun"
                ,
                IsActive = "False"
            };

            job.Schedule = new Dictionary <string, string>();
            job.Schedule.Add("StartTime", "12:15");
            job.Schedule.Add("LastRunStart", String.Empty);
            job.Schedule.Add("LastRunComplete", String.Empty);
            job.Schedule.Add("LastRunExitCode", String.Empty);
            job.Schedule.Add("Status", JobStatus.Disabled.ToString());
            job.Schedule.Add("CronX", "0 0/2 * * * ?");

            MongoDatabase         localDB = MongoSrvr.GetDatabase("PMG");
            MongoCollection <Job> jobCol  = localDB.GetCollection <Job>("Test");
            WriteConcernResult    res     = jobCol.Insert <Job>(job);

            Assert.IsTrue(res.Ok);

            //cleanup
            res = jobCol.Remove(Query.EQ("_id", oid), RemoveFlags.Single, WriteConcern.Acknowledged);
            Assert.IsTrue(res.Ok);
        }
Exemple #24
0
        public static bool Update(string dbName, string collectionName, MongoDB.Driver.IMongoQuery query, MongoDB.Driver.Builders.UpdateBuilder update)
        {
            MongoCollection    collection = GetCollection(dbName, collectionName);
            WriteConcernResult result     = collection.Update(query, update);

            return(result.UpdatedExisting);
        }
        public bool SaveDocument(IDocument document, bool rewrite)
        {
            string        dbname = MongoUrl.Create(this.connectionString).DatabaseName;
            MongoDatabase db     = client.GetServer().GetDatabase(dbname);

            var coll = db.GetCollection <IDocument>(collectionName);

            if (coll.Count(Query.EQ("Url", document.Url)) > 0)
            {
                if (rewrite)
                {
                    WriteConcernResult smr = coll.Remove(Query.EQ("Url", document.Url), WriteConcern.Acknowledged);
                    if (smr.HasLastErrorMessage)
                    {
                        Console.WriteLine(smr.ErrorMessage);
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            WriteConcernResult smr2 = coll.Insert(document, WriteConcern.Acknowledged);

            if (smr2.HasLastErrorMessage)
            {
                Console.WriteLine(smr2.ErrorMessage);
            }
            return(!smr2.HasLastErrorMessage);
        }
Exemple #26
0
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            var query        = Query.And(Query.EQ("ApplicationName", this.ApplicationName), Query.EQ("Username", username));
            var bsonDocument = this.mongoCollection.FindOneAs <BsonDocument>(query);

            if (!this.VerifyPassword(bsonDocument, oldPassword))
            {
                return(false);
            }

            var validatePasswordEventArgs = new ValidatePasswordEventArgs(username, newPassword, false);

            OnValidatingPassword(validatePasswordEventArgs);

            if (validatePasswordEventArgs.Cancel)
            {
                throw new MembershipPasswordException(validatePasswordEventArgs.FailureInformation.Message);
            }

            //var update = Update.Set("LastPasswordChangedDate", DateTime.UtcNow).Set("Password", EncodePassword(newPassword, this.PasswordFormat, bsonDocument["Salt"].AsString));
            //this.mongoCollection.Update(query, update);

            bsonDocument["LastPasswordChangedDate"] = DateTime.UtcNow;
            bsonDocument["Password"] = EncodePassword(newPassword, this.PasswordFormat, bsonDocument["Salt"].AsString);
            WriteConcernResult result = this.mongoCollection.Save(bsonDocument, WriteConcern.Acknowledged);

            return(result.Ok);
        }
Exemple #27
0
        private void Execute(Common.Day item)
        {
            var source      = SourceMongoDb.GetCollection("exevent");
            var destination = DestinationMongoDb.GetCollection("exevent");

            item.BeganAt = DateTime.Now.ToString();
            foreach (var hour in item.Hours)
            {
                try
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    IMongoQuery query  = GenerateMongoQuery(item.Year, item.Month, item.Ordinality, hour.Index);
                    var         cursor = source.Find(query);
                    //var local = cursor.ToList();
                    var pickedup = destination.InsertBatch(cursor);
                    hour.Source = pickedup.Count();
                    WriteConcernResult written = source.Remove(query);
                    hour.Destination = (int)written.DocumentsAffected;
                    sw.Stop();
                    hour.Elapsed = sw.Elapsed.TotalMilliseconds;
                }
                catch (Exception ex)
                {
                    hour.Error = ex.Message;
                }
            }
            item.EndedAt = DateTime.Now.ToString();
        }
Exemple #28
0
        public override bool DeleteValue(string key)
        {
            try
            {
                Server server = ChooseServer(key);
                MongoCollection <MongoDBCacheEntity> collection = GetMongoDBCollection(server.ConnStr);

                var query2 = Query.And(
                    Query.EQ("CacheKey", key)
                    );
                WriteConcernResult res = collection.Remove(query2);//移除文档
                //清空过期的集合数据

                if (res.Ok)
                {
                    OnOperating("删除值完成:end:key:" + key + ",result:" + res.Ok + "," + res.ErrorMessage);
                    return(true);
                }

                return(false);
            }
            catch (Exception ex)
            {
                OnOperating("删除值异常:key:" + key + ",exception:" + JsonConvert.SerializeObject(ex));
                return(false);
            }
        }
Exemple #29
0
        public string UpdateDocument(AdminData adminData)
        {
            try
            {
                MongoDatabase myDB = GetDB();

                MongoCollection <AdminData> adminDataTable = myDB.GetCollection <AdminData>("AdminData");

                QueryDocument queryDoc = new QueryDocument("_id", adminData._id);

                IMongoQuery query = queryDoc;

                //    IMongoUpdate update = new UpdateDocument("Address","Hyd");

                //  IMongoUpdate update = new UpdateDocument().Set("Address", "Hyd") as UpdateDocument;

                //   IMongoUpdate update = new UpdateDocument().Set(queryDoc.IndexOfName("Address"), "Hyd") as UpdateDocument;

                var updateDoc = Update.Set("Address", adminData.Address).Set("Age", adminData.Age.ToString()).Set("Name", adminData.Name).Set("SlNo", adminData.SlNo.ToString());

                IMongoUpdate update = updateDoc;

                WriteConcernResult updateResult = adminDataTable.Update(query, update);

                return("Succcess");
                //  adminDataTable.Update()

                // GetCollection();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemple #30
0
        public bool AddUserToleague(Invitacion invitacion)
        {
            try
            {
                Task <Persona> tp = Task.Factory.StartNew(() => { return(GetDatosUsuarioByMail(invitacion.Mail)); });
                Liga           l  = GetLigaById(invitacion.Id);

                Persona p = tp.Result;
                var     a = p.Cuentas.Where(x => x.Value == invitacion.Mail).Select(x => x.Key).First();

                if (l.Usuarios == null)
                {
                    l.Usuarios = new Dictionary <string, string>();
                }

                l.Usuarios.Add(a, invitacion.Mail);
                WriteConcernResult wcr = GetCollection <Liga>(Settings.Default.ColeccionLiga).Update(
                    Query.EQ("_id", new ObjectId(l.Id)),
                    Update.Replace(l));
                if (wcr.Ok)
                {
                    return(true);
                }
                return(false);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        public bool Delete(T Obj)
        {
            var query = Query <T> .EQ(x => x._id, Obj._id);

            LastWriteConcernResult = Collection.Remove(query);
            return(LastWriteConcernResult.Ok);
        }
 public static void ThrowIfHasWriteConcernError(ConnectionId connectionId, BsonDocument result)
 {
     BsonValue value;
     if (result.TryGetValue("writeConcernError", out value))
     {
         var message = (string)value.AsBsonDocument.GetValue("errmsg", null);
         var writeConcernResult = new WriteConcernResult(result);
         throw new MongoWriteConcernException(connectionId, message, writeConcernResult);
     }
 }
        public void TestDoesNotThrowExceptionWhenEverythingIsKosherWithAWriteConcernResult()
        {
            var response = new BsonDocument
            {
                { "n", 1 },
                { "connectionId", 1 },
                { "ok", 1 }
            };

            var writeConcernResult = new WriteConcernResult(response);
            var ex = ExceptionMapper.Map(_connectionId, writeConcernResult);

            Assert.IsNull(ex);
        }
        public void TestThrowsDuplicateKeyExceptionForMongod(int code)
        {
            var response = new BsonDocument
            {
                { "ok", 1 },
                { "err", string.Format("E{0} duplicate key error index: test.foo.$_id_  dup key: {{ : 1.0 }}", code) },
                { "code", code },
                { "n", 0 },
                { "connectionId", 1 }
            };

            var writeConcernResult = new WriteConcernResult(response);
            var ex = ExceptionMapper.Map(_connectionId, writeConcernResult);

            Assert.IsNotNull(ex);
            Assert.IsInstanceOf<MongoDuplicateKeyException>(ex);
        }
        /// <summary>
        /// Maps the specified writeConcernResult to a custom exception (if necessary).
        /// </summary>
        /// <param name="writeConcernResult">The write concern result.</param>
        /// <returns>
        /// The custom exception (or null if the writeConcernResult was not mapped to an exception).
        /// </returns>
        public static Exception Map(WriteConcernResult writeConcernResult)
        {
            var code = GetCode(writeConcernResult.Response);
            if (code.HasValue)
            {
                switch (code.Value)
                {
                    case 11000:
                    case 11001:
                    case 12582:
                        var errorMessage = string.Format(
                            "WriteConcern detected an error '{0}'. (Response was {1}).",
                            writeConcernResult.LastErrorMessage, writeConcernResult.Response.ToJson());
                        return new MongoDuplicateKeyException(errorMessage, writeConcernResult);
                }
            }

            bool ok = writeConcernResult.Response.GetValue("ok", false).ToBoolean();

            if (!ok)
            {
                var errorMessage = string.Format(
                    "WriteConcern detected an error '{0}'. (Response was {1}).",
                    writeConcernResult.LastErrorMessage, writeConcernResult.Response.ToJson());
                return new WriteConcernException(errorMessage, writeConcernResult);
            }

            if (writeConcernResult.HasLastErrorMessage)
            {
                var errorMessage = string.Format(
                    "WriteConcern detected an error '{0}'. (Response was {1}).",
                    writeConcernResult.LastErrorMessage,
                    writeConcernResult.Response.ToJson());
                return new WriteConcernException(errorMessage, writeConcernResult);
            }

            return null;
        }
 private BulkWriteBatchResult CreateSingleRequestResult(WriteRequest request, int originalIndex, WriteConcernResult writeConcernResult, MongoWriteConcernException writeConcernException)
 {
     var indexMap = new IndexMap.RangeBased(0, originalIndex, 1);
     return BulkWriteBatchResult.Create(
         request,
         writeConcernResult,
         writeConcernException,
         indexMap);
 }
        public void TestThrowsDuplicateKeyExceptionForMongos(int code)
        {
            var response = new BsonDocument
            {
                { "ok", 1 },
                { "err", string.Format("E{0} duplicate key error index 1", code) },
                { "errObjects", new BsonArray
                    {
                        new BsonDocument
                        {
                            { "ok", 1 },
                            { "err", string.Format("E{0} duplicate key error index 1", code) },
                            { "code", code }
                        },
                        new BsonDocument
                        {
                            { "ok", 1 },
                            { "err", string.Format("E{0} duplicate key error index 2", code) },
                            { "code", code }
                        },
                    } }
            };

            var writeConcernResult = new WriteConcernResult(response);
            var ex = ExceptionMapper.Map(_connectionId, writeConcernResult);

            Assert.IsNotNull(ex);
            Assert.IsInstanceOf<MongoDuplicateKeyException>(ex);
        }
        protected virtual async Task<BulkWriteBatchResult> EmulateSingleRequestAsync(IConnectionHandle connection, WriteRequest request, int originalIndex, TimeSpan timeout, CancellationToken cancellationToken)
        {
            var protocol = CreateProtocol(connection, request);

            WriteConcernResult writeConcernResult = null;
            WriteConcernException writeConcernException = null;
            try
            {
                var protocolResult = await protocol.ExecuteAsync(connection, timeout, cancellationToken);
                if (protocolResult != null)
                {
                    writeConcernResult = new WriteConcernResult(protocolResult);
                }
            }
            catch (WriteException ex)
            {
                writeConcernResult = new WriteConcernResult(ex.Result);
                writeConcernException = new WriteConcernException(ex.Message, writeConcernResult);
            }

            var indexMap = new IndexMap.RangeBased(0, originalIndex, 1);
            return BulkWriteBatchResult.Create(
                request,
                writeConcernResult,
                writeConcernException,
                indexMap);
        }
        public void TestThrowsWriteConcernExceptionWhenOkButHasLastErrorMessage()
        {
            var response = new BsonDocument
            {
                { "err", "oops" },
                { "code", 20 },
                { "n", 0 },
                { "connectionId", 1 },
                { "ok", 1 }
            };

            var writeConcernResult = new WriteConcernResult(response);
            var ex = ExceptionMapper.Map(_connectionId, writeConcernResult);

            Assert.IsNotNull(ex);
            Assert.IsInstanceOf<MongoWriteConcernException>(ex);
        }
        public static BulkWriteBatchResult Create(
            WriteRequest request,
            WriteConcernResult writeConcernResult,
            MongoWriteConcernException writeConcernException,
            IndexMap indexMap)
        {
            var processedRequests = new[] { request };
            var unprocessedRequests = __noWriteRequests;
            BsonValue upsertId = null;
            var documentsAffected = 0L;

            if (writeConcernResult != null)
            {
                upsertId = writeConcernResult.Upserted;
                documentsAffected = writeConcernResult.DocumentsAffected;
                var updateRequest = request as UpdateRequest;

                if (upsertId == null &&
                    documentsAffected == 1 &&
                    updateRequest != null &&
                    updateRequest.IsUpsert &&
                    !writeConcernResult.UpdatedExisting)
                {
                    // Get the _id field first from the Update document
                    // and then from the Query document.
                    upsertId =
                        updateRequest.Update.ToBsonDocument().GetValue("_id", null) ??
                        updateRequest.Filter.ToBsonDocument().GetValue("_id", null);
                }
            }

            var upserts = (upsertId == null) ? __noUpserts : new[] { new BulkWriteOperationUpsert(0, upsertId) };
            var writeErrors = __noWriteErrors;
            BulkWriteConcernError writeConcernError = null;

            if (writeConcernException != null)
            {
                var getLastErrorResponse = writeConcernResult.Response;
                if (IsGetLasterrorResponseAWriteConcernError(getLastErrorResponse))
                {
                    writeConcernError = CreateWriteConcernErrorFromGetLastErrorResponse(getLastErrorResponse);
                }
                else
                {
                    writeErrors = new[] { CreateWriteErrorFromGetLastErrorResponse(getLastErrorResponse) };
                }
            }

            if (request.RequestType == WriteRequestType.Insert && writeErrors.Count == 0)
            {
                documentsAffected = 1; // note: DocumentsAffected is 0 for inserts
            }

            var matchedCount = 0L;
            var deletedCount = 0L;
            var insertedCount = 0L;
            long? modifiedCount = 0L;
            switch (request.RequestType)
            {
                case WriteRequestType.Delete:
                    deletedCount = documentsAffected;
                    break;
                case WriteRequestType.Insert:
                    insertedCount = documentsAffected;
                    break;
                case WriteRequestType.Update:
                    matchedCount = documentsAffected - upserts.Count();
                    modifiedCount = null; // getLasterror does not report this value
                    break;
            }

            return new BulkWriteBatchResult(
                1, // batchCount
                processedRequests,
                unprocessedRequests,
                matchedCount,
                deletedCount,
                insertedCount,
                modifiedCount,
                upserts,
                writeErrors,
                writeConcernError,
                indexMap);
        }
        public void TestThrowsWriteConcernExceptionWhenNotOk()
        {
            var response = new BsonDocument
            {
                { "err", "oops" },
                { "code", 20 },
                { "n", 0 },
                { "connectionId", 1 },
                { "ok", 0 }
            };

            var writeConcernResult = new WriteConcernResult(response);
            var ex = ExceptionMapper.Map(_connectionId, writeConcernResult);

            Assert.NotNull(ex);
            Assert.IsType<MongoWriteConcernException>(ex);
        }