Esempio n. 1
0
    static void Main(string[] args)
    {
        // TO DO: Add your code here
        MongoClient   client   = new MongoClient("mongodb://localhost:27017");
        MongoServer   server   = client.GetServer();
        MongoDatabase database = server.GetDatabase("FinanceLast");
        MongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("RandomTradeRecords");

        foreach (BsonDocument aRecord in collection.FindAll())
        {
            int traded    = 0;
            int oriInside = 0;
            if (aRecord["HoldingPeriod"] == 1)
            {
                oriInside = 0;
            }
            else if (aRecord["HoldingPeriod"] > 1)
            {
                oriInside = 1;
            }
            traded = Math.Abs((int)aRecord["Inside"] - oriInside);
            QueryDocument  query  = new QueryDocument(new BsonElement("_id", aRecord["_id"]));
            UpdateDocument update = new UpdateDocument();
            QueryDocument  query2 = new QueryDocument();
            query2.Add(new BsonElement("OriInside", oriInside));
            query2.Add(new BsonElement("Traded", traded));
            update.Add(new BsonElement("$set", query2));
            collection.Update(query, update);
        }
    }
Esempio n. 2
0
 /// <summary>
 /// 更新指令
 /// </summary>
 /// <param name="command"></param>
 /// <returns></returns>
 public static string Update(Command command)
 {
     try
     {
         MongoDBHelper <Command> mongo = new MongoDBHelper <Command>();
         var query = new QueryDocument();
         query.Add("_id", command._id);
         var update = new UpdateDocument();
         update.Add("CommandState", command.CommandState);
         update.Add("AnswerDate", command.AnswerDate);
         update.Add("AnswerData", command.AnswerData);
         update.Add("ControlCode", command.ControlCode);
         update.Add("DataCommand", command.DataCommand);
         update.Add("DataLength", command.DataLength);
         update.Add("TaskID", command.TaskID);
         update.Add("Identification", command.Identification);
         update.Add("Order", command.Order);
         mongo.Update(CollectionNameDefine.CommandCollectionName, query, update);
     }
     catch (Exception e)
     {
         return(e.Message);
     }
     return("");
 }
Esempio n. 3
0
    private void SetCurrentAnimal(DataPlayer data)
    {
        var animalInUserCollection = _database.GetCollection <BsonDocument>("ANIMAL_IN_USER");

        // Set false to old current animal
        var where14 = new QueryDocument {
            { "current", true }
        };
        var set14 = new UpdateDocument {
            { "$set", new BsonDocument("current", false) }
        };

        animalInUserCollection.Update(where14, set14);

        // Set true to new animal
        Animal an            = (Animal)data.CurrentAnimal;
        var    currentAnimal = _database.GetCollection <BsonDocument>("ANIMALS").
                               Find(new QueryDocument("name", an.ToString()));

        ObjectId id = new ObjectId();

        foreach (var document in currentAnimal)
        {
            id = document["_id"].AsObjectId;
        }

        var where5 = new QueryDocument {
            { "animal_id", id }
        };
        var set5 = new UpdateDocument {
            { "$set", new BsonDocument("current", true) }
        };

        animalInUserCollection.Update(where5, set5);
    }
Esempio n. 4
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 User Login(UserLoginModel model)
        {
            User user = this.GetUserByUsername(model.Username);

            if (user == null)
            {
                throw new ArgumentException("Invalid username.");
            }

            if (user.AuthCode != model.AuthCode)
            {
                throw new ArgumentException("Invalid password.");
            }

            user.SessionKey = this.GenerateSessionKey(model.Username);

            var query = new QueryDocument {
                { "Username", user.Username },
            };
            var update = new UpdateDocument {
                { "$set", new BsonDocument("SessionKey", user.SessionKey) }
            };

            this.usersCollection.Update(query, update);

            return(user);
        }
        public void Transform_UpdateDocument_To_Delta_Containing_ComplexObject()
        {
            // Arrange
            var dimensions = new Dimensions()
            {
                Height = "80mm", Width = "10mm"
            };
            var updateDocument = new UpdateDocument
            {
                Data = new SingleResource()
                {
                    Id         = "123",
                    Type       = "product",
                    Attributes = new Dictionary <string, object>()
                    {
                        { "name", "Widget" },
                        { "dimensions", dimensions }
                    }
                }
            };

            var config      = TestModelConfigurationBuilder.BuilderForEverything.Build();
            var context     = new Context(new Uri("http://fakehost:1234", UriKind.Absolute));
            var transformer = new JsonApiTransformerBuilder().With(config).Build();

            // Act
            var resultDelta = transformer.TransformBack(updateDocument, typeof(Product), context);

            // Assert
            Assert.True(resultDelta.ObjectPropertyValues.ContainsKey("name"));
            Assert.True(resultDelta.ObjectPropertyValues.ContainsKey("dimensions"));
            Assert.Equal(dimensions, resultDelta.ObjectPropertyValues["dimensions"]);
        }
