public void UpdateClients(List <BannedClientRecord> newBannedClientRecords)
        {
            var filter = Builders <BannedClientRecord> .Filter;
            var update = Builders <BannedClientRecord> .Update;

            var updatesLength = newBannedClientRecords.Count;
            var updates       = new WriteModel <BannedClientRecord> [updatesLength];

            for (int i = 0; i < updatesLength; i++)
            {
                var banRecord        = newBannedClientRecords[i];
                var source           = banRecord.Source;
                var currentAccFilter = filter.Eq(a => a.Source, source);
                if (banRecord.BanCounts == 0)
                {
                    updates[i] = new DeleteOneModel <BannedClientRecord>(currentAccFilter);
                }
                else
                {
                    updates[i] = new ReplaceOneModel <BannedClientRecord>(currentAccFilter, banRecord)
                    {
                        IsUpsert = true
                    }
                };
            }
            bannedClientsCollection.BulkWrite(updates);
        }
    }
        private WriteModel <ConstellationState> GetConstellationUpdate(DiffObject.ConstellationState constellationState)
        {
            if (constellationState == null)
            {
                return(null);
            }
            var cursor = constellationState.TxCursor;

            WriteModel <ConstellationState> updateModel = null;

            if (constellationState.IsInserted)
            {
                updateModel = new InsertOneModel <ConstellationState>(new ConstellationState
                {
                    TxCursor = cursor
                });
            }
            else if (constellationState.IsDeleted)
            {
                throw new InvalidOperationException("Stellar data entry cannot be deleted");
            }
            else
            {
                updateModel = new UpdateOneModel <ConstellationState>(Builders <ConstellationState> .Filter.Empty, Builders <ConstellationState> .Update.Set(s => s.TxCursor, cursor));
            }

            return(updateModel);
        }
Esempio n. 3
0
        public void Test()
        {
            var client = new MongoClient("mongodb://localhost:27017");

            var database = client.GetDatabase("agv");

            var collection = database.GetCollection <BsonDocument>("car_station");

            var models = new WriteModel <BsonDocument>[]
            {
                new InsertOneModel <BsonDocument>(new BsonDocument("_id", 4)),
                new InsertOneModel <BsonDocument>(new BsonDocument("_id", 5)),
                new InsertOneModel <BsonDocument>(new BsonDocument("_id", 6)),
                new UpdateOneModel <BsonDocument>(
                    new BsonDocument("_id", 1),
                    new BsonDocument("$set", new BsonDocument("x", 2))),
                new DeleteOneModel <BsonDocument>(new BsonDocument("_id", 3)),
                new ReplaceOneModel <BsonDocument>(
                    new BsonDocument("_id", 3),
                    new BsonDocument("_id", 3).Add("x", 4))
            };

            // 1. Ordered bulk operation - order of operation is guaranteed
            collection.BulkWrite(models);

            // 2. Unordered bulk operation - no guarantee of order of operation
            collection.BulkWrite(models, new BulkWriteOptions {
                IsOrdered = false
            });
        }
Esempio n. 4
0
        private static void AssertModelEqualsExpectedDefinition <T>(BsonDocument expectedUpdateDefinition,
                                                                    WriteModel <T> writeModel, Dictionary <string, Action <BsonValue, BsonValue> > customAsserts = null)
        {
            if (customAsserts == null)
            {
                customAsserts = new Dictionary <string, Action <BsonValue, BsonValue> >();
            }

            var updateDefinition       = ((UpdateOneModel <T>)writeModel).Update;
            var actualUpdateDefinition = updateDefinition.ToBsonDocument()["Document"].ToBsonDocument();

            foreach (var customAssert in customAsserts)
            {
                PopValueFromExpectedAndActualDocuments(expectedUpdateDefinition, actualUpdateDefinition, customAssert.Key, out var expectedValue, out var actualValue);
                customAssert.Value(expectedValue, actualValue);
            }

            var expectedKeys = expectedUpdateDefinition.Elements.Select(e => e.Name).ToArray();
            var actualKeys   = actualUpdateDefinition.Elements.Select(e => e.Name).ToArray();

            CollectionAssert.AreEquivalent(expectedKeys, actualKeys);

            foreach (var key in actualKeys)
            {
                CollectionAssert.AreEquivalent(expectedUpdateDefinition[key].AsBsonDocument, actualUpdateDefinition[key].AsBsonDocument);
            }
        }
