public void AddStringPatternProcessors(int generationNumber, IEnumerable<StringPatternProcessor> stringPatternProcessors)
        {
            var stringPatternProcessorResults =
                stringPatternProcessors.Select((x, i) => this.stringPatternProcessorFactory.GetStringPatternProcessorResult(x, generationNumber, i)).ToDictionary(x => x.Id);


            // Update cloned candidates
            var existingIds =
                this.stringPatternProcessorCollection.Find(Query<StringPatternProcessorResult>.In(x => x.Id, stringPatternProcessorResults.Values.Select(x => x.Id)))
                    .SetFields(new FieldsBuilder<StringPatternProcessorResult>().Include(x => x.Id))
                    .Select(x => x.Id);
            foreach (var id in existingIds)
            {
                var newCandidate = stringPatternProcessorResults[id];
                var update = new UpdateBuilder<StringPatternProcessorResult>().Set(x => x.GenerationNumber, generationNumber).Set(x => x.PopulationRank, newCandidate.PopulationRank);
                this.stringPatternProcessorCollection.Update(Query<StringPatternProcessorResult>.EQ(x => x.Id, id), update);
                stringPatternProcessorResults.Remove(id);
            }

            // Batch insert the rest
            var results = this.stringPatternProcessorCollection.InsertBatch(stringPatternProcessorResults.Values);

            var badResults = results.Where(x => !x.Ok).ToArray();
            if (badResults.Any())
            {
                var msg = string.Join(", ", badResults.Select(x => x.ErrorMessage));
                throw new Exception(msg);
            }
        }
示例#2
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            var errorCollection = Database.GetCollection(ErrorRepository.CollectionName);

            ObjectId stackId = document.GetValue(ErrorStackRepository.FieldNames.Id).AsObjectId;
            if (stackId == ObjectId.Empty)
                return;

            BsonValue value;
            bool isHidden = false;
            if (document.TryGetValue(ErrorStackRepository.FieldNames.IsHidden, out value))
                isHidden = value.AsBoolean;

            DateTime? dateFixed = null;

            if (document.TryGetValue(ErrorStackRepository.FieldNames.DateFixed, out value))
                dateFixed = value.ToNullableUniversalTime();

            IMongoQuery query = Query.EQ(ErrorRepository.FieldNames.ErrorStackId, new BsonObjectId(stackId));

            var update = new UpdateBuilder();
            if (isHidden)
                update.Set(ErrorRepository.FieldNames.IsHidden, true);
            if (dateFixed.HasValue)
                update.Set(ErrorRepository.FieldNames.IsFixed, true);

            if (isHidden || dateFixed.HasValue)
                errorCollection.Update(query, update);
        }
示例#3
0
        public static bool Update <T>(string connectionName, string database, string collection, MongoQueryWarpper querys, MongoUpdateWarpper updates, MongoUpdateFlagsWarpper flgs = null)
        {
            if (updates == null || updates.IsEmpty)
            {
                return(false);
            }

            IMongoQuery mongoquery = querys == null ? Query.Null : querys.MongoQuery;

            MD.Builders.UpdateBuilder updateBuilder = updates.MongoUpdateBuilder;
            if (updateBuilder != null)
            {
                var mongocollection = GetCollecion <T>(connectionName, database, collection);

                if (flgs == null)
                {
                    mongocollection.Update(mongoquery, updateBuilder);
                }
                else
                {
                    mongocollection.Update(mongoquery, updateBuilder, flgs.MongoUpdateFlags);
                }
                return(true);
            }

            return(false);
        }
示例#4
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);
        }