Esempio n. 7
0
        public UpdateDocument GetStateChanged(object entity, EntityState original, EntityState current)
        {
            var updateDoc  = new UpdateDocument();
            var changedSet = new HashSet <PropertyInfo>();

            foreach (var mapper in this.m_allProperties.Values.Where(p => !p.IsReadOnly))
            {
                if (mapper.IsStateChanged(original, current))
                {
                    changedSet.Add(mapper.Descriptor.Property);
                    mapper.PutStateUpdate(updateDoc, original, current);
                }
            }

            foreach (var mapper in this.m_allProperties.Values.Where(p => p.IsReadOnly))
            {
                if (mapper.Descriptor.ChangeWithProperties.Any(p => changedSet.Contains(p)))
                {
                    mapper.PutValueUpdate(updateDoc, entity);
                }
            }

            if (this.m_version != null && updateDoc.ElementCount > 0)
            {
                this.m_version.PutNextVersion(updateDoc, entity);
            }

            return(updateDoc);
        }
        public object Update(object entity)
        {
            bool result = false;
            var  mlist  = entity as List <MedicationData>;

            try
            {
                using (MedicationMongoContext ctx = new MedicationMongoContext(ContractDBName))
                {
                    var bulk = ctx.Medications.Collection.InitializeUnorderedBulkOperation();

                    foreach (MEMedication fooDoc in ctx.Medications)
                    {
                        var update = new UpdateDocument {
                            { fooDoc.ToBsonDocument() }
                        };
                        update.Set("fmid", ObjectId.Parse(GetMedFamilyId(mlist, fooDoc.Id.ToString())));
                        bulk.Find(Query.EQ("_id", fooDoc.Id)).Upsert().UpdateOne(update);
                    }
                    BulkWriteResult bwr = bulk.Execute();

                    result = true;
                }
                return(result as object);
            }
            catch (Exception) { throw; }
        }
 private void ChangePropertiesOfBabyProfile(
     BabyEventModel babyEventModel, BabyEvent selectedBabyEvent, MongoCollection babyEvents)
 {
     if (babyEventModel.Title != null)
     {
         var query = new QueryDocument {
             { "_id", selectedBabyEvent.Id }
         };
         var update = new UpdateDocument {
             { "$set", new BsonDocument("Title", babyEventModel.Title) }
         };
         babyEvents.Update(query, update);
     }
     if (babyEventModel.Description != null)
     {
         var query = new QueryDocument {
             { "_id", selectedBabyEvent.Id }
         };
         var update = new UpdateDocument {
             { "$set", new BsonDocument("Description", babyEventModel.Description) }
         };
         babyEvents.Update(query, update);
     }
     if (babyEventModel.Date != null)
     {
         var query = new QueryDocument {
             { "_id", selectedBabyEvent.Id }
         };
         var update = new UpdateDocument {
             { "$set", new BsonDocument("Date", babyEventModel.Date) }
         };
         babyEvents.Update(query, update);
     }
 }
        static void setindex2()
        {
            //var queryTask = new QueryDocument { { "SearchSource", 1 }, { "IsRemoved", false } };
            //MongoCollection<IW2S_BaiduCommend> col = new MongoDBClass<IW2S_BaiduCommend>().GetMongoDB().GetCollection<IW2S_BaiduCommend>("IW2S_BaiduCommend");
            //var categoryList = col.Find(queryTask);
            //var clist = categoryList.ToList();

            //foreach (var item in clist)
            //{
            //    var update = new UpdateDocument { { "$set", new QueryDocument { { "JisuanStatus", 0 } } } };
            //    var result = MongoDBHelper.Instance.Get_IW2S_BaiduCommend().UpdateOne(new QueryDocument { { "_id", item._id } }, update);
            //    Console.WriteLine("完成关键词状态标注:" + item._id + "/" + item.CommendKeyword);
            //}


            var update = new UpdateDocument {
                { "$set", new QueryDocument {
                      { "AlternateFields", "0" }
                  } }
            };
            var result = MongoDBHelper.Instance.GetIW2S_level1links().UpdateMany(new QueryDocument {
                { "AppType", 0 }
            }, update);

            Console.WriteLine("完成修改");


            Console.WriteLine("完成!");
        }
Esempio n. 11
0
        public void Update(Dictionary <string, object> queryObject, Dictionary <string, object> updateObject)
        {
            var query  = new QueryDocument(queryObject);
            var update = new UpdateDocument(updateObject);

            Collection.Update(query, update);
        }
Esempio n. 12
0
        private void button2_Click(object sender, EventArgs e)
        {
            {
                MongoClient              client = new MongoClient("mongodb://localhost");
                MongoServer              server = client.GetServer();
                MongoDatabase            db     = server.GetDatabase("dms");
                MongoCollection <Class1> stud   = db.GetCollection <Class1>("u_signup");
                foreach (Class1 i in stud.Find(Query.EQ("fname", textBox1.Text.Trim())))
                {
                    IMongoUpdate update1 = new UpdateDocument();
                    IMongoUpdate update2 = new UpdateDocument();
                    IMongoUpdate update3 = new UpdateDocument();
                    IMongoUpdate update4 = new UpdateDocument();
                    IMongoUpdate update5 = new UpdateDocument();
                    if (textBox1.Text != "")
                    {
                        update1 = MongoDB.Driver.Builders.Update.Set("fname", textBox1.Text);
                        update2 = MongoDB.Driver.Builders.Update.Set("lname", textBox2.Text);
                        update3 = MongoDB.Driver.Builders.Update.Set("uname", textBox3.Text);
                        update4 = MongoDB.Driver.Builders.Update.Set("emaila", textBox6.Text);
                        update5 = MongoDB.Driver.Builders.Update.Set("phone", textBox7.Text);
                    }
                    stud.Update(Query.EQ("fname", textBox1.Text), update2);
                    stud.Update(Query.EQ("fname", textBox1.Text), update3);
                    stud.Update(Query.EQ("fname", textBox1.Text), update4);
                    stud.Update(Query.EQ("fname", textBox1.Text), update5);
                    stud.Update(Query.EQ("fname", textBox1.Text), update1);

                    MessageBox.Show("Updated");
                    //  refresh();
                    break;
                }
            }
        }