Esempio n. 5
0
        public async Task <IActionResult> WriteTable([FromBody] WriteModel model)
        {
            model.UserId = _User.ID;
            if (model.UserId == 0)
            {
                _logger.LogWarning($"{DateTime.Now} 请求WriteTable access_token 无效");
                this.HttpContext.Response.StatusCode = 401;
                return(Ok(new
                {
                    Success = false,
                    Msg = "Token无效 Httpcontext 解析失败",
                    this.HttpContext.Response.StatusCode
                }));
            }
            model.Role = _User.GetRole();
            var result = await _ProjectInfoService.WriteTableData(model);

            _logger.LogInformation($"IP: {_User.GetClientIP()} 用户名:{_User.Name} ID:{_User.ID}  成功写入了数据");
            return(Ok(new
            {
                Success = result,
                Msg = result == true ? "写入成功" : "写入失败",
                this.HttpContext.Response.StatusCode
            }));
        }
#pragma warning restore CRR0026 // Unused member
        private string GetWriteModelAsString <TEntity>(WriteModel <TEntity> writeModel)
        {
            if (writeModel is InsertOneModel <TEntity> insertModel)
            {
                return(new BsonDocument
                {
                    { "Document", insertModel.Document.ToBsonDocument() }
                }.ToString());
            }
            else if (writeModel is UpdateOneModel <TEntity> updateModel)
            {
                var serializer = BsonSerializer.LookupSerializer <TEntity>();
                return(new BsonDocument
                {
                    { "Filter", updateModel.Filter.Render(serializer, BsonSerializer.SerializerRegistry) },
                    { "Update", updateModel.Update.Render(serializer, BsonSerializer.SerializerRegistry) }
                }.ToString());
            }
            else if (writeModel is DeleteOneModel <TEntity> deleteModel)
            {
                var serializer = BsonSerializer.LookupSerializer <TEntity>();
                return(new BsonDocument
                {
                    { "Filter", deleteModel.Filter.Render(serializer, BsonSerializer.SerializerRegistry) }
                }.ToString());
            }
            else
            {
                return($"Can't render {writeModel.ModelType} to a string");
            }
        }
Esempio n. 7
0
        public object getProcess(WriteModel pro)
        {
            FromOA            f    = new FromOA();
            List <WriteModel> list = f.getProcessList(pro);

            return(list);
        }
Esempio n. 8
0
        public override async Task <BulkWriteResult <BsonDocument> > ApplyToField(IFieldDefinition field,
                                                                                  IMongoCollection <BsonDocument> collection,
                                                                                  CancellationToken?cancellationToken = null)
        {
            if (cancellationToken == null)
            {
                cancellationToken = CancellationToken.None;
            }
            var updateModels = new WriteModel <BsonDocument> [field.Extras.Extra.Count];
            int iModel       = 0;
            var dummies      = field.Extras.Extra;

            foreach (var column in dummies)
            {
                var query = Builders <BsonDocument> .Filter.And(
                    Builders <BsonDocument> .Filter.Eq(field.Name, column.Value)
                    );

                var updates = new List <UpdateDefinition <BsonDocument> >();
                updates.Add(Builders <BsonDocument> .Update.Set(field.Name, column.Key));
                var qrUpdateRoot = Builders <BsonDocument> .Update.Combine(updates);

                var actionModel = new UpdateManyModel <BsonDocument>(query, qrUpdateRoot);
                updateModels[iModel++] = actionModel;
            }
            var result = await collection.BulkWriteAsync(updateModels, new BulkWriteOptions()
            {
            }, cancellationToken.Value);

            return(result);
        }
