Esempio n. 1
0
        public virtual async Task <DynamicObject> UpdateAsync(string id, DynamicObject model)
        {
            var bsonDocument    = BsonDocument.Create(model.ToDynamic());
            var updatedDocument = await this._repository.UpdateAsync(bsonDocument, id);

            return(updatedDocument != null ? await this.GetAsync(id) : null);
        }
Esempio n. 2
0
        public async Task can_handle_null_transaction_type()
        {
            (IBank <TestUser> _, IMongoCollection <TestUser> usersCollection) = CreateDbObjects(new MockClock());
            const string id      = "590df61373b975210006fcdf";
            Instant      instant = InstantPattern.ExtendedIso.Parse("2017-05-06T16:13:07.314Z").Value;
            IMongoCollection <BsonDocument> bsonTransactionLogCollection =
                usersCollection.Database.GetCollection <BsonDocument>("transactionLog");
            await bsonTransactionLogCollection.InsertOneAsync(BsonDocument.Create(new Dictionary <string, object?>
            {
                ["_id"]         = ObjectId.Parse(id),
                ["user"]        = "******",
                ["change"]      = -9,
                ["timestamp"]   = instant.ToDateTimeUtc(),
                ["old_balance"] = 25,
                ["new_balance"] = 16,
                ["match"]       = 35510,
            }));

            IMongoCollection <TransactionLog> transactionLogCollection =
                usersCollection.Database.GetCollection <TransactionLog>("transactionLog");
            TransactionLog log = await transactionLogCollection.Find(t => t.Id == id).FirstAsync();

            Assert.AreEqual(id, log.Id);
            Assert.AreEqual("137272735", log.UserId);
            Assert.AreEqual(-9, log.Change);
            Assert.AreEqual(25, log.OldBalance);
            Assert.AreEqual(16, log.NewBalance);
            Assert.AreEqual(instant, log.CreatedAt);
            Assert.IsNull(log.Type);
            Assert.AreEqual(new Dictionary <string, object?> {
                ["match"] = 35510
            }, log.AdditionalData);
        }
        /// <summary>
        /// 把解析到的爬虫实体数据存到MongoDb中
        /// </summary>
        /// <param name="model">数据模型</param>
        /// <param name="datas">数据</param>
        /// <param name="logger">日志接口</param>
        /// <param name="sender">调用方</param>
        /// <returns>最终影响结果数量(如数据库影响行数)</returns>
        protected override int Process(IModel model, IList <dynamic> datas, ILogger logger, dynamic sender = null)
        {
            if (datas == null || datas.Count == 0)
            {
                return(0);
            }

            var db         = _client.GetDatabase(model.Table.Database);
            var collection = db.GetCollection <BsonDocument>(model.Table.FullName);

            var action = new Action(() =>
            {
                List <BsonDocument> reslut = new List <BsonDocument>();
                foreach (var data in datas)
                {
                    BsonDocument item = BsonDocument.Create(data);
                    reslut.Add(item);
                }
                reslut.Add(BsonDocument.Create(DateTime.Now));
                collection.InsertMany(reslut);
            });

            if (DbConnectionExtensions.UseNetworkCenter)
            {
                NetworkCenter.Current.Execute("db", action);
            }
            else
            {
                action();
            }
            return(datas.Count);
        }
Esempio n. 4
0
        public virtual async Task <DynamicObject> CreateAsync(DynamicObject model)
        {
            var bsonDocument     = BsonDocument.Create(model.ToDynamic());
            var insertedDocument = await this._repository.InsertAsync(bsonDocument) as BsonDocument;

            return(DynamicObject.Create(BsonTypeMapper.MapToDotNetValue(insertedDocument) as Dictionary <string, object>));
        }
 public override int Process(string entityName, IList <dynamic> datas, ISpider spider)
 {
     if (_collections.TryGetValue(entityName, out var collection))
     {
         var action = new Action(() =>
         {
             List <BsonDocument> reslut = new List <BsonDocument>();
             foreach (var data in datas)
             {
                 BsonDocument item = BsonDocument.Create(data);
                 reslut.Add(item);
             }
             reslut.Add(BsonDocument.Create(DateTime.Now));
             collection.InsertMany(reslut);
         });
         if (DbExecutor.UseNetworkCenter)
         {
             NetworkCenter.Current.Execute("db", action);
         }
         else
         {
             action();
         }
     }
     return(datas.Count);
 }