Esempio n. 13
0
        public static void SetStatus(BsonDocument service, bool restart)
        {
            try
            {
                var server = MongoServer.Create(ConfigurationManager.ConnectionStrings["mongodb"].ConnectionString);
                server.Connect();

                var database   = server.GetDatabase("config");
                var collection = database.GetCollection("services");
                var filter     = new QueryDocument {
                    { "_id", service["_id"].AsObjectId }
                };
                var update = new UpdateDocument();

                foreach (var key in service)
                {
                    update[key.Name] = key.Value;
                }

                update["restart"] = restart;
                collection.Update(filter, update);

                server.Disconnect();
            }
            catch (Exception err)
            {
                Console.WriteLine("** error updating restart status: " + err.Message);
            }
        }
Esempio n. 14
0
        public void Update(TrackingStatus status, string trackingId, string message = null)
        {
            if (String.IsNullOrEmpty(trackingId))
            {
                Log.Warn("Unable to track message: empty trackingID");
                return;
            }

            try
            {
                var updateFields = new BsonDocument()
                                   .Add("Updated", DateTime.UtcNow)
                                   .Add("Status", status);
                if (message != null)
                {
                    updateFields.Add("Description", message);
                }
                var update = new UpdateDocument("$set", updateFields);
                _trackCollection.Update(Query <TrackingRecord> .EQ(e => e.Id, trackingId), update,
                                        WriteConcern.Unacknowledged);
            }
            catch (Exception ex)
            {
                Log.Error("Tracking failed", ex);
            }
        }
        public void ShouldWriteDataModelToMongoLab()
        {
            // Arrange
            var collection = _providerUnderTest.Database.GetCollection <AboutDataModel>("about");
            var original   = collection.FindAll().FirstOrDefault();

            if (original != null)
            {
                var clone = original.Clone();
                clone.Title = "bodgy";

                // Act
                var result = _providerUnderTest.Update <AboutDataModel>("about", clone);

                var altered = collection.FindAll().FirstOrDefault();
                if (altered != null)
                {
                    // Assert
                    Assert.That(result, Is.Not.Null);
                    Assert.That(result.Title, Is.EqualTo("bodgy"));
                }

                // Reset
                var updQuery = new QueryDocument {
                    { "_id", original._id }
                };
                var updDoc = new UpdateDocument {
                    { "$set", new BsonDocument("Title", original.Title) }
                };
                collection.Update(updQuery, updDoc);
            }
        }
Esempio n. 16
0
 /// <summary>
 ///     根据ID修改分类
 /// </summary>
 /// <returns></returns>
 public int ModifyByID(int id, tbExampaperSort sort)
 {
     try
     {
         MongoCollection <tbExampaperSort> coll =
             BaseDB.CreateInstance().GetCollection <tbExampaperSort>("tbExampaperSort");
         var b = new UpdateDocument
         {
             { "Description", sort.Description },
             { "Title", sort.Title },
             { "FatherID", sort.FatherID },
             { "Status", sort.Status }
         };
         coll.Update(Query.EQ("_id", id), b);
         return(id);
     }
     catch
     {
         return(0);
     }
     finally
     {
         BaseDB.MongoService.Disconnect();
     }
 }
Esempio n. 17
0
        public static bool Modify(LinePackagePrice linePackagePrice)
        {
            Mongo mongo = Mongo.GetInstance();
            //最底层的方法(获取指定名称的文档集)
            var coll  = mongo.GetCollection <LinePackagePrice>(MongoDbManager.MongoCollectionName.Coll_LinePackagePrice, MongoDbManager.DbName.Db_TCZZYPrice);
            var query = new QueryDocument
            {
                { "l", linePackagePrice.LineId },
                { "lp", linePackagePrice.LinePackageId },
                { "p.d", new DateTime(2016, 3, 9) }
            };
            var updateElement = new BsonDocument
            {
                { "p.$.aa", "123" },
                { "p.$.ac", "123" },
                { "p.$.ad", "123" }
            };
            var update = new UpdateDocument
            {
                { "$set", updateElement }
            };
            var result = coll.Update(query, update);

            return(result.Ok);
        }
Esempio n. 18
0
        public void Update()
        {
            //创建数据库链接
            MongoServerSettings settings = new MongoServerSettings();
            //settings.Server = new MongoServerAddress("localhost");

            //创建数据库链接
            MongoServer server = new MongoServer(settings);
            //获得数据库test
            MongoDatabase db = server.GetDatabase(dbName);
            //获取Users集合
            MongoCollection col = db.GetCollection("Users");
            //定义获取“Name”值为“test”的查询条件
            var query = new QueryDocument {
                { "Name", "FDB" }
            };
            //定义更新文档
            var update = new UpdateDocument {
                { "$set", new QueryDocument {
                      { "Age", 30 }
                  } }
            };

            //执行更新操作
            col.Update(query, update);
        }
        public void UpdateWorkItemLink(
            string sourceWorkItemId,
            string targetWorkItemId,
            int linkTypeId,
            string comment,
            bool isLocked)
        {
            CreateEmptyUpdateDoc();

            XmlElement xwi = UpdateDocument.CreateElement(UpdateWorkItemLinkElem);

            UpdateDocument.AppendChild(xwi);

            xwi.SetAttribute(WorkItemLinkSourceID, sourceWorkItemId);
            xwi.SetAttribute(WorkItemLinkTargetID, targetWorkItemId);
            xwi.SetAttribute(WorkItemLinkType, XmlConvert.ToString(linkTypeId));

            var autoMergeOption = XmlConvert.ToString(false);
            var lockOption      = XmlConvert.ToString(isLocked);

            xwi.SetAttribute(WorkItemLinkAutoMerge, autoMergeOption);

            xwi.SetAttribute(WorkItemLinkComment, comment);
            xwi.SetAttribute(WorkItemLinkLock, lockOption);
        }