示例#5
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document)
        {
            var errorCollection = Database.GetCollection("error");

            ObjectId stackId = document.GetValue("_id").AsObjectId;
            if (stackId == ObjectId.Empty)
                return;

            BsonValue value;
            bool isHidden = false;
            if (document.TryGetValue("hid", out value))
                isHidden = value.AsBoolean;

            DateTime? dateFixed = null;

            if (document.TryGetValue("fdt", out value))
                dateFixed = value.ToNullableUniversalTime();

            IMongoQuery query = Query.EQ("sid", new BsonObjectId(stackId));

            var update = new UpdateBuilder();
            if (isHidden)
                update.Set("hid", true);
            if (dateFixed.HasValue)
                update.Set("fix", true);

            if (isHidden || dateFixed.HasValue)
                errorCollection.Update(query, update, UpdateFlags.Multi);
        }
        public void IncrementStats(string errorStackId, DateTime occurrenceDate)
        {
            // if total occurrences are zero (stack data was reset), then set first occurrence date
            _collection.Update(
                M.Query.And(
                    M.Query.EQ(FieldNames.Id, new BsonObjectId(new ObjectId(errorStackId))),
                    M.Query.EQ(FieldNames.TotalOccurrences, new BsonInt32(0))
                    ),
                M.Update.Set(FieldNames.FirstOccurrence, occurrenceDate));

            // Only update the LastOccurrence if the new date is greater then the existing date.
            IMongoQuery query = M.Query.And(M.Query.EQ(FieldNames.Id, new BsonObjectId(new ObjectId(errorStackId))), M.Query.LT(FieldNames.LastOccurrence, occurrenceDate));

            M.UpdateBuilder update = M.Update.Inc(FieldNames.TotalOccurrences, 1).Set(FieldNames.LastOccurrence, occurrenceDate);

            var result = _collection.Update(query, update);

            if (result.DocumentsAffected > 0)
            {
                return;
            }

            _collection.Update(M.Query.EQ(FieldNames.Id, new BsonObjectId(new ObjectId(errorStackId))), M.Update.Inc(FieldNames.TotalOccurrences, 1));
            InvalidateCache(errorStackId);
        }
        public void TestEmptyUpdateBuilder() {
            var document = new BsonDocument("x", 1);
            collection.Insert(document);

            var query = Query.EQ("_id", document["_id"]);
            var update = new UpdateBuilder();
            Assert.Throws<ArgumentException>(() => collection.Update(query, update));
        }
示例#8
0
        public static long Incr <T>(string connectionName, string database, string collection, MongoQueryWarpper querys, string field, long incr)
        {
            MongoUpdateWarpper updates = new MongoUpdateWarpper();

            updates.Incr(field, incr);

            IMongoQuery mongoquery = querys == null ? Query.Null : querys.MongoQuery;

            MD.Builders.UpdateBuilder updateBuilder = updates.MongoUpdateBuilder;
            if (updateBuilder != null)
            {
                var mongocollection = GetCollecion <T>(connectionName, database, collection);

                var result = mongocollection.Update(mongoquery, updates.MongoUpdateBuilder, UpdateFlags.Upsert);
                if (!result.UpdatedExisting)
                {
                    return(incr);
                }

                var entity   = mongocollection.FindOneAs <T>(querys.MongoQuery);
                var property = typeof(T).GetProperty(field);

                if (property == null)
                {
                    foreach (var mb in typeof(T).GetMembers())
                    {
                        var ca = mb.GetCustomAttributes(typeof(MB.Serialization.Attributes.BsonElementAttribute), true).FirstOrDefault();
                        if (ca == null)
                        {
                            continue;
                        }
                        if (((MB.Serialization.Attributes.BsonElementAttribute)ca).ElementName.Equals(field))
                        {
                            property = typeof(T).GetProperty(mb.Name);
                            break;
                        }
                    }
                }

                if (property == null)
                {
                    return(0);
                }

                return((long)(Convert.ChangeType(property.GetValue(entity, null), typeof(Int64))));
            }

            return(0);
        }
示例#9
0
    /// <summary>
    /// NFX Record -> BSON Update
    /// </summary>
    public static UpdateBuilder ToBSONUpdate(this Record rec)
    {
      var result = new UpdateBuilder();

      foreach(var fld in rec.Fields.Where(f => f.StoreFlag == StoreFlag.LoadAndStore || f.StoreFlag == StoreFlag.OnlyStore))
      {                              
         BsonValue bval = null;
         if (fld is DecimalField)
          bval =  BsonValue.Create(fld.ValueAsString);
         else
          bval =  BsonValue.Create(fld.ValueAsObject);   
        
         result.Set(fld.FieldName, bval);      
      }

      return result;
    }