Esempio n. 6
0
        /// <summary>
        /// Updates the given saga data with an optimistic lock, once in a while also ensuring that synchronous
        /// indexes with unique constraints are created for the given saga data property paths.
        /// </summary>
        public void Update(ISagaData sagaData, string[] sagaDataPropertyPathsToIndex)
        {
            var collection = database.GetCollection <BsonDocument>(GetCollectionName(sagaData.GetType()));

            EnsureIndexHasBeenCreated(sagaDataPropertyPathsToIndex, collection);

            var revisionElementName = GetRevisionElementName(sagaData);

            var criteria = Builders <BsonDocument> .Filter.And(Builders <BsonDocument> .Filter.Eq(IdElementName, sagaData.Id),
                                                               Builders <BsonDocument> .Filter.Eq(revisionElementName, sagaData.Revision));

            sagaData.Revision++;
            var docData = BsonDocument.Create(sagaData);

            try
            {
                var safeModeResult = collection.WithWriteConcern(WriteConcern.Acknowledged)
                                     .FindOneAndReplace(
                    criteria,
                    docData);
            }
            catch (MongoWriteConcernException ex)
            {
                // in case of race conditions, we get a duplicate key error because the upsert
                // cannot proceed to insert a document with the same _id as an existing document
                // ... therefore, we map the MongoSafeModeException to our own OptimisticLockingException
                throw new OptimisticLockingException(sagaData, ex);
            }
        }
        /// <summary>
        /// 把解析到的爬虫实体数据存到MongoDb中
        /// </summary>
        /// <param name="entityName">爬虫实体类的名称</param>
        /// <param name="datas">实体类数据</param>
        /// <param name="spider">爬虫</param>
        /// <returns>最终影响结果数量(如数据库影响行数)</returns>
        protected override int Process(IModel model, IEnumerable <dynamic> datas, ISpider spider)
        {
            var db         = _client.GetDatabase(model.TableInfo.Database);
            var collection = db.GetCollection <BsonDocument>(model.TableInfo.FullName);

            var action = new Action(() =>
            {
                List <BsonDocument> reslut = new List <BsonDocument>();
                foreach (var data in datas)
                {
                    BsonDocument item = BsonDocument.Create(data);
                    reslut.Add(item);
                }
                reslut.Add(BsonDocument.Create(DateTime.Now));
                collection.InsertMany(reslut);
            });

            if (DbExecutor.UseNetworkCenter)
            {
                NetworkCenter.Current.Execute("db", action);
            }
            else
            {
                action();
            }
            return(datas.Count());
        }
        /// <summary>
        /// 把解析到的爬虫实体数据存到MongoDb中
        /// </summary>
        /// <param name="datas">数据</param>
        /// <param name="sender">调用方</param>
        /// <returns>最终影响结果数量(如数据库影响行数)</returns>
        protected override int Process(IEnumerable <IBaseEntity> datas, dynamic sender = null)
        {
            if (datas == null)
            {
                return(0);
            }
            var tableInfo  = new TableInfo(datas.First().GetType());
            var db         = _client.GetDatabase(tableInfo.Schema.Database);
            var collection = db.GetCollection <BsonDocument>(tableInfo.Schema.FullName);

            var action = new Action(() =>
            {
                List <BsonDocument> reslut = new List <BsonDocument>();
                foreach (var data in datas)
                {
                    BsonDocument item = BsonDocument.Create(data);
                    reslut.Add(item);
                }
                reslut.Add(BsonDocument.Create(DateTime.Now));
                collection.InsertMany(reslut);
            });

            if (DatabaseExtensions.UseNetworkCenter)
            {
                NetworkCenter.Current.Execute("db", action);
            }
            else
            {
                action();
            }
            return(datas.Count());
        }