Esempio n. 20
0
        public void Transform_UpdateDocument_To_Delta_TwoFields()
        {
            // Arrange
            var updateDocument = new UpdateDocument
            {
                Data = new SingleResource()
                {
                    Id         = "123",
                    Type       = "post",
                    Attributes = new Dictionary <string, object>()
                    {
                        { "title", "someTitle" },
                        { "authorId", "1234" },
                    }
                }
            };

            var config      = TestModelConfigurationBuilder.BuilderForEverything.Build();
            var context     = new Context(new Uri("http://fakehost:1234", UriKind.Absolute));
            var transformer = new JsonApiTransformerBuilder().With(config).Build();

            // Act
            var resultDelta = transformer.TransformBack(updateDocument, typeof(Post), context);

            // Assert
            Assert.True(resultDelta.ObjectPropertyValues.ContainsKey("Title"));
            Assert.True(resultDelta.ObjectPropertyValues.ContainsKey("AuthorId"));
        }
Esempio n. 21
0
        public void Transform_properties_with_reserverd_keyword()
        {
            var updateDocument = new UpdateDocument()
            {
                Data = new Dictionary <string, object>()
                {
                    { "posts", JObject.Parse("{ \"_id\":123, \"title\": \"someTitle\" }") }
                }
            };

            var configuration = (new ConfigurationBuilder())
                                .Resource <Post>()
                                .WithSimpleProperty(x => x.AuthorId)
                                .WithSimpleProperty(x => x.Id)
                                .WithSimpleProperty(x => x.Title);
            var context = new Context {
                Configuration = configuration.ConfigurationBuilder.Build()
            };
            var sut = new JsonApiTransformer();

            // Act
            var resultDelta = sut.TransformBack(updateDocument, typeof(Post), context);

            // Assert
            resultDelta.ObjectPropertyValues.ContainsKey("id").ShouldBeTrue();
        }
Esempio n. 22
0
        public void Transform_UpdateDocument_To_Delta_TwoFields()
        {
            // Arrange
            var updateDocument = new UpdateDocument
            {
                Data = new Dictionary <string, object>
                {
                    {
                        "posts", JObject.FromObject(new PostUpdateTwoFields()
                        {
                            Title    = "Food",
                            AuthorId = 0
                        })
                    }
                }
            };

            var configuration = (new ConfigurationBuilder())
                                .Resource <Post>()
                                .WithSimpleProperty(x => x.AuthorId)
                                .WithSimpleProperty(x => x.Title);
            var context = new Context {
                Configuration = configuration.ConfigurationBuilder.Build()
            };
            var sut = new JsonApiTransformer();


            // Act
            var resultDelta = sut.TransformBack(updateDocument, typeof(Post), context);

            // Assert
            resultDelta.ObjectPropertyValues.ContainsKey("title").ShouldBeTrue();
            resultDelta.ObjectPropertyValues.ContainsKey("authorId").ShouldBeTrue();
        }
        //edit users information
        private void btnSavePersonalInfo_Click(object sender, EventArgs e)
        {
            if (validateForm())
            {
                MongoClient            client = new MongoClient("mongodb://localhost");
                MongoServer            server = client.GetServer();
                MongoDatabase          db     = server.GetDatabase("NBA");
                MongoCollection <User> Users  = db.GetCollection <User>("Users");
                foreach (User i in Users.Find(Query.EQ("username", username)))
                {
                    IMongoUpdate update1 = new UpdateDocument();
                    IMongoUpdate update2 = new UpdateDocument();
                    IMongoUpdate update3 = new UpdateDocument();
                    IMongoUpdate update4 = new UpdateDocument();
                    IMongoUpdate update5 = new UpdateDocument();

                    update1 = MongoDB.Driver.Builders.Update.Set("name", txtname.Text.Trim());
                    update2 = MongoDB.Driver.Builders.Update.Set("security", combosecurity.Text.Trim());
                    update3 = MongoDB.Driver.Builders.Update.Set("answer", txtanswer.Text.Trim());
                    update4 = MongoDB.Driver.Builders.Update.Set("email", txtemail.Text.Trim());
                    update5 = MongoDB.Driver.Builders.Update.Set("mobileno", txtmobile.Text.Trim());

                    Users.Update(Query.EQ("username", username), update1);
                    Users.Update(Query.EQ("username", username), update2);
                    Users.Update(Query.EQ("username", username), update3);
                    Users.Update(Query.EQ("username", username), update4);
                    Users.Update(Query.EQ("username", username), update5);
                    MessageBox.Show("Information Updated");
                    break;
                }
            }
        }
        private void buttonActualizar_Click(object sender, EventArgs e)
        {
            var peliculas = db.GetCollection <Pelicula>("peliculas");
            var query     = new QueryDocument {
                { "_id", ObjectId.Parse(peliculaSeleccionada) }
            };

            var update = new UpdateDocument
            {
                { "$set", new BsonDocument
                  {
                      { "nombre", textNombre.Text },
                      { "genero", textGenero.Text },
                      { "director", textDirector.Text },
                      { "franquicia", textFranquicia.Text },
                      { "pais", textPais.Text },
                      { "ano", Int32.Parse(anoPeli.Text) },
                      { "duracion", Int32.Parse(textDuracion.Text) },
                      { "compania", companiaBox.Text },
                      { "reparto", new BsonArray(obtenerListaActores()) }
                  } }
            };

            peliculas.UpdateOne(query, update);
            cargarPeliculas();
            peliculaSeleccionada = "";
            vaciarCampos();
            buttonGuardar.Enabled    = true;
            buttonActualizar.Enabled = false;
        }