示例#10
0
 /// <summary>
 /// Combines another UpdateBuilder into this one.
 /// </summary>
 /// <param name="otherUpdate">The UpdateBuilder to combine into this one.</param>
 /// <returns>A combined UpdateBuilder.</returns>
 public UpdateBuilder Combine(UpdateBuilder otherUpdate)
 {
     foreach (var otherOperation in otherUpdate.Document)
     {
         var         otherOperationName = otherOperation.Name;
         var         otherTargets       = otherOperation.Value.AsBsonDocument;
         BsonElement operation;
         if (document.TryGetElement(otherOperationName, out operation))
         {
             operation.Value.AsBsonDocument.Add(otherTargets);
         }
         else
         {
             document.Add(otherOperationName, otherTargets);
         }
     }
     return(this);
 }
示例#11
0
 public static UpdateBuilder<AdianboVideo> UpdateBuilder(AdianboVideo data) {
     var update = new UpdateBuilder<AdianboVideo>();
     if (data.Imdb > 0)
         update = Update<AdianboVideo>.Set(d => d.Imdb, data.Imdb);
     if (!string.IsNullOrEmpty(data.ImdbId))
         update = update.Set(d => d.ImdbId, data.ImdbId);
     if (data.Douban > 0)
         update = Update<AdianboVideo>.Set(d => d.Douban, data.Douban);
     if (!string.IsNullOrEmpty(data.DoubanId))
         update = update.Set(d => d.DoubanId, data.DoubanId);
     if (data.IsTeleplay)
         update = update.Set(d => d.IsTeleplay, true);
     if (!string.IsNullOrEmpty(data.ChinsesName))
         update = update.Set(d => d.ChinsesName, data.ChinsesName);
     if (string.IsNullOrEmpty(data.EnglishName))
         update = update.Set(d => d.EnglishName, data.EnglishName);
     if (!string.IsNullOrEmpty(data.Intro))
         update = update.Set(d => d.Intro, data.Intro);
     if (data.ShowDate != null)
         update = update.Set(d => d.ShowDate, data.ShowDate);
     if (data.CloseDate != null)
         update = update.Set(d => d.CloseDate, data.CloseDate);
     if (data.Region != 0)
         update = update.Set(d => d.Region, data.Region);
     if (!string.IsNullOrEmpty(data.Nation))
         update = update.Set(d => d.Nation, data.Nation);
     if (data.CurrentQuater != 0)
         update = update.Set(d => d.CurrentQuater, data.CurrentQuater);
     if (data.CurrentSet != 0)
         update = update.Set(d => d.CurrentSet, data.CurrentSet);
     if (data.Writer.Length > 0)
         update = update.Set(d => d.Writer, data.Writer);
     if (data.Director.Length > 0)
         update = update.Set(d => d.Director, data.Director);
     if (data.Actor.Length > 0)
         update = update.Set(d => d.Actor, data.Actor);
     if (data.HasHD)
         update = update.Set(d => d.HasHD, true);
     if (data.Comments.Count > 0)
         update = update.Set(d => d.Comments, data.Comments);
     return update;
 }
示例#12
0
        public void Execute(BsonDocument doc)
        {
            var occurance = new BsonDocument(doc.GetElement("time"),
                                             doc.GetElement("details"));
            doc.Remove("time");
            doc.Remove("details");

            var query = Query.And(Query.EQ("token", doc["token"]),
                                  Query.EQ("hash", doc["hash"]));

            UpdateBuilder ub = new UpdateBuilder();
            ub.Push("occurances", occurance);
            ub.Set("token", doc["token"]);
            ub.Set("hash", doc["hash"]);
            ub.Set("level", doc["level"]);
            ub.Set("common", doc["common"]);
            ub.Set("lastTime", occurance["time"]);

            Events.Update(query, ub, UpdateFlags.Upsert);
        }
        public UserFavoriteInfo ResetUserFavorite(string appName, UserFavoriteInfo userFavoriteInfo)
        {
            var dataBase = _serverWrapper.ServerConnection.GetDatabase(appName);
            var collection = dataBase.GetCollection<UserFavoriteInfo>(USER_FAVORITES_COLLECTION_NAME);

            collection.EnsureIndex(new IndexKeysBuilder().Ascending("user_id", "to_user_id"), IndexOptions.SetUnique(true));

            var selectQuery = Query.And(Query.EQ("user_id", userFavoriteInfo.UserId),
                                        Query.EQ("to_user_id", userFavoriteInfo.ToUserId));

            var result = collection.FindOne(selectQuery);
            var updateQuery = new UpdateBuilder();

            updateQuery.Set("date_modified", userFavoriteInfo.DateModified);
            updateQuery.Set("is_active", userFavoriteInfo.IsActive);

            collection.Update(selectQuery, updateQuery);

            return userFavoriteInfo;
        }