Esempio n. 9
0
        protected void BulkWriteAsync(IEnumerable <T> elements, int bulkSize)
        {
            if (elements == null)
            {
                throw new ArgumentNullException("elements");
            }

            if (bulkSize < 1)
            {
                throw new InvalidOperationException("bulkSize is small than 1.");
            }

            var cache   = new WriteModel <T> [bulkSize];
            var options = new BulkWriteOptions
            {
                BypassDocumentValidation = true,
                IsOrdered = false
            };

            var index = 0;

            foreach (var item in elements)
            {
                cache[index % BulkSize] = new InsertOneModel <T>(item);

                if (((index + 1) % bulkSize) == 0)
                {
                    MongoCollection.BulkWriteAsync(cache, options);
                }

                index++;
            }
        }
Esempio n. 10
0
        protected override async Task Handle(SubscribeCommand command, CancellationToken token)
        {
            try
            {
                await CheckConflicts(command);

                WriteModel.BeginTransaction();

                var user = CreateUser(command);

                await Task.WhenAll(
                    new Task[] {
                    WriteModel.UserRepository.Save(user),
                    EventPublisher.PublishNewEvents(user)
                }
                    );

                WriteModel.Commit();
            }
            catch
            {
                WriteModel.Rollback();
                throw;
            }
        }