Esempio n. 25
0
        /// <summary>
        /// Updates the selectorified collection.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection">The collection.</param>
        /// <param name="updater">The updater.</param>
        /// <param name="selector">The selector.</param>
        public static void Update <T>(this DBCollection <T> collection, Expression <Func <T, T> > updater, Expression <Func <T, bool> > selector) where T : class
        {
            Dictionary <string, object> KV = new Dictionary <string, object>();

            #region //获取Update的赋值语句。

            var updateMemberExpr = (MemberInitExpression)updater.Body;
            var updateMembers    = updateMemberExpr.Bindings.Cast <MemberAssignment>();
            foreach (var item in updateMembers)
            {
                string name  = item.Member.Name;
                var    value = Expression.Lambda(item.Expression).Compile().DynamicInvoke();
                if (!string.IsNullOrEmpty(name))
                {
                    KV.Add(name, value);
                }
            }

            #endregion

            var          wrapper  = new UpdateDocument(KV);
            BsonDocument modifier = new BsonDocument();
            modifier.Add("$set", (BsonDocument)wrapper);
            var mongoQuery = GetQuery(collection, selector);
            collection.Update((BsonDocument)mongoQuery, modifier, new BsonDocument());
        }
Esempio n. 26
0
        public bool Update(string collectionname, Dictionary <string, object> queryjson, Dictionary <string, object> updatejson)
        {
            QueryDocument  qd = new QueryDocument(queryjson);
            UpdateDocument up = new UpdateDocument(updatejson);

            return(Update(collectionname, qd, up, UpdateFlags.Upsert));
        }
Esempio n. 27
0
 /// <summary>
 ///     修改试题库
 /// </summary>
 /// <param name="SortID"></param>
 /// <param name="qSort"></param>
 /// <returns></returns>
 public int ModifyByID(int SortID, tbQuestionSort qSort)
 {
     try
     {
         MongoCollection <tbQuestionSort> coll =
             BaseDB.CreateInstance().GetCollection <tbQuestionSort>("tbQuestionSort");
         var update = new UpdateDocument
         {
             { "FatherID", qSort.FatherID },
             { "Title", qSort.Title },
             { "Description", qSort.Description },
             { "Status", qSort.Status }
         };
         coll.Update(Query.EQ("_id", SortID), update);
         return(SortID);
     }
     catch
     {
         return(0);
     }
     finally
     {
         BaseDB.MongoService.Disconnect();
     }
 }
        public void saveBaiduKeyword(IW2S_BaiduCommend baiduCommend)
        {
            if (baiduCommend == null)
            {
                return;
            }


            var col     = MongoDBHelper.Instance.GetIW2S_BaiduCommends();
            var builder = Builders <IW2S_BaiduCommend> .Filter;

            var exists_obj = col.Find(builder.Eq(x => x._id, baiduCommend._id)).Project(x => new IDIntDto {
                Id = x._id, Times = x.Times
            }).FirstOrDefault();

            if (exists_obj == null || exists_obj.Id == new MongoDB.Bson.ObjectId("000000000000000000000000"))
            {
                col.InsertOne(baiduCommend);
                log("SUCCESS saving keywords {0} for {1}".FormatStr(baiduCommend.CommendKeyword, baiduCommend.Keyword));
            }
            else
            {
                var update = new UpdateDocument {
                    { "$set", new QueryDocument {
                          { "Times", exists_obj.Times + 1 }
                      } }
                };

                var result = MongoDBHelper.Instance.GetIW2S_BaiduCommends().UpdateOne(new QueryDocument {
                    { "_id", baiduCommend._id }
                }, update);
            }
        }