示例#14
0
 public void UpdateImgStatus(ObjectId id, bool? isDelete, bool? isConfirm, bool? isPublic)
 {
     var query = Query<Image>.EQ(o => o.ID, id);
     var update = new UpdateBuilder<Image>();
     if (isDelete != null)
         update = update.Set(o => o.IsDelete, isDelete);
     if (isConfirm != null)
         update = update.Set(o => o.IsConfirm, isConfirm);
     if (isPublic != null)
         update = update.Set(o => o.IsPublic, isPublic);
     imgConn.Update(query, update);
 }
示例#15
0
        public FacebookAppInfo UpsertFacebookApp(BsonDocument facebookAppInfo)
        {
            var dataBase = _serverWrapper.ServerConnection.GetDatabase("facebook_applications");
            var collection = dataBase.GetCollection<FacebookAppInfo>(APPS_COLLECTION_NAME);

            collection.EnsureIndex(new IndexKeysBuilder().Ascending("app_id"), IndexOptions.SetUnique(true));

            var appId = long.Parse((string)facebookAppInfo["id"]);
            var selectQuery = Query.EQ("app_id", appId);

            var appInfo = collection.Find(selectQuery)
                .SetFields("app_id", "app_secret_key", "app_access_token", "name", "namespace", "link", "logo_url")
                .SingleOrDefault();

            if (appInfo != null)
            {
                var updateBuilder = new UpdateBuilder();

                foreach (var val in facebookAppInfo)
                {
                    if (val.Name == "id")
                        updateBuilder.Set("app_id", long.Parse((string)val.Value));
                    else
                        updateBuilder.Set(val.Name, val.Value);
                }

                updateBuilder.Set("date_modified", DateTime.Now);

                collection.Update(Query.EQ("app_id", appId), updateBuilder);

                return appInfo;
            }

            facebookAppInfo["app_id"] = long.Parse((string)facebookAppInfo["id"]);
            facebookAppInfo["date_modified"] = DateTime.Now;
            facebookAppInfo["date_created"] = DateTime.Now;

            facebookAppInfo.Remove("id");

            collection.Insert(facebookAppInfo);

            appInfo = GetAppInfo(appId);

            return appInfo;
        }
 public void SaveCounterName(int parentCategoryId, CounterNameInfo nameInfo)
 {
     MongoCollection<BsonDocument> items = Database.GetCollection("countersInfo");
     IMongoQuery q = Query.EQ("id", parentCategoryId);
     UpdateBuilder u = new UpdateBuilder();
     u.AddToSet("counters", new BsonDocument {{"name", nameInfo.Name}, {"id", nameInfo.Id}});
     u.Set("c" + nameInfo.Id, new BsonDocument
                                  {
                                      {"sources", new BsonArray()},
                                      {"instances", new BsonArray()},
                                      {"extDatas", new BsonArray()}
                                  });
     items.Update(q, u, UpdateFlags.Upsert, SafeMode.True);
 }
        public MessageInfo InsertMessage(string appName, string sessionId, ObjectId from, ObjectId to, string header, string message)
        {
            var dataBase = _serverWrapper.ServerConnection.GetDatabase(appName);
            var collection = dataBase.GetCollection<MessageSessionInfo>(MESSAGE_SESSIONS_COLLECTION_NAME);
            MessageSessionInfo session = EnsureSession(appName, sessionId, from, to, collection);
            bool isUser1From = session.User1 == from;
            MessageInfo messageInfo = new MessageInfo()
            {
                Id = Guid.NewGuid().ToString("N"),
                Body = message,
                From = from,
                Header = header,
                DateCreated = DateTime.Now
            };
            bool isDeletedSession = session.IsDeletedUser1 || session.IsDeletedUser2;
            UpdateBuilder updater = new UpdateBuilder();
            updater = updater.PushWrapped("messages", messageInfo)
                .Set("last_updated", DateTime.Now)
                .Inc(isUser1From ? "user2_count" : "user1_count", 1);

            //Make sure that if the session is deleted by this user, it'll automatically be active again.
            if (isDeletedSession)
            {
                updater.Set("user1_is_deleted", false).Set("user2_is_deleted", false);
            }
            collection.Update(Query.EQ("session_id", sessionId), updater);
            return messageInfo;
        }