Esempio n. 9
0
        protected override async Task <DataFlowResult> Store(DataFlowContext context)
        {
            var items = context.GetItems();

            foreach (var item in items)
            {
                var tableMetadata = (TableMetadata)context[item.Key];

                if (!_cache.ContainsKey(tableMetadata.Schema.Database))
                {
                    _cache.TryAdd(tableMetadata.Schema.Database, _client.GetDatabase(tableMetadata.Schema.Database));
                }

                var db         = _cache[tableMetadata.Schema.Database];
                var collection = db.GetCollection <BsonDocument>(tableMetadata.Schema.Table);

                var bsonDocs = new List <BsonDocument>();
                foreach (var data in item.Value)
                {
                    bsonDocs.Add(BsonDocument.Create(data));
                }

                await collection.InsertManyAsync(bsonDocs);
            }

            return(DataFlowResult.Success);
        }
Esempio n. 10
0
        /// <summary>
        /// Drills down a certain "BsonDocument" for it's inner
        /// </summary>
        /// <param name="bsonDocument"></param>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        private static BsonDocument ReachInnerDocument(BsonDocument bsonDocument, String fieldName)
        {
            // New Instance of "bDoc"
            BsonDocument bDoc   = bsonDocument;
            BsonValue    bValue = null;

            // Splitting fields by hierarchy
            String[] fieldsHierarchy = fieldName.Split('.');

            // "Drilling Down" the fields
            foreach (string fieldLevel in fieldsHierarchy)
            {
                try
                {
                    bValue = bDoc[fieldLevel];

                    // Is this Value a "Primitive" type, or is it still a composite one?
                    if (bValue.IsBsonDocument)
                    {
                        bDoc = bValue.AsBsonDocument;
                    }
                }
                catch (Exception ex)
                {
                    error        = true;
                    errorMessage = ex.Message;
                    return(BsonDocument.Create(null));
                }
            }

            // Creating a new instance of "BsonDocument" containing the value found for this field
            return(new BsonDocument(fieldsHierarchy.Last(), bValue));
        }
        public async Task Consume(ConsumeContext <StandardizationValidationFailed> context)
        {
            var storedResult = new
            {
                Id = context.Message.Id,
                Ex = context.Message.Message
            }.ToBsonDocument();

            await collection.InsertOneAsync(BsonDocument.Create(storedResult));
        }
Esempio n. 12
0
 /// <summary>
 /// 将字符串转成List<BsonDocument>
 /// </summary>
 /// <param name="source"></param>
 /// <returns></returns>
 public static List <BsonDocument> ToBsonDocumentList(this string source)
 {
     try
     {
         List <object> objs = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <List <object> >(source);
         return(objs.Select(a => BsonDocument.Create(a)).ToList());
     }
     catch (Exception ex)
     {
     }
     return(new List <BsonDocument>());
 }
Esempio n. 13
0
        public void Save(string json, string collectionName)
        {
            var collection = GetCollection(collectionName);

            BsonArray docs =
                MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonArray>(json);

            foreach (var itm in docs)
            {
                collection.Save(BsonDocument.Create(itm));
            }
        }
        public override void Process(string entityName, List <DataObject> datas)
        {
            if (Collections.TryGetValue(entityName, out var collection))
            {
                List <BsonDocument> reslut = new List <BsonDocument>();
                foreach (var data in datas)
                {
                    BsonDocument item = new BsonDocument(data);

                    reslut.Add(item);
                }
                reslut.Add(BsonDocument.Create(DateTime.Now));
                collection.InsertMany(reslut);
            }
        }
Esempio n. 15
0
 public override int Process(string entityName, List <dynamic> datas)
 {
     if (Collections.TryGetValue(entityName, out var collection))
     {
         List <BsonDocument> reslut = new List <BsonDocument>();
         foreach (var data in datas)
         {
             BsonDocument item = BsonDocument.Create(data);
             reslut.Add(item);
         }
         reslut.Add(BsonDocument.Create(DateTime.Now));
         collection.InsertMany(reslut);
     }
     return(datas.Count);
 }