Esempio n. 29
0
        /// <summary>
        /// 根据实体创建UpdateDefinition
        /// </summary>
        /// <param name="updateEntity"></param>
        /// <param name="isUpsert"></param>
        /// <returns></returns>
        protected UpdateDefinition <TEntity> CreateUpdateDefinition(TEntity updateEntity, bool isUpsert = false)
        {
            long         id    = 0;
            BsonDocument bsDoc = updateEntity.ToBsonDocument();

            bsDoc.Remove(Util.PRIMARY_KEY_NAME);

            UpdateDefinition <TEntity> update = new UpdateDocument("$set", bsDoc);// string.Concat("{$set:", bsDoc.ToJson(), "}");

            //if (isUpsert && isAutoIncrType)
            //{
            //    //如果key不为空或0,则检查是否存在
            //    var exists = updateEntity.ID.Equals(default(TKey)) ? false
            //        : this.Exists(Filter.Eq(Util.PRIMARY_KEY_NAME, updateEntity.ID));

            //    if (!exists)
            //    {
            //        id = CreateIncID();
            //        update = update.SetOnInsert(Util.PRIMARY_KEY_NAME, id);
            //    }
            //}
            if (isUpsert && isAutoIncrType)
            {
                id     = CreateIncID();
                update = update.SetOnInsert(Util.PRIMARY_KEY_NAME, id);
            }

            return(update);
        }
        //change password
        private void btnSaveChangePassword_Click(object sender, EventArgs e)
        {
            if (password != txtoldpassword.Text)
            {
                // validate old password
                MessageBox.Show("Wrong Password!");
                txtoldpassword.Focus();
            }
            else if (validateForm())
            {
                MongoClient            client = new MongoClient("mongodb://localhost");
                MongoServer            server = client.GetServer();
                MongoDatabase          db     = server.GetDatabase("NBA");
                MongoCollection <User> Users  = db.GetCollection <User>("Users");
                foreach (User i in Users.Find(Query.EQ("username", username)))
                {
                    IMongoUpdate update = new UpdateDocument();
                    //update password
                    update = MongoDB.Driver.Builders.Update.Set("password", txtnewpassword.Text.Trim());

                    Users.Update(Query.EQ("username", username), update);
                    MessageBox.Show("Password Updated");
                    break;
                }
            }
        }
    public static void ChangePassword(string id,string password)
    {
        MongoServer server = MongoServer.Create(connectionString);
        MongoDatabase db = server.GetDatabase(dbString);
        MongoCollection collection = db.GetCollection(collectionString);

        var query = new QueryDocument("StudentID", id);

        var update = new UpdateDocument { { "$set", new QueryDocument { { "Password", HashMD5(password) } } } };
        collection.Update(query, update);
    }
    public static void UpdateUser(string StudentID, string Name, string Sex, string Major, string BoardID , string Password)
    {
        MongoServer server = MongoServer.Create(connectionString);
        MongoDatabase db = server.GetDatabase(dbString);
        MongoCollection collection = db.GetCollection(collectionString);

        var query = new QueryDocument("StudentID", StudentID);

        var update = new UpdateDocument();

        if (Password == string.Empty)
        {
            update = new UpdateDocument { { "$set", new QueryDocument { { "StudentID", StudentID }, { "Name", Name }, { "Major", Major }, { "Sex", Sex }, { "BoardID", BoardID } } } };
        }
        else
        {
            update = new UpdateDocument { { "$set", new QueryDocument { { "StudentID", StudentID }, { "Name", Name }, { "Major", Major }, { "Sex", Sex }, { "BoardID", BoardID }, { "Password", HashMD5(Password) } } } };

        }

        collection.Update(query, update);
    }
    public static void UpdateLoginTime(string id)
    {
        MongoServer server = MongoServer.Create(connectionString);
        MongoDatabase db = server.GetDatabase(dbString);
        MongoCollection collection = db.GetCollection(collectionString);

        var query = new QueryDocument("StudentID", id);

        var update = new UpdateDocument { { "$set", new QueryDocument { { "LastLoginTime", BsonDateTime.Create(DateTime.Now + TimeSpan.FromHours(8)) } } } };
        collection.Update(query, update);
    }