示例#18
0
        public FacebookUserInfo UpsertFacebookUser(string appName, BsonDocument facebookUserInfo)
        {
            var dataBase = _serverWrapper.ServerConnection.GetDatabase(appName);
            var collection = dataBase.GetCollection<FacebookUserInfo>(FACEBOOK_USERS_COLLECTION_NAME);

            collection.EnsureIndex(new IndexKeysBuilder().Ascending("facebook_id"), IndexOptions.SetUnique(true));

            var facebookId = long.Parse((string)facebookUserInfo["id"]);
            var selectQuery = Query.EQ("facebook_id", facebookId);
            var userInfo = collection.Find(selectQuery)
                .SetFields("facebook_id", "name", "is_active", "is_banned", "is_posted_on_wall", "access_token", "gender")
                .SingleOrDefault();

            if (userInfo != null)
            {
                var updateBuilder = new UpdateBuilder();

                foreach (var val in facebookUserInfo)
                {
                    if (val.Name == "birthday")
                        updateBuilder.Set(val.Name, DateTime.ParseExact((string)val.Value, "MM/dd/yyyy", CultureInfo.InvariantCulture));
                    else if (val.Name == "updated_time")
                        updateBuilder.Set(val.Name, DateTime.Parse((string)val.Value));
                    else if (val.Name == "facebook_id")
                        updateBuilder.Set(val.Name, long.Parse((string)val.Value));
                    else
                        updateBuilder.Set(val.Name, val.Value);
                }

                updateBuilder.Set("date_modified", DateTime.Now);

                if (!userInfo.IsActive)
                {
                    updateBuilder.Set("is_active", true);
                    userInfo.IsReturning = true;
                }

                collection.Update(Query.EQ("facebook_id", facebookId), updateBuilder);

                return userInfo;
            }

            facebookUserInfo["birthday"] = DateTime.ParseExact((string)facebookUserInfo["birthday"], "MM/dd/yyyy", CultureInfo.InvariantCulture);
            facebookUserInfo["updated_time"] = DateTime.Parse((string)facebookUserInfo["updated_time"]);
            facebookUserInfo["date_modified"] = DateTime.Now;
            facebookUserInfo["date_created"] = DateTime.Now;
            facebookUserInfo["facebook_id"] = long.Parse((string)facebookUserInfo["id"]);
            facebookUserInfo["is_active"] = true;
            facebookUserInfo["is_banned"] = false;
            facebookUserInfo["is_posted_on_wall"] = false;
            facebookUserInfo.Remove("id");

            collection.Insert(facebookUserInfo);

            userInfo = GetUserInfo(appName, facebookId);
            userInfo.IsNew = true;

            return userInfo;
        }
 public void SaveCounterExtData(int parentCategoryId, int parentCounterId,
                                CounterExtDataInfo counterExtDataInfo)
 {
     MongoCollection<BsonDocument> items = Database.GetCollection("countersInfo");
     IMongoQuery q = Query.And(Query.EQ("id", parentCategoryId));
     UpdateBuilder u = new UpdateBuilder();
     if (counterExtDataInfo != null)
         u.AddToSet("c" + parentCounterId + ".extDatas",
                    new BsonDocument {{"name", counterExtDataInfo.Name}, {"id", counterExtDataInfo.Id}});
     items.Update(q, u, UpdateFlags.Upsert, SafeMode.True);
 }
        /// <summary>
        ///     Конвертирует страницу в команду обновления
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public IMongoUpdate UpdateFromPage(WikiPage page) {
            var updateBuilder = new UpdateBuilder();

            if (!string.IsNullOrEmpty(page.Text)) {
                updateBuilder.Set("text", page.Text);
            }

            if (!string.IsNullOrEmpty(page.Title)) {
                updateBuilder.Set("title", page.Title);
            }

            updateBuilder.Set("ver", (page.LastWriteTime != DateTime.MinValue) ? (page.LastWriteTime) : (DateTime.Now));
            updateBuilder.Set("editor", Application.Current.Principal.CurrentUser.Identity.Name);

            foreach (var propety in page.Propeties) {
                updateBuilder.Set(propety.Key, propety.Value ?? "");
            }

            return updateBuilder;
        }