Esempio n. 16
0
        public override BsonDocument Build(object value)
        {
            if (!(value is IEnumerable <string>))
            {
                throw new ArgumentException("Invalid type of value parameter. It should be an IEnumerable<string>.");
            }

            var strings = (IEnumerable <string>)value;

            if (!strings.Any())
            {
                return(BsonDocument.Create(string.Empty));
            }

            return(BsonDocument.Parse(string.Format("{{$in: {0}}}", strings.ToJson())));
        }
Esempio n. 17
0
        public IEnumerable <BsonDocument> GetRecords(string key)
        {
            var response = _s3.GetObjectAsync("datahub69", key).Result;

            using (var stream = response.ResponseStream)
                using (var reader = new StreamReader(stream))
                    using (var csv = new CsvReader(reader))
                    {
                        csv.Read();
                        csv.ReadHeader();

                        while (csv.Read())
                        {
                            yield return(BsonDocument.Create((IDictionary <string, object>)csv.GetRecord <dynamic>()));
                        }
                    }
        }
        public override void Process(string entityName, List <JObject> datas)
        {
            IMongoCollection <BsonDocument> collection;

            if (Collections.TryGetValue(entityName, out collection))
            {
                List <BsonDocument> reslut = new List <BsonDocument>();
                foreach (var data in datas)
                {
                    BsonDocument item = BsonDocument.Parse(data.ToString());

                    reslut.Add(item);
                }
                reslut.Add(BsonDocument.Create(DateTime.Now));
                collection.InsertMany(reslut);
            }
        }
        public SnapshotDocument Serialize(IUncommittedSnapshot serializedSnapshot)
        {
            var id       = serializedSnapshot.Metadata.GetValue(MetadataKeys.SnapshotId, value => Guid.Parse(value.ToString()));
            var data     = BsonDocumentWrapper.Create(serializedSnapshot.Data);
            var metadata = BsonDocument.Create(serializedSnapshot.Metadata);

            var snapshot = new SnapshotDocument
            {
                Id          = id,
                Timestamp   = DateTime.UtcNow,
                AggregateId = serializedSnapshot.AggregateId,
                Version     = serializedSnapshot.AggregateVersion,
                Data        = data,
                Metadata    = metadata,
            };

            return(snapshot);
        }
Esempio n. 20
0
        public async Task log_has_expected_bson_datatypes()
        {
            MockClock clockMock = new MockClock();

            (IBank <TestUser> bank, IMongoCollection <TestUser> usersCollection) = CreateDbObjects(clockMock);
            TestUser user = new TestUser {
                Money = 10
            };
            await usersCollection.InsertOneAsync(user);

            List <int> list = new List <int> {
                1, 2, 3
            };
            Dictionary <string, bool> dictionary = new Dictionary <string, bool> {
                ["yes"] = true, ["no"] = false
            };
            await bank.PerformTransaction(new Transaction <TestUser>(user, 1, "test",
                                                                     new Dictionary <string, object?>
            {
                ["null_field"] = null,
                ["int_field"] = 42,
                ["string_field"] = "foo",
                ["list_field"] = list,
                ["dictionary_field"] = dictionary
            }));

            IMongoCollection <BsonDocument> transactionLogCollection =
                usersCollection.Database.GetCollection <BsonDocument>("transactionLog");
            BsonDocument log = await transactionLogCollection.Find(FilterDefinition <BsonDocument> .Empty).FirstAsync();

            Assert.IsInstanceOf <BsonObjectId>(log["_id"]);
            Assert.AreEqual(BsonString.Create(user.Id), log["user"]);
            Assert.AreEqual(BsonInt64.Create(1), log["change"]);
            Assert.AreEqual(BsonInt64.Create(10), log["old_balance"]);
            Assert.AreEqual(BsonInt64.Create(11), log["new_balance"]);
            Assert.AreEqual(clockMock.FixedCurrentInstant, log["timestamp"].ToUniversalTime().ToInstant());
            Assert.AreEqual(BsonString.Create("test"), log["type"]);
            Assert.AreEqual(BsonNull.Value, log["null_field"]);
            Assert.AreEqual(BsonInt32.Create(42), log["int_field"]);
            Assert.AreEqual(BsonString.Create("foo"), log["string_field"]);
            Assert.AreEqual(BsonArray.Create(list), log["list_field"]);
            Assert.AreEqual(BsonDocument.Create(dictionary), log["dictionary_field"]);
        }