Esempio n. 34
0
    public static void save_html_item_to_db(string type, string url, string html, string doc_id, string html_path, string regular_path, string doc_path,string redirect_template_id)
    {
        /*---------------------------------------------------------------------------------------------------|
         | type     |  HTML PATH        |     Regular PATH    |        DOC PATH       |  Redirect Template ID |
         | ---------|-------------------|---------------------|-----------------------|-----------------------|
         | F        | Fixed Value       |           X         |ALL                    |           X           |
         | ---------|-------------------|---------------------|-----------------------|-----------------------|
         | U        | URL  Value        |          √         |ALL                    |           X           |
         | ---------|-------------------|---------------------|-----------------------|-----------------------|
         | H        | HTML Path         |          √         |ALL,INNER,PROPERTY     |           X           |
         | ---------|-------------------|---------------------|-----------------------|-----------------------|
         | FR       | Fixed Value       |           X         |ALL                    |          √           |
         | ---------|-------------------|---------------------|-----------------------|-----------------------|
         | HR       | HTML Path         |          √         |ALL,INNER,PROPERTY     |          √           |
         |------------------------------|---------------------|-----------------------|-----------------------|
         | IMG      | HTML Path         |          √         |ALL,INNER,PROPERTY     |           X           |
         |------------------------------|---------------------|-----------------------|----------------------*/

        QueryDocument doc_query = new QueryDocument();
        doc_query.Add("doc_id", doc_id);
        UpdateDocument doc_update = new UpdateDocument();
        Regex reg;
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        HtmlNodeCollection nodes;

        string str_from = "";
        string str_update = "";
        switch (type)
        {
            case "F":
                str_update = doc_path.Replace("#ALL#", html_path);
                doc_update = MongoHelper.get_update_from_str(str_update);
                MongoHelper.update_bson(doc_query, doc_update);
                break;
            case "U":
                if (string.IsNullOrEmpty(regular_path))
                {
                    str_from = url;
                }
                else
                {
                    reg = new Regex(regular_path);
                    str_from = reg.Match(url).Value;
                }
                str_update = doc_path.Replace("#ALL#", str_from);
                doc_update = MongoHelper.get_update_from_str(str_update);
                MongoHelper.update_bson(doc_query, doc_update);
                break;

            case "H":
                doc.LoadHtml(html);
                nodes = doc.DocumentNode.SelectNodes(html_path);

                foreach (HtmlNode node in nodes)
                {

                    string value_orig = "";
                    string value_new = "";

                    reg = new Regex(@"#[^#]*#");
                    MatchCollection colloct = reg.Matches(doc_path);
                    value_orig = colloct[0].Value;

                    if (value_orig == "#ALL#")
                    {
                        value_new = node.WriteTo();

                    }
                    else if (value_orig == "#INNER#")
                    {
                        value_new = node.InnerHtml;
                    }
                    else
                    {
                        value_new = node.Attributes[value_orig.Replace("#", "").Trim()].Value.ToString();
                    }

                    //使用正则表达式选取值
                    if (string.IsNullOrEmpty(regular_path))
                    {
                        str_from = value_new;
                    }
                    else
                    {
                        reg = new Regex(regular_path);
                        str_from = reg.Match(value_new).Value;
                    }

                    //替代update_path中设置的参数
                    str_update = doc_path.Replace(value_orig, str_from);
                    doc_update = MongoHelper.get_update_from_str(str_update);
                    MongoHelper.update_bson(doc_query, doc_update);
                }
                break;
            case "FR":
                str_update = doc_path.Replace("#ALL#", html_path);
                doc_update = MongoHelper.get_update_from_str(str_update);
                MongoHelper.update_bson(doc_query, doc_update);

                save_redirect_html_to_db(HtmlHelper.get_full_url(url,html_path), redirect_template_id,doc_id);
                break;

            case "HR":
                doc.LoadHtml(html);
                nodes = doc.DocumentNode.SelectNodes(html_path);

                foreach (HtmlNode node in nodes)
                {

                    string value_orig = "";
                    string value_new = "";

                    reg = new Regex(@"#[^#]*#");
                    MatchCollection colloct = reg.Matches(doc_path);
                    value_orig = colloct[0].Value;

                    if (value_orig == "#ALL#")
                    {
                        value_new = node.WriteTo();

                    }
                    else if (value_orig == "#INNER#")
                    {
                        value_new = node.InnerHtml;
                    }
                    else
                    {
                        value_new = node.Attributes[value_orig.Replace("#", "").Trim()].Value.ToString();
                    }

                    //使用正则表达式选取值
                    if (string.IsNullOrEmpty(regular_path))
                    {
                        str_from = value_new;
                    }
                    else
                    {
                        reg = new Regex(regular_path);
                        str_from = reg.Match(value_new).Value;
                    }

                    //替代update_path中设置的参数
                    str_update = doc_path.Replace(value_orig, str_from);
                    doc_update = MongoHelper.get_update_from_str(str_update);
                    MongoHelper.update_bson(doc_query, doc_update);

                    save_redirect_html_to_db(HtmlHelper.get_full_url(url,str_from), redirect_template_id,doc_id);
                }
                break;

            case "IMG":
                doc.LoadHtml(html);
                nodes = doc.DocumentNode.SelectNodes(html_path);

                string img_url = "";
                foreach (HtmlNode node in nodes)
                {

                    string value_orig = "";
                    string value_new = "";

                    reg = new Regex(@"#[^#]*#");
                    MatchCollection colloct = reg.Matches(doc_path);
                    value_orig = colloct[0].Value;

                    if (value_orig == "#ALL#")
                    {
                        value_new = node.WriteTo();
                    }
                    else if (value_orig == "#INNER#")
                    {
                        value_new = node.InnerHtml;
                    }
                    else
                    {
                        value_new = node.Attributes[value_orig.Replace("#", "").Trim()].Value.ToString();
                    }

                    //使用正则表达式选取值
                    if (string.IsNullOrEmpty(regular_path))
                    {
                        img_url = value_new;
                    }
                    else
                    {
                        reg = new Regex(regular_path);
                        img_url = reg.Match(value_new).Value;
                    }

                    str_from = img_url.Replace(@"/", "-").Replace(@"\", "-");
                    //替代update_path中设置的参数
                    str_update = doc_path.Replace(value_orig, str_from);
                    doc_update = MongoHelper.get_update_from_str(str_update);
                    MongoHelper.update_bson(doc_query, doc_update);

                    HtmlHelper.down_img_from_url(HtmlHelper.get_full_url(url, img_url), doc_id + str_from);
                }
                break;
            default:
                break;
        }
    }
    public static void UpdateHomeworkRecord(string studentID, int index)
    {
        MongoServer server = MongoServer.Create(connectionString);
        MongoDatabase db = server.GetDatabase(dbString);
        MongoCollection collection = db.GetCollection(collectionString);

        var query = new QueryDocument("StudentID", studentID);

        var update = new UpdateDocument { { "$set", new QueryDocument { { "Homework" + index.ToString(), "1" } } } };

        collection.Update(query, update);
    }
    public static void UpdateLoginNum(string id)
    {
        MongoServer server = MongoServer.Create(connectionString);
        MongoDatabase db = server.GetDatabase(dbString);
        MongoCollection collection = db.GetCollection(collectionString);

        User user = QueryUser(id);

        var query = new QueryDocument("StudentID", id);

        var update = new UpdateDocument { { "$set", new QueryDocument { { "LoginNum", BsonInt32.Create(user.LoginNum + 1) } } } };
        collection.Update(query, update);
    }
Esempio n. 37
0
 public static void update_bson(QueryDocument query_doc, UpdateDocument update_doc)
 {
     MongoCollection<BsonDocument> collecions = base_db.GetCollection(base_doc_name);
     collecions.Update(query_doc, update_doc);
 }
        private void SaveChunk()
        {
            using (_fileInfo.Server.RequestStart(null, _fileInfo.ServerInstance))
            {
                var gridFS = new MongoGridFS(_fileInfo.Server, _fileInfo.DatabaseName, _fileInfo.GridFSSettings);
                var database = gridFS.GetDatabase(ReadPreference.Primary);
                var chunksCollection = gridFS.GetChunksCollection(database);

                var lastChunkIndex = (_length + _fileInfo.ChunkSize - 1) / _fileInfo.ChunkSize - 1;
                if (_chunkIndex == -1 || _chunkIndex > lastChunkIndex)
                {
                    var message = string.Format("Invalid chunk index {0}.", _chunkIndex);
                    throw new MongoGridFSException(message);
                }

                var lastChunkSize = (int)(_length % _fileInfo.ChunkSize);
                if (lastChunkSize == 0)
                {
                    lastChunkSize = _fileInfo.ChunkSize;
                }

                BsonBinaryData data;
                if (_chunkIndex < lastChunkIndex || lastChunkSize == _fileInfo.ChunkSize)
                {
                    data = new BsonBinaryData(_chunk);
                }
                else
                {
                    var lastChunk = new byte[lastChunkSize];
                    Buffer.BlockCopy(_chunk, 0, lastChunk, 0, lastChunkSize);
                    data = new BsonBinaryData(lastChunk);
                }

                var query = Query.EQ("_id", _chunkId);
                var update = new UpdateDocument
                {
                    { "_id", _chunkId },
                    { "files_id", _fileInfo.Id },
                    { "n", (_chunkIndex < int.MaxValue) ? (BsonValue)new BsonInt32((int)_chunkIndex) : new BsonInt64(_chunkIndex) },
                    { "data", data }
                };
                chunksCollection.Update(query, update, UpdateFlags.Upsert);
                _chunkIsDirty = false;
            }
        }
        private void SaveChunk()
        {
            var lastChunkIndex = (_length + _fileInfo.ChunkSize - 1) / _fileInfo.ChunkSize - 1;
            if (_chunkIndex == -1 || _chunkIndex > lastChunkIndex)
            {
                var message = string.Format("Invalid chunk index {0}.", _chunkIndex);
                throw new MongoGridFSException(message);
            }

            var lastChunkSize = (int)(_length % _fileInfo.ChunkSize);
            if (lastChunkSize == 0)
            {
                lastChunkSize = _fileInfo.ChunkSize;
            }

            BsonBinaryData data;
            if (_chunkIndex < lastChunkIndex || lastChunkSize == _fileInfo.ChunkSize)
            {
                data = new BsonBinaryData(_chunk);
            }
            else
            {
                var lastChunk = new byte[lastChunkSize];
                Buffer.BlockCopy(_chunk, 0, lastChunk, 0, lastChunkSize);
                data = new BsonBinaryData(lastChunk);
            }

            var query = Query.EQ("_id", _chunkId);
            var update = new UpdateDocument
            {
                { "_id", _chunkId },
                { "files_id", _fileInfo.Id },
                { "n", (_chunkIndex < int.MaxValue) ? (BsonValue)new BsonInt32((int)_chunkIndex) : new BsonInt64(_chunkIndex) },
                { "data", data }
            };
            _gridFS.Chunks.Update(query, update, UpdateFlags.Upsert);
            _chunkIsDirty = false;
        }
Esempio n. 40
0
        private async Task DoWork(IMongoCollection<BsonDocument> collection)
        {
            var rand = new Random();
            while (!_cancellationTokenSource.IsCancellationRequested)
            {
                var i = rand.Next(0, 10000);
                List<BsonDocument> docs;
                try
                {
                    docs = await collection.Find(new BsonDocument("i", i))
                        .ToListAsync(_cancellationTokenSource.Token);
                }
                catch
                {
                    Console.Write("+");
                    continue;
                }

                if (docs.Count == 0)
                {
                    try
                    {
                        await collection.InsertOneAsync(new BsonDocument("i", i), _cancellationTokenSource.Token);
                    }
                    catch
                    {
                        Console.Write("*");
                    }
                }
                else
                {
                    try
                    {
                        var filter = new QueryDocument("_id", docs[0]["_id"]);
                        var update = new UpdateDocument("$set", new BsonDocument("i", i + 1));
                        await collection.UpdateOneAsync(filter, update, cancellationToken: _cancellationTokenSource.Token);
                        //Console.Write(".");
                    }
                    catch (Exception)
                    {
                        Console.Write("*");
                    }
                }
            }
        }
Esempio n. 41
0
 public static UpdateDocument get_update_from_str(string str)
 {
     BsonDocument doc = BsonSerializer.Deserialize<BsonDocument>(str);
     UpdateDocument doc_update = new UpdateDocument();
     doc_update.AddRange(doc.Elements);
     return doc_update;
 }