Esempio n. 11
0
        private void btn_WriteInt_Click(object sender, EventArgs e)
        {
            try
            {
                WriteModel writeModel = new WriteModel();
                writeModel.address = Convert.ToInt32(tb_WriteAddr.Text, 16).ToString();
                WriteModel.value   = Convert.ToInt32(tb_WriteValue.Text);
                writeModel.btnName = ((Button)sender).Name;
                writeModel.diZeng  = Convert.ToInt32(tb_WriteDiZeng.Text);

                if (!cb_ContinuousWrite.Checked)
                {
                    Write(writeModel);
                }
                else
                {
                    if (WriteModel.threadTimer == null)
                    {
                        WriteModel.threadTimer     = new System.Threading.Timer(new System.Threading.TimerCallback(Write), writeModel, 0, Convert.ToInt32(tb_periodWrite.Text));
                        WriteModel.IsRun           = true;
                        btn_WriteTimerStop.Enabled = true;
                        ShowMsg("已启用循环写入");
                    }
                }
            }
            catch {
                ShowMsg("请输入正确的值");
            }
        }
        public virtual string SerializeWriteModel(WriteModel <BsonDocument> writeModel)
        {
            string serializedDoc;

            var serializer = DbContext
                             .Database
                             .GetCollection <BsonDocument>(DbContext.JobGraph.CollectionNamespace.CollectionName)
                             .DocumentSerializer;

            var registry = DbContext.JobGraph.Settings.SerializerRegistry;

            switch (writeModel.ModelType)
            {
            case WriteModelType.InsertOne:
                serializedDoc = ((InsertOneModel <BsonDocument>)writeModel).Document.ToJson();
                break;

            case WriteModelType.DeleteOne:
                serializedDoc = ((DeleteOneModel <BsonDocument>)writeModel).Filter.Render(serializer, registry)
                                .ToJson();
                break;

            case WriteModelType.DeleteMany:
                serializedDoc = ((DeleteManyModel <BsonDocument>)writeModel).Filter.Render(serializer, registry)
                                .ToJson();
                break;

            case WriteModelType.ReplaceOne:

                serializedDoc = new Dictionary <string, BsonDocument>
                {
                    ["Filter"]      = ((ReplaceOneModel <BsonDocument>)writeModel).Filter.Render(serializer, registry),
                    ["Replacement"] = ((ReplaceOneModel <BsonDocument>)writeModel).Replacement
                }.ToJson();
                break;

            case WriteModelType.UpdateOne:
                serializedDoc = new Dictionary <string, BsonDocument>
                {
                    ["Filter"] = ((UpdateOneModel <BsonDocument>)writeModel).Filter.Render(serializer, registry),
                    ["Update"] = ((UpdateOneModel <BsonDocument>)writeModel).Update.Render(serializer, registry).AsBsonDocument
                }.ToJson();
                break;

            case WriteModelType.UpdateMany:
                serializedDoc = new Dictionary <string, BsonDocument>
                {
                    ["Filter"] = ((UpdateManyModel <BsonDocument>)writeModel).Filter.Render(serializer, registry),
                    ["Update"] = ((UpdateManyModel <BsonDocument>)writeModel).Update.Render(serializer, registry).AsBsonDocument
                }.ToJson();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(serializedDoc);
        }
Esempio n. 13
0
        public WriteViewModel()
        {
            writeModel = new WriteModel();
            GenerateDummyDataCommand = new RelayCommand(o => GenerateDummyDataClick("GenerateDummyDataCommandButton"));
            DeleteDummyDataCommand   = new RelayCommand(o => DeleteDummyDataClick("DeleteDummyDataCommandButton"));

            SetStatusUpdate("Ready.");
            RecordAmountValue = "1234567";
        }
Esempio n. 14
0
 public void OneTimeSetUp()
 {
     _connectionId = new ConnectionId(new ServerId(new ClusterId(1), new DnsEndPoint("localhost", 27017)), 2);
     var processedRequests = new[] { new InsertOneModel<BsonDocument>(new BsonDocument("b", 1)) };
     var upserts = new BulkWriteUpsert[0];
     _bulkWriteResult = new BulkWriteResult<BsonDocument>.Acknowledged(1, 1, 0, 0, 0, processedRequests, upserts);
     _writeConcernError = new WriteConcernError(11, "funny", new BsonDocument("c", 1));
     _writeErrors = new[] { new BulkWriteError(10, ServerErrorCategory.Uncategorized, 1, "blah", new BsonDocument("a", 1)) };
     _unprocessedRequests = new[] { new InsertOneModel<BsonDocument>(new BsonDocument("a", 1)) };
 }
Esempio n. 15
0
        /// <summary>
        /// 流程签字
        /// </summary>
        /// <param name="pro"></param>
        /// <returns></returns>
        public List <WriteModel> getProcessList(WriteModel pro)
        {
            string     sql    = "select m.name,d.name as 'depatement',l.name as 'leave',c.attitude,c.create_date FROM  [dbo].[col_opinion] c left join v3x_org_member m on c.writer_id = m.id left join v3x_org_department d on d.id = m.org_department_id left join v3x_org_level l on l.id = m.org_level_id     where col_id='" + pro.col_id + "' order by c.create_date ";
            DataTable  dt     = SqlHelper.ExecuteDataTable(config, sql);
            WriteModel result = new WriteModel();

            string[]          field = new string[] { "name", "depatement", "leave", "create_date", "attitude" };
            List <WriteModel> list  = ModelHelper.PutAllVal <WriteModel>(result, dt, field);

            return(list);
        }
Esempio n. 16
0
        private WriteModel <AccountModel>[] GetAccountUpdates(List <DiffObject.Account> accounts)
        {
            if (accounts == null || accounts.Count < 1)
            {
                return(null);
            }
            var filter = Builders <AccountModel> .Filter;
            var update = Builders <AccountModel> .Update;

            var accLength = accounts.Count;
            var updates   = new WriteModel <AccountModel> [accLength];

            for (int i = 0; i < accLength; i++)
            {
                var acc = accounts[i];
                var currentAccFilter = filter.Eq(a => a.Id, acc.Id);
                if (acc.IsInserted)
                {
                    updates[i] = new InsertOneModel <AccountModel>(new AccountModel
                    {
                        Id                = acc.Id,
                        Nonce             = acc.Nonce,
                        PubKey            = acc.PubKey,
                        RequestRateLimits = acc.RequestRateLimits,
                        Withdrawal        = (acc.Withdrawal.HasValue ? acc.Withdrawal.Value : 0)
                    });
                }
                else if (acc.IsDeleted)
                {
                    updates[i] = new DeleteOneModel <AccountModel>(currentAccFilter);
                }
                else
                {
                    var updateDefs = new List <UpdateDefinition <AccountModel> >();
                    if (acc.Nonce != 0)
                    {
                        updateDefs.Add(update.Set(a => a.Nonce, acc.Nonce));
                    }

                    if (acc.RequestRateLimits != null)
                    {
                        updateDefs.Add(update.Set(a => a.RequestRateLimits, acc.RequestRateLimits));
                    }

                    if (acc.Withdrawal.HasValue)
                    {
                        updateDefs.Add(update.Set(a => a.Withdrawal, acc.Withdrawal.Value));
                    }

                    updates[i] = new UpdateOneModel <AccountModel>(currentAccFilter, update.Combine(updateDefs));
                }
            }
            return(updates);
        }
Esempio n. 17
0
        public void Should_convert_from_InsertRequest_to_BsonDocument()
        {
            var document = BsonDocument.Parse("{a:1}");
            var request  = new InsertRequest(new BsonDocumentWrapper(document));

            var result = WriteModel <BsonDocument> .FromCore(request);

            result.Should().BeOfType <InsertOneModel <BsonDocument> >();
            var insertModel = (InsertOneModel <BsonDocument>)result;

            insertModel.Document.Should().BeSameAs(document);
        }
Esempio n. 18
0
        /// <summary>
        /// 批量插入数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="databaseName"></param>
        /// <param name="collectionName"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static BulkWriteResult BulkWrite <T>(string databaseName, string collectionName, List <T> list)
        {
            WriteModel <T>[] bulkModels = new WriteModel <T> [list.Count];
            Parallel.For(0, list.Count, (int i) =>
            {
                bulkModels[i] = new InsertOneModel <T>(list[i]);
            });

            BulkWriteResult result = ClientInstance.GetDatabase(databaseName).GetCollection <T>(collectionName).BulkWrite(bulkModels);

            return(result);
        }
Esempio n. 19
0
        public void Should_convert_from_InsertRequest_to_Class()
        {
            var document = new TestClass {
                a = 1
            };
            var request = new InsertRequest(new BsonDocumentWrapper(document));

            var result = WriteModel <TestClass> .FromCore(request);

            result.Should().BeOfType <InsertOneModel <TestClass> >();
            var model = (InsertOneModel <TestClass>)result;

            model.Document.Should().BeSameAs(document);
        }
        public async Task <bool> AddItemAsync(Gorev item)
        {
            var db         = MongoService.Db;
            var collection = db.GetCollection <Gorev>("gorevler");
            var wm         = new WriteModel <Gorev> [1];

            wm[0] = new ReplaceOneModel <Gorev>(new BsonDocument("_id", item.Id), item)
            {
                IsUpsert = true
            };
            collection.BulkWrite(wm);
            GetData();
            return(await Task.FromResult(true));
        }
Esempio n. 21
0
        private void Write(object wtiteModel)
        {
            try
            {
                WriteModel writeModel = (WriteModel)wtiteModel;
                bool       isSuccess  = false;
                switch (writeModel.btnName)
                {
                case "btn_WriteInt32":
                    isSuccess = mbClient.Write(writeModel.address, WriteModel.value);
                    break;

                case "btn_WriteInt16":
                    isSuccess = mbClient.Write(writeModel.address, (short)WriteModel.value);
                    break;

                case "btn_WriteUInt16":
                    isSuccess = mbClient.Write(writeModel.address, (ushort)WriteModel.value);
                    break;

                case "btn_WriteUInt32":
                    uint a = Convert.ToUInt32(WriteModel.value);
                    isSuccess = mbClient.Write(writeModel.address, a);
                    break;

                //btn_WriteInt16
                //btn_WriteUInt16
                //btn_WriteUInt32
                default: return;
                }
                if (isSuccess)
                {
                    ShowMsgToWriteRegion("将值" + WriteModel.value + "写入到地址:" + writeModel.address + " - 成功!");
                }
                else
                {
                    ShowMsgToWriteRegion("将值" + WriteModel.value + "写入到地址:" + writeModel.address + " - 失败!");
                }
                if (writeModel.diZeng != 0)
                {
                    WriteModel.value += writeModel.diZeng;
                }
            }
            catch (Exception ex) {
                ShowMsg("执行写入出错:" + ex.Message);
            }
        }
        public ActionResult Write()
        {
            UserModel user = userService.GetCurrentUserAsModel();

            if (user == null || user.keywords.Count == 0)
            {
                return(View(new WriteModel()
                {
                    IsMale = true
                }));
            }
            WriteModel writeModel = new WriteModel();

            writeModel.keywords = user.keywords;
            writeModel.IsMale   = true;
            return(View(writeModel));
        }
Esempio n. 23
0
        private bool TryParseWriteModel(BsonDocument value, out WriteModel <BsonDocument> request)
        {
            var name = value["name"].AsString;

            switch (name)
            {
            case "updateMany":
                return(TryParseUpdateManyModel(value, out request));

            case "updateOne":
                return(TryParseUpdateOneModel(value, out request));

            default:
                request = null;
                return(false);
            }
        }
Esempio n. 24
0
        private WriteModel <OrderModel>[] GetOrderUpdates(List <DiffObject.Order> orders)
        {
            if (orders == null || orders.Count < 1)
            {
                return(null);
            }
            unchecked
            {
                var filter = Builders <OrderModel> .Filter;
                var update = Builders <OrderModel> .Update;

                var ordersLength = orders.Count;
                var updates      = new WriteModel <OrderModel> [ordersLength];

                for (int i = 0; i < ordersLength; i++)
                {
                    var order = orders[i];

                    var currentOrderFilter = filter.And(filter.Eq(s => s.Id, (long)order.OrderId));

                    if (order.IsInserted)
                    {
                        updates[i] = new InsertOneModel <OrderModel>(new OrderModel
                        {
                            Id          = (long)order.OrderId,
                            Amount      = order.AmountDiff,
                            QuoteAmount = order.QuoteAmountDiff,
                            Price       = order.Price,
                            Account     = order.Account
                        });
                    }
                    else if (order.IsDeleted)
                    {
                        updates[i] = new DeleteOneModel <OrderModel>(currentOrderFilter);
                    }
                    else
                    {
                        updates[i] = new UpdateOneModel <OrderModel>(
                            currentOrderFilter,
                            update.Inc(b => b.Amount, order.AmountDiff).Inc(b => b.QuoteAmount, order.QuoteAmountDiff)
                            );
                    }
                }
                return(updates);
            }
        }
Esempio n. 25
0
        private void MongoTest()
        {
            var db         = MongoService.Db;
            var collection = db.GetCollection <Gorev>("gorevler");
            var models     = new WriteModel <Gorev> [1];
            var gorev      = new Gorev()
            {
                Aciklama    = "Test girişi",
                BitisTarihi = DateTime.Now.AddDays(10),
                GorevAdi    = "Test görevi"
            };

            models[0] = new ReplaceOneModel <Gorev>(new BsonDocument("_id", gorev.Id), gorev)
            {
                IsUpsert = true
            };
            collection.BulkWrite(models);
        }
Esempio n. 26
0
        public async Task PutPagesAsync(List <PageDto> pages)
        {
            var collection = Context.Database.GetCollection <PageDto>("Pages");
            var models     = new WriteModel <PageDto> [pages.Count];

            for (var i = 0; i < pages.Count; i++)
            {
                var item = pages[i];
                models[i] = new ReplaceOneModel <PageDto>(
                    Builders <PageDto> .Filter.Where(x => x._id == item._id),
                    (PageDto)item
                    )
                {
                    IsUpsert = true
                };
            }
            ;
            await collection.BulkWriteAsync(models);
        }
Esempio n. 27
0
        private WriteModel <BalanceModel>[] GetBalanceUpdates(List <DiffObject.Balance> balances)
        {
            if (balances == null || balances.Count < 1)
            {
                return(null);
            }
            var filter = Builders <BalanceModel> .Filter;
            var update = Builders <BalanceModel> .Update;

            var balancesLength = balances.Count;
            var updates        = new WriteModel <BalanceModel> [balancesLength];

            for (int i = 0; i < balancesLength; i++)
            {
                var balance = balances[i];
                var currentBalanceFilter = filter.Eq(s => s.Id, balance.Id);

                if (balance.IsInserted)
                {
                    updates[i] = new InsertOneModel <BalanceModel>(new BalanceModel
                    {
                        Id          = balance.Id,
                        Amount      = balance.AmountDiff,
                        Liabilities = balance.LiabilitiesDiff
                    });
                }
                else if (balance.IsDeleted)
                {
                    updates[i] = new DeleteOneModel <BalanceModel>(currentBalanceFilter);
                }
                else
                {
                    updates[i] = new UpdateOneModel <BalanceModel>(
                        currentBalanceFilter,
                        update
                        .Inc(b => b.Amount, balance.AmountDiff)
                        .Inc(b => b.Liabilities, balance.LiabilitiesDiff)
                        );
                }
            }
            return(updates);
        }
Esempio n. 28
0
        private Task UpdateAll(FindAndModifyArgs <TRecord>[] modifications)
        {
            var updateModels = new WriteModel <TRecord> [modifications.Length];

            for (var i = 0; i < modifications.Length; i++)
            {
                var mod = modifications[i];
                //_collection.FindAndModify(mod);
                var actionModel = new UpdateOneModel <TRecord>(mod.Query, mod.Update);
                updateModels[i] = actionModel;
            }
            var output = _collection.BulkWriteAsync(updateModels, new BulkWriteOptions()
            {
            }, _cancellationToken).ContinueWith(x =>
            {
                Debug.WriteLine($"{DateTime.Now} Written batch[{modifications.Length}]");
            }, _cancellationToken);

            return(output);
        }
Esempio n. 29
0
        private bool TryParseUpdateOneModel(BsonDocument value, out WriteModel <BsonDocument> model)
        {
            FilterDefinition <BsonDocument> filter;
            UpdateDefinition <BsonDocument> update;
            List <ArrayFilterDefinition>    arrayFilters;

            if (TryParseArguments(value, out filter, out update, out arrayFilters))
            {
                model = new UpdateOneModel <BsonDocument>(filter, update)
                {
                    ArrayFilters = arrayFilters
                };
                return(true);
            }
            else
            {
                model = null;
                return(false);
            }
        }
        public static void write(byte[] message, WriteModel model)
        {
            if (message == null || message.Length <= 0)
            {
                return;
            }
            StringBuilder str = new StringBuilder();

            for (int i = 0; i < message.Length; i++)
            {
                str.Append(" 0x" + Convert.ToString(message[i], 16));
            }

            if (model.Equals(WriteModel.send))
            {
                //4.0协议
                int serial = 0;
                if (message.Length > 13)
                {
                    serial = StringUtil.byte2Int(new byte[] { message[10], message[11], message[12], message[13] });
                }
                //开始写入
                swS.WriteLine("serial:" + serial + "  data:" + str.ToString() + "   time:" + DateTime.Now.ToString("yyyyMMddhhmmssfff"));
                //清空缓冲区
                swS.Flush();
            }
            else
            {
                //4.0协议
                int serial = 0;
                if (message.Length > 10)
                {
                    serial = StringUtil.byte2Int(new byte[] { message[7], message[8], message[9], message[10] });
                }

                //开始写入
                swR.WriteLine("serial:" + serial + "  data:" + str.ToString() + "   time:" + DateTime.Now.ToString("yyyyMMddhhmmssfff"));
                //清空缓冲区
                swR.Flush();
            }
        }
 public static void write(string message, WriteModel model)
 {
     if (message == null || message.Length <= 0)
     {
         return;
     }
     if (model.Equals(WriteModel.send))
     {
         //开始写入
         swS.WriteLine("data:" + message + "    time:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"));
         //清空缓冲区
         swS.Flush();
     }
     else
     {
         //开始写入
         swR.WriteLine("data:" + message + "   time:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"));
         //清空缓冲区
         swR.Flush();
     }
 }