Esempio n. 21
0
        /// <summary>
        /// Inserts the given saga data, once in a while also ensuring that synchronous indexes with unique
        /// constraints are created for the given saga data property paths.
        /// </summary>
        public void Insert(ISagaData sagaData, string[] sagaDataPropertyPathsToIndex)
        {
            var collection = database.GetCollection <BsonDocument>(GetCollectionName(sagaData.GetType()));

            EnsureIndexHasBeenCreated(sagaDataPropertyPathsToIndex, collection);

            sagaData.Revision++;
            var sagaDataBson = BsonDocument.Create(sagaData);

            try
            {
                collection.WithWriteConcern(WriteConcern.Acknowledged).InsertOne(sagaDataBson);
            }
            catch (MongoWriteConcernException ex)
            {
                // in case of race conditions, we get a duplicate key error because the upsert
                // cannot proceed to insert a document with the same _id as an existing document
                // ... therefore, we map the MongoSafeModeException to our own OptimisticLockingException
                throw new OptimisticLockingException(sagaData, ex);
            }
        }
Esempio n. 22
0
        /// <summary>
        /// 客户任务调度统计
        /// </summary>
        /// <returns></returns>
        private Dictionary <string, int> GetCustomerJobInfo()
        {
            Dictionary <string, int> result = new Dictionary <string, int>();
            var col = new MongoOperation().GetCollection("BackgroundJob");
            Dictionary <string, int> dicInitial = new Dictionary <string, int>();

            dicInitial["count"] = 0;
            var r = col.Group(
                Query.And(Query.NE("customerCode", null), Query.NE("customerCode", ""), Query.Exists("customerCode", true)),
                "customerCode",
                BsonDocument.Create(dicInitial),
                BsonJavaScript.Create("function(doc,prev){prev.count++;}"),
                null
                ).ToList();

            if (r.Count > 0)
            {
                foreach (var item in r)
                {
                    result.Add(item.Text("customerCode"), item.Int("count"));
                }
            }
            return(result);
        }