示例#21
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="key"></param>
 /// <param name="value"></param>
 /// <returns></returns>
 public static IMongoUpdate GetMongoUpdate(string key, object value)
 {
     UpdateBuilder result = new UpdateBuilder();
     result.Set(key, BsonValue.Create(value));
     return result;
 }
示例#22
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="updates"></param>
 /// <returns></returns>
 public static IMongoUpdate GetMongoUpdate(Dictionary<string, object> updates)
 {
     UpdateBuilder result = new UpdateBuilder();
     foreach (KeyValuePair<string, object> kv in updates)
     {
         IMongoUpdate u = GetMongoUpdate(kv.Key, kv.Value);
         result.Combine(u);
     }
     return result;
 }
        /// <summary>
        /// Initializes the Organisation URIs that don't already exist.
        /// </summary>
        /// <param name="uris">The URIs to add to the organisation collection.</param>
        private void InitUris(Dictionary<SystemUriType, string> uris)
        {
            if (uris.Count == 0)
            {
                return;
            }

            this.installLogger.Log(Messages.DB_InitUris);
            MongoCollection<BsonDocument> collection = this.Database.GetCollection(iApplyDb.SystemSettings._COLLECTION_NAME);

            if (collection.Count() == 0)
            {
                throw new NullReferenceException();
            }

            UpdateBuilder builder = new UpdateBuilder();
            foreach (KeyValuePair<SystemUriType, string> uri in uris)
            {
                string name = string.Format("{0}.{1}", iApplyDb.SystemSettings.URIS, uri.Key);
                builder.Set(name, new BsonString(uri.Value));
            }

            FindAndModifyArgs args = new FindAndModifyArgs
                                     {
                                         Update = builder
                                     };

            collection.FindAndModify(args);
            this.installLogger.LogSuccess(Messages.MAIN_StepComplete);
        }
示例#24
0
    public override bool update(Object objClass, string paramName, string paramVal, string tableName)
    {
        string ret = String.Empty;
        MongoCollection<BsonDocument> objCollection = this.getobjCollection(tableName);

        BsonDocument doc = new BsonDocument();
        var query = Query.EQ(paramName, ObjectId.Parse(paramVal));
        var sortBy = SortBy.Descending(paramName);
        PropertyInfo[] _objProperties = objClass.GetType().GetProperties();
        string _type = String.Empty;
        string _name = String.Empty;
        string _val = String.Empty;
        UpdateBuilder update = new UpdateBuilder();

        foreach (PropertyInfo property in _objProperties)
        {
            if (property.CanRead)
            {
                _name = property.Name;
                _val = (string)property.GetValue(objClass, null);
                if (_val != null)
                {
                    if (_name == "Id" || _name == "UserId")
                    {
                        update.Set(_name, ObjectId.Parse(_val));
                    }
                    else
                    {
                        update.Set(_name, _val);
                    }
                }
            }
        }

        var result = objCollection.FindAndModify(query, sortBy, update, true);
        return true;
    }
示例#25
0
        public void UpdateProxy(ObjectId proxyId, bool isActive, double responseTime, int responseCode, string responseDescription)
        {
            var dataBase = _serverWrapper.GetServer(PROXIES_DB_NAME).GetDatabase(PROXIES_DB_NAME);
            var collection = dataBase.GetCollection<BsonDocument>(PROXIES_COLLECTION_NAME);

            var updateBuilder = new UpdateBuilder();

            updateBuilder.Set("response_time", responseTime);
            updateBuilder.Set("response_code", responseCode);
            updateBuilder.Set("response_description", responseDescription);
            updateBuilder.Set("date_modified", DateTime.Now);
            updateBuilder.Set("is_active", isActive);

            collection.Update(Query.EQ("_id", proxyId), updateBuilder);
        }
示例#26
0
        public BsonDocument UpsertFacebookUser(BsonDocument facebookUserInfo, params string[] fields)
        {
            var dataBase = _serverWrapper.GetServer(EXTENTIONS_DB_NAME).GetDatabase(EXTENTIONS_DB_NAME);
            var collection = dataBase.GetCollection<BsonDocument>(USERS_COLLECTION_NAME);

            var facebookId = long.Parse((string)facebookUserInfo["id"]);
            var selectQuery = Query.EQ("facebook_id", facebookId);
            var userInfo = collection.Find(selectQuery)
                .SetFields(fields)
                .SingleOrDefault();

            if (userInfo != null)
            {
                var updateBuilder = new UpdateBuilder();

                foreach (var val in facebookUserInfo)
                {
                    if (val.Name == "birthday")
                        updateBuilder.Set(val.Name, DateTime.ParseExact((string)val.Value, "MM/dd/yyyy", CultureInfo.InvariantCulture));
                    else if (val.Name == "updated_time")
                        updateBuilder.Set(val.Name, DateTime.Parse((string)val.Value));
                    else if (val.Name == "id")
                        updateBuilder.Set("facebook_id", long.Parse((string)val.Value));
                    else
                        updateBuilder.Set(val.Name, val.Value);
                }

                updateBuilder.Set("date_modified", DateTime.Now);
                updateBuilder.Set("is_active", true);

                collection.Update(Query.EQ("facebook_id", facebookId), updateBuilder);

                return userInfo;
            }

            facebookUserInfo["birthday"] = DateTime.ParseExact((string)facebookUserInfo["birthday"], "MM/dd/yyyy", CultureInfo.InvariantCulture);
            facebookUserInfo["updated_time"] = DateTime.Parse((string)facebookUserInfo["updated_time"]);
            facebookUserInfo["date_modified"] = DateTime.Now;
            facebookUserInfo["date_created"] = DateTime.Now;
            facebookUserInfo["is_active"] = true;
            facebookUserInfo["is_banned"] = false;
            facebookUserInfo["facebook_id"] = long.Parse((string)facebookUserInfo["id"]);
            facebookUserInfo.Remove("id");

            collection.Insert(facebookUserInfo);

            return facebookUserInfo;
        }
        public void Save (AggregatedValue val)
        {
            MongoCollection<BsonDocument> items = MongoDb.GetCollection("countersData");
            UpdateBuilder updateBuilder = new UpdateBuilder();
            if (val.Count.HasValue)
                updateBuilder.Inc("data.Count", val.Count.Value);
            if (val.Sum.HasValue)
                updateBuilder.Inc("data.Sum", val.Sum.Value);
            if (val.Min.HasValue)
                updateBuilder.Push("data.Min", val.Min.Value);
            if (val.Max.HasValue)
                updateBuilder.Push("data.Max", val.Max.Value);
            if (val.Avg.HasValue)
                updateBuilder.Push("data.Avg", val.Avg.Value);
            if (val.Percentiles!=null || val.DistributionGroups!=null)
                updateBuilder.PushAll("data.Raw", val.RawValues.Select(v =>new BsonDouble(v)));

            IMongoQuery q = Query.And(Query.EQ("date", val.Date), Query.EQ("props.pCnt", val.Props.Count));
            foreach (var prop in val.Props)
            {
                q = Query.And(q, Query.EQ("props."+prop.Key, prop.Value));
            }
            items.Update(q, updateBuilder,UpdateFlags.Upsert,SafeMode.True);
        }