Esempio n. 23
0
        public IHttpActionResult Get([FromUri] Request <Info> request)
        {
            if (request.Type == -1)
            {
                MongoCollection          data           = database.GetCollection("info");
                GroupByBuilder           groupbyBuilder = new GroupByBuilder(new string[] { "CategoryCode", "CategoryName" });
                Dictionary <string, int> dic_F          = new Dictionary <string, int>();
                dic_F["num"] = 0;
                var result_F = data.Group(null, groupbyBuilder, BsonDocument.Create(dic_F), BsonJavaScript.Create("function(doc,prev){prev.num++;}"), BsonJavaScript.Create("function(doc){doc.Count=doc.num;delete doc.num;}")).ToList();

                /*List<InfoAllList> list = new List<InfoAllList>();
                 * if (result_F.Count > 0)
                 * {
                 *  foreach (var item in result_F)
                 *  {
                 *      InfoAllList temp = new InfoAllList();
                 *      temp.CategoryCode = item["CategoryCode"].AsString;
                 *      temp.CategoryName = item["CategoryName"].AsString;
                 *      temp.Count = item["Count"].AsDouble.ToString().ToInt(0);
                 *      list.Add(temp);
                 *  }
                 * }*/
                Response <List <BsonDocument> > rsp = new Response <List <BsonDocument> >();
                rsp.Data = result_F;
                return(Ok(rsp));
            }
            if (request.ID == "SearchInfo")
            {
                Response <List <InfoModel> > rsp = new Response <List <InfoModel> >();
                if (string.IsNullOrEmpty(request.Keyword))
                {
                    return(Ok(rsp));
                }

                List <InfoModel> list = new List <InfoModel>();

                #region 1、在mongodb查询匹配的Info对象
                IMongoQuery query = null;
                if (request.UserName == "Title")
                {
                    query = Query <Info> .Matches(c => c.Title, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "Author")
                {
                    query = Query <Info> .Matches(c => c.Author, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "Source")
                {
                    query = Query <Info> .Matches(c => c.Source, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "Digest")
                {
                    query = Query <Info> .Matches(c => c.Digest, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "KeyWord")
                {
                    query = Query <Info> .Matches(c => c.KeyWord, new BsonRegularExpression(new Regex(request.Keyword + ".*")));
                }
                else if (request.UserName == "CategoryCode")
                {
                    query = Query <Info> .Matches(c => c.CategoryCode, new BsonRegularExpression(new Regex(request.Keyword)));
                }

                if (query != null)
                {
                    var data = database.GetCollection("info").Find(query).ToList();
                    foreach (var item in data)
                    {
                        InfoModel temp = new InfoModel();
                        temp.InfoId = item.GetValue("_id").ToString();
                        temp.Title  = item.GetValue("Title").ToString();
                        Dictionary dic = getArticleClassNameFoo(item.GetValue("CategoryCode").ToString());
                        if (dic != null)
                        {
                            temp.ArticleClass = dic.value;
                        }
                        temp.ArticleCategory = item.GetValue("CategoryName").ToString();
                        temp.Author          = item.GetValue("Author").ToString();
                        string   extStr = item.GetValue("ArticleType").ToString();
                        string[] arr    = extStr.Split('、');
                        if (arr.Length > 0)
                        {
                            temp.FileType = arr[0];
                        }
                        else
                        {
                            temp.FileType = "1176708";
                        }

                        string fileUrl    = "";
                        string dbFileName = item.GetValue("FileName").AsString.Trim();
                        if (!string.IsNullOrEmpty(dbFileName))
                        {
                            fileUrl = "/Upload/" + dbFileName;
                        }

                        /*if (item.GetValue("FileName").ToString().Trim().EndsWith(".xls") || item.GetValue("FileName").ToString().Trim().EndsWith(".xlsx"))
                         * {
                         *  fileUrl += "XLS/";
                         * }
                         * fileUrl += item.GetValue("FileId").ToString().Trim() + "/" + item.GetValue("FileName").ToString().Trim();*/
                        temp.FilePath    = fileUrl;
                        temp.PublishTime = item.GetValue("PublishTime").AsDateTime;
                        temp.ArticleType = item.GetValue("ArticleType").AsString;
                        temp.ModifyTime  = item.GetValue("ModifyTime").AsDateTime;
                        temp.ModifyUser  = item.GetValue("ModifyUser").AsString;

                        list.Add(temp);
                    }
                }
                #endregion

                if (request.UserName == "Content")
                {
                    #region 2、查询solr服务器来搜索文件内容
                    string      q      = "text:" + request.Keyword;
                    string      url    = SolrUrl + "select?q=" + HttpUtility.UrlEncode(q) + "&rows=1000000&wt=json&_=" + StringExtension.getTimeStamp(DateTime.Now);
                    HttpClient  client = new HttpClient();
                    string      result = client.GetStringAsync(url).Result;
                    SolrContext sc     = result.JsonDeserialize <SolrContext>();
                    #endregion

                    #region 3、通过solr搜索结果来匹配数据库
                    foreach (var item in sc.response.docs)
                    {
                        FileInfo fi      = new FileInfo(item.uri);
                        string   dirName = fi.Directory.Name;
                        var      query2  = Query.EQ("FileId", dirName);
                        Info     info    = database.GetCollection("info").FindAs <Info>(query2).FirstOrDefault();
                        if (info == null)
                        {
                            continue;
                        }
                        if (info.FileName != fi.Name)
                        {
                            continue;
                        }

                        InfoModel temp = new InfoModel();
                        temp.InfoId = info._id.ToString();
                        temp.Title  = info.Title;
                        Dictionary dic = getArticleClassNameFoo(info.CategoryCode);
                        if (dic != null)
                        {
                            temp.ArticleClass = dic.value;
                        }
                        temp.ArticleCategory = info.CategoryName;
                        temp.Author          = info.Author;

                        string   extStr = info.ArticleType;
                        string[] arr    = extStr.Split('、');
                        if (arr.Length > 0)
                        {
                            temp.FileType = arr[0];
                        }
                        else
                        {
                            temp.FileType = "1176708";
                        }

                        string fileUrl = "/Upload/";
                        if (fi.Extension == ".xls" || fi.Extension == ".xlsx")
                        {
                            fileUrl += "XLS/";
                        }
                        fileUrl      += info.FileId + "/" + info.FileName;
                        temp.FilePath = fileUrl;

                        if (list.Contains(temp))
                        {
                            continue;
                        }
                        list.Add(temp);
                    }
                    #endregion
                }

                rsp.Data = list;
                if (request.UserName == "CategoryCode")
                {
                    List <InfoModel> result = list.Skip((request.CurrentPage - 1) * PageSize).Take(PageSize).ToList();
                    int count = list.Count / PageSize;
                    if (list.Count % PageSize > 0)
                    {
                        count += 1;
                    }
                    rsp.PagesCount = count;
                    rsp.Data       = result;
                }

                return(Ok(rsp));
            }
            else
            {
                Guid g = new Guid();
                if (Guid.TryParse(request.Keyword, out g))
                {
                    Dictionary    dic     = _dictionary.GetDictionaryById(g.ToString());
                    List <string> nodeIds = new List <string>();
                    nodeIds.Add(dic.nodeId);
                    Foo(nodeIds, dic);

                    Response <List <Info> > response = new Response <List <Info> >();
                    var         list   = database.GetCollection <Info>("info").FindAll().ToList();
                    List <Info> result = new List <Info>();
                    foreach (string item in nodeIds)
                    {
                        Info temp = list.Find(p => p.CategoryCode == item);
                        if (temp != null)
                        {
                            result.Add(temp);
                        }
                    }
                    response.Data = result;
                    return(Ok(response));
                }
                else
                {
                    Response <List <Info> > response = new Response <List <Info> >();
                    var list = database.GetCollection <Info>("info").FindAll().ToList();
                    if (!string.IsNullOrEmpty(request.Keyword))
                    {
                        list = list.FindAll(p => p.Title.Contains(request.Keyword) || p.Html.Contains(request.Keyword) || p.Author.Contains(request.Keyword));
                    }
                    response.Data = list;
                    return(Ok(response));
                }
            }
        }
Esempio n. 24
0
        public static BsonValue Create(this BsonType bsonType, object o)
        {
            BsonValue value = BsonNull.Value;

            try
            {
                switch (bsonType)
                {
                case BsonType.EndOfDocument:
                    break;

                case BsonType.Double:
                    value = BsonDouble.Create(o);
                    break;

                case BsonType.String:
                    value = BsonString.Create(o);
                    break;

                case BsonType.Document:
                    value = BsonDocument.Create(o);
                    break;

                case BsonType.Array:
                    value = BsonArray.Create(o);
                    break;

                case BsonType.Binary:
                    value = BsonBinaryData.Create(o);
                    break;

                case BsonType.Undefined:
                    break;

                case BsonType.ObjectId:
                    value = BsonObjectId.Create(o);
                    break;

                case BsonType.Boolean:
                    value = BsonBoolean.Create(o);
                    break;

                case BsonType.DateTime:
                    value = BsonDateTime.Create(o);
                    break;

                case BsonType.Null:
                    value = BsonNull.Value;
                    break;

                case BsonType.RegularExpression:
                    value = BsonRegularExpression.Create(o);
                    break;

                case BsonType.JavaScript:
                    value = BsonJavaScript.Create(o);
                    break;

                case BsonType.Symbol:
                    value = BsonSymbol.Create(o);
                    break;

                case BsonType.JavaScriptWithScope:
                    value = BsonJavaScriptWithScope.Create(o);
                    break;

                case BsonType.Int32:
                    value = BsonInt32.Create(o);
                    break;

                case BsonType.Timestamp:
                    value = BsonTimestamp.Create(o);
                    break;

                case BsonType.Int64:
                    value = BsonInt64.Create(o);
                    break;

                case BsonType.MaxKey:
                    value = BsonValue.Create(o);
                    break;

                case BsonType.MinKey:
                    value = BsonValue.Create(o);
                    break;
                }
            }
            catch
            {
            }

            return(value);
        }
Esempio n. 25
0
        public override void Handle(params object[] args)
        {
            //分析参数
            string  assetid      = (string)args[0];
            UInt32  height       = UInt32.Parse((string)args[1]);
            string  sendAssetid  = (string)args[2];
            decimal sendCount    = decimal.Parse((string)args[3]);
            string  snapshopColl = (string)args[4];

            //获取快照资产的详情
            AssetInfo assetInfo = GetAssetInfo(assetid);

            //获取已有地址个数 分段处理
            var count    = mongoHelper.GetDataCount(Config.Ins.Address_Conn, Config.Ins.Address_DB, Config.Ins.Address_Coll);
            var looptime = count / 10000 + 1;

            for (var i = 1; i < looptime + 1; i++)
            {
                MyJson.JsonNode_Array Ja_addressInfo = mongoHelper.GetDataPages(Config.Ins.Address_Conn, Config.Ins.Address_DB, Config.Ins.Address_Coll, "{}", 10000, i);
                for (var ii = 0; ii < Ja_addressInfo.Count; ii++)
                {
                    string address = JsonConvert.DeserializeObject <Address>(Ja_addressInfo[ii].ToString()).addr;
                    //获取这个address的所有的utxo
                    string findFliter = ToolHelper.RemoveUndefinedParams(JsonConvert.SerializeObject(new UTXO()
                    {
                        addr = address, asset = assetid
                    }));
                    MyJson.JsonNode_Array utxos = mongoHelper.GetData(Config.Ins.UTXO_Conn, Config.Ins.UTXO_DB, Config.Ins.UTXO_Coll, findFliter);

                    decimal value = 0;
                    foreach (MyJson.JsonNode_Object j in utxos)
                    {
                        UTXO uTXO = JsonConvert.DeserializeObject <UTXO>(j.ToString());
                        if (uTXO.createHeight <= height && (uTXO.useHeight > height || uTXO.useHeight == -1))
                        {
                            value += (decimal)uTXO.value;
                        }
                    }
                    deleRuntime(((i - 1) * 10000 + ii) + "/" + count);
                    if (value > 0)
                    {
                        Snapshot snapshot = new Snapshot();
                        snapshot.addr        = address;
                        snapshot.assetid     = assetid;
                        snapshot.balance     = BsonDecimal128.Create(value);
                        snapshot.send        = BsonDecimal128.Create(((value / assetInfo.totoalSupply) * sendCount).ToString("F8"));
                        snapshot.totalSend   = BsonDecimal128.Create(sendCount);
                        snapshot.sendAssetid = sendAssetid;
                        snapshot.txid        = "";
                        snapshot.height      = height;
                        snapshot.applied     = false;
                        findFliter           = ToolHelper.RemoveUndefinedParams(JsonConvert.SerializeObject(new Snapshot()
                        {
                            addr = address
                        }));
                        mongoHelper.ReplaceData(Config.Ins.Snapshot_Conn, Config.Ins.Snapshot_DB, snapshopColl, findFliter, BsonDocument.Create(snapshot));
                    }
                }
            }


            //更新最新的分红数据表
            mongoHelper.DelData(Config.Ins.Snapshot_Conn, Config.Ins.Snapshot_DB, Config.Ins.CurrentDb_Coll, "{}");
            mongoHelper.InsetOne(Config.Ins.Snapshot_Conn, Config.Ins.Snapshot_DB, Config.Ins.CurrentDb_Coll, BsonDocument.Parse("{CurrentColl:\"" + snapshopColl + "\"}"));
            deleResult("完成");
        }