public override OpRes makeQuery(object param, GMUser user, QueryCondition queryCond)
    {
        ParamQueryRecharge p = (ParamQueryRecharge)param;

        int          condCount = 0;
        PlatformInfo pinfo     = null;

        if (!string.IsNullOrEmpty(p.m_param))
        {
            switch (p.m_way)
            {
            case QueryWay.by_way0:     //  通过玩家id查询
            {
                int val = -1;
                if (!int.TryParse(p.m_param, out val))
                {
                    return(OpRes.op_res_param_not_valid);
                }
                Dictionary <string, object> ret = QueryBase.getPlayerProperty(val, user, s_field);
                if (ret == null)
                {
                    return(OpRes.op_res_not_found_data);
                }
                if (!ret.ContainsKey("platform"))
                {
                    return(OpRes.op_res_failed);
                }

                // 取玩家ID所在平台
                string platName = Convert.ToString(ret["platform"]);
                queryCond.addQueryCond("PlayerId", val);

                pinfo = ResMgr.getInstance().getPlatformInfoByName(platName);

                // 获取服务器ID

                /*DbServerInfo dbInfo = ResMgr.getInstance().getDbInfo(user.m_dbIP);
                 * if (dbInfo != null)
                 * {
                 *  queryCond.addQueryCond("ServerId", dbInfo.m_serverId);
                 * }*/
            }
            break;

            case QueryWay.by_way1:     //  通过账号查询
            {
                Dictionary <string, object> ret = QueryBase.getPlayerPropertyByAcc(p.m_param, user, s_field);
                if (ret == null)
                {
                    return(OpRes.op_res_not_found_data);
                }
                if (!ret.ContainsKey("platform"))
                {
                    return(OpRes.op_res_failed);
                }

                // 取玩家账号所在平台,然后从相应的平台去查
                string platName = Convert.ToString(ret["platform"]);
                queryCond.addQueryCond("Account", p.m_param);

                pinfo = ResMgr.getInstance().getPlatformInfoByName(platName);

                // 获取服务器ID

                /* DbServerInfo dbInfo = ResMgr.getInstance().getDbInfo(user.m_dbIP);
                 * if (dbInfo != null)
                 * {
                 *   queryCond.addQueryCond("ServerId", dbInfo.m_serverId);
                 * }*/
            }
            break;

            case QueryWay.by_way2:     //  通过订单号查询
            {
                pinfo = ResMgr.getInstance().getPlatformInfo(p.m_platIndex);
                queryCond.addQueryCond("OrderID", p.m_param);
            }
            break;

            default:
            {
                return(OpRes.op_res_failed);
            }
            }
            condCount++;
        }
        else
        {
            pinfo = ResMgr.getInstance().getPlatformInfo(p.m_platIndex);

            // 获取服务器ID

            /*DbServerInfo dbInfo = ResMgr.getInstance().getDbInfo(user.m_dbIP);
             * if (dbInfo != null)
             * {
             *  queryCond.addQueryCond("ServerId", dbInfo.m_serverId);
             * }*/
        }

        if (pinfo == null)
        {
            return(OpRes.op_res_need_sel_platform);
        }

        if (!m_items.ContainsKey(pinfo.m_engName))
        {
            return(OpRes.op_res_not_found_data);
        }

        m_rbase = m_items[pinfo.m_engName];

        m_platInfo.m_tableName = pinfo.m_tableName;
        m_platInfo.m_platName  = pinfo.m_engName;

        if (queryCond.isExport())
        {
            queryCond.addCond("table", m_platInfo.m_tableName);
            queryCond.addCond("plat", m_platInfo.m_platName);
        }

        if (p.m_time != "")
        {
            DateTime mint = DateTime.Now, maxt = DateTime.Now;
            bool     res = Tool.splitTimeStr(p.m_time, ref mint, ref maxt);
            if (!res)
            {
                return(OpRes.op_res_time_format_error);
            }

            condCount++;
            if (queryCond.isExport())
            {
                queryCond.addCond("time", p.m_time);
            }
            else
            {
                IMongoQuery imq1 = Query.LT("PayTime", BsonValue.Create(maxt));
                IMongoQuery imq2 = Query.GTE("PayTime", BsonValue.Create(mint));
                queryCond.addImq(Query.And(imq1, imq2));
            }
        }

        if (p.m_result > 0)
        {
            queryCond.addQueryCond("Process", p.m_result == 1 ? true : false);
        }
        if (!string.IsNullOrEmpty(p.m_range))
        {
            if (!Tool.isTwoNumValid(p.m_range))
            {
                return(OpRes.op_res_param_not_valid);
            }

            if (queryCond.isExport())
            {
                queryCond.addCond("range", p.m_range);
            }
            else
            {
                List <int> range = new List <int>();
                Tool.parseNumList(p.m_range, range);
                IMongoQuery timq1  = Query.LTE("RMB", BsonValue.Create(range[1]));
                IMongoQuery timq2  = Query.GTE("RMB", BsonValue.Create(range[0]));
                IMongoQuery tmpImq = Query.And(timq1, timq2);
                queryCond.addImq(tmpImq);
            }
        }

        if (condCount == 0)
        {
            return(OpRes.op_res_need_at_least_one_cond);
        }

        return(OpRes.opres_success);
    }
Exemplo n.º 2
0
        private InvoiceAutoNumberDefault GetInvoiceAutoNumberDefault()
        {
            MongoCollection <InvoiceAutoNumberDefault> collection = mongo.MongoDatabase.GetCollection <InvoiceAutoNumberDefault>(typeof(InvoiceAutoNumberDefault).Name);
            InvoiceAutoNumberDefault invoiceAutoNumber            = collection.FindOneAs <InvoiceAutoNumberDefault>(Query.And(
                                                                                                                        Query.EQ("_id", BsonValue.Create(typeof(InvoiceAutoNumberDefault).Name)),
                                                                                                                        Query.EQ(COMPANY_ID_FIELD, BsonValue.Create(companyId))));

            if (invoiceAutoNumber == null)
            {
                invoiceAutoNumber = new InvoiceAutoNumberDefault(typeof(InvoiceAutoNumberDefault).Name, companyId);
                collection.Save <InvoiceAutoNumberDefault>(invoiceAutoNumber);
            }

            return(invoiceAutoNumber);
        }
Exemplo n.º 3
0
 public T GetById <T, ID>(ID id) where T : class
 {
     return(GetCollection <T>().FindOneByIdAs <T>(BsonValue.Create(id)));
 }
Exemplo n.º 4
0
        public Result BatchAdd(InterfaceSetting interfaceSetting, IEnumerable <BsonDocument> bsonsList)
        {
            if (interfaceSetting == null)
            {
                return(Result.Error("接口设置参数不能为空"));
            }

            if (bsonsList == null || !bsonsList.Any())
            {
                return(Result.Success($"没有任何数据需要插入"));
            }

            //获取全部接口校验
            var verificationDic = _interfaceVerificationRepository.GetMetaFieldUpperKeyDicByInterfaceVerificationId(interfaceSetting.InterfaceVerificationId);

            //获取到字段列表以编码为Key大写的字典
            var metaFields = _metaFieldRepository.GetMetaFieldShortCodeUpperDicByMetaObjectId(interfaceSetting.MetaObjectId);

            List <BsonDocument> insertBsonsList = new List <BsonDocument>(bsonsList.Count());

            foreach (var bsonDocument in bsonsList)
            {
                if (bsonDocument == null)
                {
                    return(Result.Error("数据为空,插入终止"));
                }

                BsonDocument bsonElementsToAdd = new BsonDocument();

                foreach (var bsonElement in bsonDocument)
                {
                    string upperKey = bsonElement.Name.ToUpperInvariant();

                    if (!metaFields.ContainsKey(upperKey))
                    {
                        continue;
                    }

                    //校验值是否符合接口校验设置
                    if (verificationDic.ContainsKey(upperKey))
                    {
                        var verification = verificationDic[upperKey];
                        if (!_interfaceVerificationService.IsMatch(verification, Convert.ToString(bsonElement.Value)))
                        {
                            return(Result.Error(!string.IsNullOrEmpty(verification.VerificationTips) ? verification.VerificationTips : $"字段[{bsonElement.Name}]传递的值[{bsonElement.Value}]格式不正确"));
                        }
                    }

                    //检查字段的值是否符合字段类型
                    var checkResult = _metaFieldService.CheckAndGetFieldValueByFieldType(metaFields[upperKey], bsonElement.Value);

                    if (checkResult.IsSuccess)
                    {
                        bsonElementsToAdd.Add(new BsonElement(metaFields[upperKey].ShortCode, BsonValue.Create(checkResult.Data)));
                    }
                    else
                    {
                        return(Result.Error($"字段[{bsonElement.Name}]传递的值[{bsonElement.Value}]不符合字段定义的类型"));
                    }
                }

                //获取系统内置的bson元素
                var systemBsonDocument = _metaFieldService.GetSystemFieldBsonDocument();

                //设置系统字段及其默认值
                foreach (var presetBsonElement in systemBsonDocument)
                {
                    //如果传入的字段已经有了,那么这里就不预置了
                    if (!bsonElementsToAdd.Contains(presetBsonElement.Name))
                    {
                        bsonElementsToAdd.Add(presetBsonElement);
                    }
                }

                //补充字段
                bsonElementsToAdd.SetElement(new BsonElement("MetaObject", interfaceSetting.MetaObjectCode));

                if (bsonElementsToAdd.Any())
                {
                    insertBsonsList.Add(bsonElementsToAdd);
                }
            }

            if (insertBsonsList.Any())
            {
                _chameleonDataDbContext.GetCollectionBson(interfaceSetting.MetaObjectCode).InsertMany(insertBsonsList);
            }

            return(Result.Success($"插入成功! 成功{insertBsonsList.Count}条,失败{bsonsList.Count() - insertBsonsList.Count}条."));
        }
Exemplo n.º 5
0
        private InvoiceAutoNumberYearly GetInvoiceAutoNumberYearly()
        {
            MongoCollection <InvoiceAutoNumberYearly> collection = mongo.MongoDatabase.GetCollection <InvoiceAutoNumberYearly>(typeof(InvoiceAutoNumberYearly).Name);
            InvoiceAutoNumberYearly invoiceAutoNumber            = collection.FindOneAs <InvoiceAutoNumberYearly>(Query.And(
                                                                                                                      Query.EQ("_id", BsonValue.Create(transactionDate.Year.ToString())),
                                                                                                                      Query.EQ(COMPANY_ID_FIELD, BsonValue.Create(companyId))));

            if (invoiceAutoNumber == null)
            {
                invoiceAutoNumber = new InvoiceAutoNumberYearly(transactionDate.Year.ToString(), companyId, transactionDate.Year);
                collection.Save <InvoiceAutoNumberYearly>(invoiceAutoNumber);
            }

            return(invoiceAutoNumber);
        }
Exemplo n.º 6
0
        public async Task Update()
        {
            //    Filter    ============Update============
            // [{_id : 1}, {$set: {"name" : "Gabriel", "age" : 21}}]

            var filter = Builders <T> .Filter.Where(obj => obj.Id.Equals(Id)).RenderToBsonDocument().ToJson();//Where(iCompareCriteria).ToJson();

            var typeName = typeof(T).Name;

            var updObj = new BsonDocument();

            if (CAConfig.CLOUD_API_MODE == "CLIENT")
            {
                var valRes = await Validate(CADocumentModification.Update);

                if (valRes.Count > 0)
                {
                    InvalidFields = valRes;
                    return;
                }
                InvalidFields = new List <CtrlValidationResult>();
            }

            foreach (var propInfo in GetAllProperties())
            {
                var propName = propInfo.Name;
                var propVal  = propInfo.GetValue(this);

                if (propName == "Id")
                {
                    continue;
                }

                if (propInfo.PropertyType.GetTypeInfo().BaseType != null &&
                    propInfo.PropertyType.GetTypeInfo().BaseType.IsGenericType&&
                    propInfo.PropertyType.GetTypeInfo().BaseType ==
                    typeof(CADocument <>).MakeGenericType(propInfo.PropertyType))
                {
                    var propObj = propInfo.GetValue(this);
                    if (propObj == null)
                    {
                        continue;
                    }

                    var propValDoc = propInfo.PropertyType.GetMethod("ToNestedDocument").Invoke(propObj, null);
                    updObj[propName] = BsonValue.Create(propValDoc);
                }
                else if (propVal is decimal)
                {
                    var stringRep = Convert.ToString(propVal);
                    updObj[propName] = BsonValue.Create(stringRep);
                    //throw new Exception("Decimals are not supported by cloudapi, sorry! (Use double instead)");
                }
                else if (propVal is Dictionary <string, string> )
                {
                    var saveString = new StringBuilder();
                    foreach (var kv in ((Dictionary <string, string>)propVal))
                    {
                        saveString.Append($"{kv.Key}§${kv.Value}$-§");
                    }
                    updObj[propName] = BsonValue.Create(saveString.ToString());
                }
                else
                {
                    updObj[propName] = BsonValue.Create(propVal);
                }
            }

            var updObjJson = $"[{filter}, {{$set: {updObj.ToJson()}}}]";
            var cmd        = $"OPCODE=CLOUD_API_DATA&COLLECTION={typeName}&ACTION=UPDATE#UDOC={updObjJson}";

            await CAHttpManager.Instance.HttpPostAsync(CAConfig.CLOUD_API_URL, cmd);
        }
Exemplo n.º 7
0
 private void MarkCommitAsProcessed(Guid commitId)
 {
     _commits.Update(Query.EQ("CommitId", BsonValue.Create(commitId)),
                     Update.Push("Processed", BsonValue.Create(true)));
 }
Exemplo n.º 8
0
        static void CopyCollection(string databaseName, string sourceCollectionName, string targetCollectionName)
        {
            MongoClientSettings mcs = new MongoClientSettings()
            {
                //Server = new MongoServerAddress("141.20.100.49", 27017)
                Server = new MongoServerAddress("127.0.0.1", 27017)
            };
            var client           = new MongoClient(mcs);
            var database         = client.GetDatabase(databaseName);
            var sourceCollection = database.GetCollection <BsonDocument>(sourceCollectionName);
            var targetCollection = database.GetCollection <BsonDocument>(targetCollectionName);

            var noFilter = new BsonDocument();
            var cursor   = sourceCollection.Find(noFilter).ToCursor();

            List <BsonDocument> buffer = new List <BsonDocument>();
            int bufCounter             = 0;
            int totalCounts            = 0;
            int missingCounts          = 0;

            string[] fieldNames = new string[]
            {
                "time", "headline", "body", "CompanyName"
            };

            while (cursor.MoveNext())
            {
                foreach (BsonDocument doc in cursor.Current)
                {
                    #region Conversion
                    BsonDocument bd            = new BsonDocument();
                    bool         fieldComplete = true;
                    foreach (string fieldName in fieldNames)
                    {
                        if (!doc.Contains(fieldName))
                        {
                            fieldComplete = false;
                            break;
                        }
                        object result       = null;
                        string fieldContent = doc[fieldName].ToString();
                        switch (fieldName)
                        {
                        case "time":
                            if (DateTime.TryParse(fieldContent, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime dtParseResult))
                            {
                                result = dtParseResult;
                            }
                            else
                            {
                                fieldComplete = false;
                            }
                            break;

                        case "CompanyName":
                            result = fieldContent.Trim();
                            break;

                        default:
                            result = fieldContent.Replace('\n', ' ').Trim();
                            break;
                        }
                        bd.Add(fieldName, BsonValue.Create(result));
                    }

                    if (!fieldComplete)
                    {
                        missingCounts++;
                        continue;
                    }

                    #endregion

                    buffer.Add(bd);
                    bufCounter++;
                    totalCounts++;

                    if (bufCounter > 100)
                    {
                        targetCollection.InsertMany(buffer);
                        Console.WriteLine($"has written {totalCounts}");
                        buffer.Clear();
                        bufCounter = 0;
                    }
                }
            }
            targetCollection.InsertMany(buffer);
            Console.WriteLine($"has written {totalCounts}. missing counts {missingCounts}");
        }
Exemplo n.º 9
0
        static void CreateDateTimeField()
        {
            //var client = new MongoClient("mongodb+srv://<username>:<password>@<cluster-address>/test?w=majority");
            MongoClientSettings mcs = new MongoClientSettings()
            {
                //Server = new MongoServerAddress("141.20.100.49", 27017)
                Server = new MongoServerAddress("127.0.0.1", 27017)
            };

            var client     = new MongoClient(mcs);
            var database   = client.GetDatabase("factiva");
            var collection = database.GetCollection <BsonDocument>("statis_data3");

            var noFilter = new BsonDocument();
            var cursor   = collection.Find(noFilter).ToCursor();

            while (cursor.MoveNext())
            {
                foreach (BsonDocument doc in cursor.Current)
                {
                    // do something with the documents

                    ObjectId id = doc.GetValue("_id").AsObjectId;
                    if (doc.Contains("DateTime"))
                    {
                        DateTime existedDt = doc["DateTime"].ToUniversalTime();
                        Console.WriteLine($"{existedDt.ToString()} {id.ToString()} existed. Skip");
                        continue;
                    }

                    string date   = doc.GetValue("DATE").AsString;
                    Match  result = Regex.Match(date, @"^(\d+)/(\d+)/(\d+)");

                    if (result.Groups.Count != 4)
                    {
                        continue;
                    }

                    int month = int.Parse(result.Groups[1].ToString());
                    int day   = int.Parse(result.Groups[2].ToString());
                    int year  = int.Parse(result.Groups[3].ToString());

                    if (year > 30)
                    {
                        year += 1900;
                    }
                    else
                    {
                        year += 2000;
                    }

                    DateTime  dt     = new DateTime(year, month, day, 0, 0, 0, DateTimeKind.Utc);
                    BsonValue bv     = BsonValue.Create(dt);
                    var       update = new BsonDocument("$set", new BsonDocument("DateTime", bv));

                    var filter       = new BsonDocument("_id", id);
                    var updateResult = collection.UpdateOne(filter, update);

                    Console.WriteLine($"{dt.ToString()} {id.ToString()}");
                }
            }
        }
 public Task RemoveEvent(TEventKey eventId)
 {
     _events.Remove(Query.EQ("_id", BsonValue.Create(eventId)));
     return(RemoveFromAllFeeds(eventId));
 }
Exemplo n.º 11
0
 public virtual T Get(TId id)
 {
     return(Collection.FindOneById(BsonValue.Create(id)));
 }
Exemplo n.º 12
0
        public void TestLookupActualType()
        {
            var actualType = BsonSerializer.LookupActualType(typeof(A), BsonValue.Create("C"));

            Assert.Equal(typeof(C), actualType);
        }
Exemplo n.º 13
0
 public void SetProperty(object entity, string propertyName, object propertyValue)
 {
     (entity as BsonDocument).Add(propertyName, BsonValue.Create(ConvertValue(propertyValue)));
 }
Exemplo n.º 14
0
 private static IMongoQuery GetQuery(string name, Identity?groupId)
 {
     return(Query.And(
                Query.EQ("Name", BsonValue.Create(name)),
                Query.EQ("GroupId", groupId.ToBson())));
 }
            private BsonValue BuildValue(Expression node)
            {
                switch (node.NodeType)
                {
                case ExpressionType.Add:
                case ExpressionType.AddChecked:
                    return(BuildAdd((BinaryExpression)node));

                case ExpressionType.And:
                case ExpressionType.AndAlso:
                    return(BuildOperation((BinaryExpression)node, "$and", true));

                case ExpressionType.ArrayLength:
                    return(new BsonDocument("$size", ResolveValue(((UnaryExpression)node).Operand)));

                case ExpressionType.Call:
                    return(BuildMethodCall((MethodCallExpression)node));

                case ExpressionType.Coalesce:
                    return(BuildOperation((BinaryExpression)node, "$ifNull", false));

                case ExpressionType.Conditional:
                    return(BuildConditional((ConditionalExpression)node));

                case ExpressionType.Constant:
                    var value       = BsonValue.Create(((ConstantExpression)node).Value);
                    var stringValue = value as BsonString;
                    if (stringValue != null && stringValue.Value.StartsWith("$"))
                    {
                        value = new BsonDocument("$literal", value);
                    }
                    // TODO: there may be other instances where we should use a literal...
                    // but I can't think of any yet.
                    return(value);

                case ExpressionType.Convert:
                case ExpressionType.ConvertChecked:
                    return(BuildValue(((UnaryExpression)node).Operand));

                case ExpressionType.Divide:
                    return(BuildOperation((BinaryExpression)node, "$divide", false));

                case ExpressionType.Equal:
                    return(BuildOperation((BinaryExpression)node, "$eq", false));

                case ExpressionType.GreaterThan:
                    return(BuildOperation((BinaryExpression)node, "$gt", false));

                case ExpressionType.GreaterThanOrEqual:
                    return(BuildOperation((BinaryExpression)node, "$gte", false));

                case ExpressionType.LessThan:
                    return(BuildOperation((BinaryExpression)node, "$lt", false));

                case ExpressionType.LessThanOrEqual:
                    return(BuildOperation((BinaryExpression)node, "$lte", false));

                case ExpressionType.MemberAccess:
                    return(BuildMemberAccess((MemberExpression)node));

                case ExpressionType.Modulo:
                    return(BuildOperation((BinaryExpression)node, "$mod", false));

                case ExpressionType.Multiply:
                case ExpressionType.MultiplyChecked:
                    return(BuildOperation((BinaryExpression)node, "$multiply", true));

                case ExpressionType.New:
                    return(BuildNew((NewExpression)node));

                case ExpressionType.Not:
                    return(BuildNot((UnaryExpression)node));

                case ExpressionType.NotEqual:
                    return(BuildOperation((BinaryExpression)node, "$ne", false));

                case ExpressionType.Or:
                case ExpressionType.OrElse:
                    return(BuildOperation((BinaryExpression)node, "$or", true));

                case ExpressionType.Subtract:
                case ExpressionType.SubtractChecked:
                    return(BuildOperation((BinaryExpression)node, "$subtract", false));

                case ExpressionType.Extension:
                    var mongoExpression = node as MongoExpression;
                    if (mongoExpression != null)
                    {
                        switch (mongoExpression.MongoNodeType)
                        {
                        case MongoExpressionType.Aggregation:
                            return(BuildAggregation((AggregationExpression)node));
                        }
                    }
                    break;
                }

                var message = string.Format("{0} is an unsupported node type in an $project or $group pipeline operator.", node.NodeType);

                throw new NotSupportedException(message);
            }
Exemplo n.º 16
0
 public T Find <T>(object id)
 {
     return(this.GetCollection <T>()
            .FindOneById(BsonValue.Create(id)));
 }
Exemplo n.º 17
0
        public void TestCreateNull()
        {
            object obj = null;

            Assert.Same(BsonNull.Value, BsonValue.Create(obj));
        }
Exemplo n.º 18
0
        public static BsonValue ToBson(this JToken source)
        {
            switch (source.Type)
            {
            case JTokenType.Object:
                return(((JObject)source).ToBson());

            case JTokenType.Array:
                return(((JArray)source).ToBson());

            case JTokenType.Integer:
                return(BsonValue.Create(((JValue)source).Value));

            case JTokenType.Float:
                return(BsonValue.Create(((JValue)source).Value));

            case JTokenType.String:
                return(BsonValue.Create(((JValue)source).Value));

            case JTokenType.Boolean:
                return(BsonValue.Create(((JValue)source).Value));

            case JTokenType.Null:
                return(BsonNull.Value);

            case JTokenType.Undefined:
                return(BsonUndefined.Value);

            case JTokenType.Bytes:
                return(BsonValue.Create(((JValue)source).Value));

            case JTokenType.Guid:
                return(BsonValue.Create(((JValue)source).ToString()));

            case JTokenType.Uri:
                return(BsonValue.Create(((JValue)source).ToString()));

            case JTokenType.TimeSpan:
                return(BsonValue.Create(((JValue)source).ToString()));

            case JTokenType.Date:
            {
                var value = ((JValue)source).Value;

                if (value is DateTime dateTime)
                {
                    return(dateTime.ToString("yyyy-MM-ddTHH:mm:ssK", CultureInfo.InvariantCulture));
                }
                else if (value is DateTimeOffset dateTimeOffset)
                {
                    if (dateTimeOffset.Offset == TimeSpan.Zero)
                    {
                        return(dateTimeOffset.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssK", CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        return(dateTimeOffset.ToString("yyyy-MM-ddTHH:mm:ssK", CultureInfo.InvariantCulture));
                    }
                }
                else
                {
                    return(value.ToString());
                }
            }
            }

            throw new NotSupportedException($"Cannot convert {source.GetType()} to Bson.");
        }
Exemplo n.º 19
0
        public async Task Save()
        {
            var requestBuilder = new StringBuilder();
            var bson           = new BsonDocument();
            var typeName       = GetType().Name;

            var exists = (await FindOne(doc => doc.Id.Equals(Id))) != null;

            if (exists)
            {
                await Update();

                return;
            }

            if (CAConfig.CLOUD_API_MODE == "CLIENT")
            {
                var valRes = await Validate(CADocumentModification.Create);

                if (valRes.Count > 0)
                {
                    InvalidFields = valRes;
                    return;
                }
                InvalidFields = new List <CtrlValidationResult>();
            }

            requestBuilder.Append($"OPCODE=CLOUD_API_DATA&COLLECTION={typeName}&ACTION=CREATE#CDOC=");

            foreach (var propInfo in GetAllProperties())
            {
                var propName = propInfo.Name;
                var propVal  = propInfo.GetValue(this);

                if (propName == "Id")
                {
                    propName = "_id";                   //Umbenennen für JSON Serialisierung
                }
                if (propInfo.PropertyType.GetTypeInfo().BaseType != null &&
                    propInfo.PropertyType.GetTypeInfo().BaseType.IsGenericType&&
                    propInfo.PropertyType.GetTypeInfo().BaseType ==
                    typeof(CADocument <>).MakeGenericType(propInfo.PropertyType))
                {
                    var propObj = propInfo.GetValue(this);
                    if (propObj == null)
                    {
                        continue;
                    }

                    var propValDoc = propInfo.PropertyType.GetMethod("ToNestedDocument").Invoke(propObj, null);
                    bson[propName] = BsonValue.Create(propValDoc);
                }
                else if (propVal is decimal)
                {
                    var stringRep = Convert.ToString(propVal);
                    bson[propName] = BsonValue.Create(stringRep);
                    //throw new Exception("Decimals are not supported by cloudapi, sorry! (Use double instead)");
                }
                else if (propVal is Dictionary <string, string> )
                {
                    var saveString = new StringBuilder();
                    foreach (var kv in ((Dictionary <string, string>)propVal))
                    {
                        saveString.Append($"{kv.Key}§${kv.Value}$§");
                    }
                    bson[propName] = BsonValue.Create(saveString.ToString());
                }
                else
                {
                    bson[propName] = BsonValue.Create(propVal);
                }
            }

            requestBuilder.Append(bson.ToJson().Replace("\\", ""));
            var res = await CAHttpManager.Instance.HttpPostAsync(CAConfig.CLOUD_API_URL, requestBuilder.ToString());

            var resDoc = BsonDocument.Parse(res);

            Id = ObjectId.Parse(Convert.ToString(resDoc.GetValue("_id")));
        }
Exemplo n.º 20
0
        /// <summary>
        /// 根据标识属性删除对象
        /// </summary>
        /// <param name="id"></param>
        public void MakeTransient(int id)
        {
            var collection = MongoDataBase.GetCollection <T>(DataBase);

            collection.Remove(Query.EQ("_id", BsonValue.Create(id)));
        }
Exemplo n.º 21
0
 /// <inheritdoc />
 public virtual Task <TModel> this[TKey index] => _collection
 .Find(new BsonDocument("_id", BsonValue.Create(index)))
 .FirstAsync();
Exemplo n.º 22
0
    // 开始统计
    public override OpRes doStat(object param, GMUser user)
    {
        ParamQuery p = (ParamQuery)param;

        if (string.IsNullOrEmpty(p.m_time))
        {
            return(OpRes.op_res_time_format_error);
        }

        DateTime mint = DateTime.Now, maxt = DateTime.Now;
        bool     res = Tool.splitTimeStr(p.m_time, ref mint, ref maxt);

        if (!res)
        {
            return(OpRes.op_res_time_format_error);
        }

        m_result.Clear();

        int serverId = DBMgr.getInstance().getSpecialServerId(DbName.DB_ACCOUNT);

        if (serverId == -1)
        {
            return(OpRes.op_res_failed);
        }

        IMongoQuery imq1    = Query.LT("genTime", BsonValue.Create(maxt));
        IMongoQuery imq2    = Query.GTE("genTime", BsonValue.Create(mint));
        IMongoQuery imqTime = Query.And(imq1, imq2);

        MapReduceResult map_result = DBMgr.getInstance().executeMapReduce(TableName.CHANNEL_TD,
                                                                          serverId,
                                                                          DbName.DB_ACCOUNT,
                                                                          imqTime,
                                                                          MapReduceTable.getMap("LTV"),
                                                                          MapReduceTable.getReduce("LTV"));

        if (map_result != null)
        {
            IEnumerable <BsonDocument> bson = map_result.GetResults();
            foreach (BsonDocument d in bson)
            {
                try
                {
                    ResultLTVItem tmp = new ResultLTVItem();
                    tmp.m_genTime = Convert.ToDateTime(d["_id"]).ToLocalTime().ToShortDateString();
                    BsonValue resValue = d["value"];
                    tmp.m_regeditCount       = resValue["regeditCount"].ToInt32();
                    tmp.m_1DayTotalRecharge  = resValue["day1TotalRecharge"].ToInt32();
                    tmp.m_3DayTotalRecharge  = resValue["day3TotalRecharge"].ToInt32();
                    tmp.m_7DayTotalRecharge  = resValue["day7TotalRecharge"].ToInt32();
                    tmp.m_14DayTotalRecharge = resValue["day14TotalRecharge"].ToInt32();
                    tmp.m_30DayTotalRecharge = resValue["day30TotalRecharge"].ToInt32();
                    tmp.m_60DayTotalRecharge = resValue["day60TotalRecharge"].ToInt32();
                    tmp.m_90DayTotalRecharge = resValue["day90TotalRecharge"].ToInt32();

                    m_result.Add(tmp);
                }
                catch (System.Exception ex)
                {
                }
            }
        }
        return(OpRes.opres_success);
    }
Exemplo n.º 23
0
        public Result BatchUpdate(InterfaceSetting interfaceSetting, FilterDefinition <BsonDocument> filter, BsonDocument bsonDocument)
        {
            if (interfaceSetting == null)
            {
                return(Result.Error("接口设置参数不能为空"));
            }

            if (bsonDocument == null)
            {
                return(Result.Error("数据为空,更新终止"));
            }

            //获取全部接口校验
            var verificationDic = _interfaceVerificationRepository.GetMetaFieldUpperKeyDicByInterfaceVerificationId(interfaceSetting.InterfaceVerificationId);

            //获取到字段列表以编码为Key大写的字典
            var metaFields = _metaFieldRepository.GetMetaFieldShortCodeUpperDicByMetaObjectId(interfaceSetting.MetaObjectId);

            BsonDocument bsonElementsToModify = new BsonDocument();

            foreach (var bsonElement in bsonDocument)
            {
                string upperKey = bsonElement.Name.ToUpperInvariant();

                if (!metaFields.ContainsKey(upperKey))
                {
                    continue;
                }

                //校验值是否符合接口校验设置
                if (verificationDic.ContainsKey(upperKey))
                {
                    var verification = verificationDic[upperKey];

                    if (!_interfaceVerificationService.IsMatch(verification, Convert.ToString(bsonElement.Value)))
                    {
                        return(Result.Error(!string.IsNullOrEmpty(verification.VerificationTips) ? verification.VerificationTips : $"字段[{bsonElement.Name}]传递的值[{bsonElement.Value}]格式不正确"));
                    }
                }

                //检查字段的值是否符合字段类型
                var checkResult = _metaFieldService.CheckAndGetFieldValueByFieldType(metaFields[upperKey], bsonElement.Value);

                if (checkResult.IsSuccess)
                {
                    bsonElementsToModify.Add(new BsonElement(metaFields[upperKey].ShortCode, BsonValue.Create(checkResult.Data)));
                }
                else
                {
                    return(Result.Error($"字段[{bsonElement.Name}]传递的值[{bsonElement.Value}]不符合字段定义的类型"));
                }
            }

            //设置更新并执行更新操作
            var updateDefinitions = bsonElementsToModify.Select(item => Builders <BsonDocument> .Update.Set(item.Name, item.Value)).ToArray();

            _chameleonDataDbContext.GetCollectionBson(interfaceSetting.MetaObjectCode).UpdateMany(filter, Builders <BsonDocument> .Update.Combine(updateDefinitions));

            return(Result.Success($"修改成功"));
        }
Exemplo n.º 24
0
        private void ReadValue()
        {
            //bool value = true;
            _type = PBBsonReaderType.Value;
            switch (_bsonType)
            {
            case BsonType.Document:
                WriteLine(2, "ReadStartDocument");
                WriteLine(1, "{");
                //_indent += 2;
                Indent(2);
                _reader.ReadStartDocument();
                _type = PBBsonReaderType.Document;
                //value = false;
                break;

            case BsonType.Array:
                WriteLine(2, "ReadStartArray");
                WriteLine(1, "[");
                //_indent += 2;
                Indent(2);
                _reader.ReadStartArray();
                _type = PBBsonReaderType.Array;
                //value = false;
                break;

            case BsonType.Binary:
                _value = BsonValue.Create(_reader.ReadBytes());
                break;

            case BsonType.Boolean:
                _value = BsonValue.Create(_reader.ReadBoolean());
                break;

            case BsonType.DateTime:
                _value = BsonValue.Create(_reader.ReadDateTime());
                break;

            case BsonType.Double:
                _value = BsonValue.Create(_reader.ReadDouble());
                break;

            case BsonType.Int32:
                _value = BsonValue.Create(_reader.ReadInt32());
                break;

            case BsonType.Int64:
                _value = BsonValue.Create(_reader.ReadInt64());
                break;

            case BsonType.JavaScript:
                _value = BsonValue.Create(_reader.ReadJavaScript());
                break;

            case BsonType.JavaScriptWithScope:
                _value = BsonValue.Create(_reader.ReadJavaScriptWithScope());
                break;

            case BsonType.MaxKey:
                _reader.ReadMaxKey();
                _value = BsonMaxKey.Value;
                break;

            case BsonType.MinKey:
                _reader.ReadMinKey();
                _value = BsonMinKey.Value;
                break;

            case BsonType.Null:
                _reader.ReadNull();
                _value = BsonNull.Value;
                break;

            case BsonType.ObjectId:
                _value = BsonValue.Create(_reader.ReadObjectId());
                break;

            case BsonType.RegularExpression:
                _value = BsonValue.Create(_reader.ReadRegularExpression());
                break;

            case BsonType.String:
                _value = BsonValue.Create(_reader.ReadString());
                break;

            case BsonType.Symbol:
                _value = BsonValue.Create(_reader.ReadSymbol());
                break;

            case BsonType.Timestamp:
                _value = BsonValue.Create(_reader.ReadTimestamp());
                break;

            case BsonType.Undefined:
                _reader.ReadUndefined();
                _value = BsonUndefined.Value;
                break;

            default:
                throw new PBException("error unable to read value type {0}", _bsonType);
            }
            //return value;
        }
Exemplo n.º 25
0
        public InvoiceAutoNumberConfig GetInvoiceAutoNumberConfig(string companyId)
        {
            MongoCollection <InvoiceAutoNumberConfig> collection = mongo.MongoDatabase.GetCollection <InvoiceAutoNumberConfig>(typeof(InvoiceAutoNumberConfig).Name);
            InvoiceAutoNumberConfig cfg = collection.FindOneAs <InvoiceAutoNumberConfig>(Query.And(
                                                                                             Query.EQ("_id", typeof(InvoiceAutoNumberConfig).Name),
                                                                                             Query.EQ(COMPANY_ID_FIELD, BsonValue.Create(companyId))));

            if (cfg == null)
            {
                cfg = new InvoiceAutoNumberConfig(typeof(InvoiceAutoNumberConfig).Name, AutoNumberMode.Default, DEFAULT_PREFIX, companyId);
                collection.Save <InvoiceAutoNumberConfig>(cfg);
            }

            return(cfg);
        }
Exemplo n.º 26
0
        public bool TryMapToBsonValue(object value, out BsonValue bsonValue)
        {
            bsonValue = value is JObject src?BsonDocument.Parse("{_p:" + src + "}")[0] : BsonValue.Create(value);

            return(true);
        }
Exemplo n.º 27
0
        private InvoiceAutoNumberMonthly GetInvoiceAutoNumberMonthly()
        {
            string id = string.Format("{0}{1}", transactionDate.Year.ToString(), transactionDate.Month.ToString().PadLeft(2, '0'));
            MongoCollection <InvoiceAutoNumberMonthly> collection = mongo.MongoDatabase.GetCollection <InvoiceAutoNumberMonthly>(typeof(InvoiceAutoNumberMonthly).Name);
            InvoiceAutoNumberMonthly invoiceAutoNumber            = collection.FindOneAs <InvoiceAutoNumberMonthly>(Query.And(
                                                                                                                        Query.EQ("_id", BsonValue.Create(id)),
                                                                                                                        Query.EQ(COMPANY_ID_FIELD, BsonValue.Create(companyId))));

            if (invoiceAutoNumber == null)
            {
                invoiceAutoNumber = new InvoiceAutoNumberMonthly(id, companyId, transactionDate.Year, transactionDate.Month);
                collection.Save <InvoiceAutoNumberMonthly>(invoiceAutoNumber);
            }

            return(invoiceAutoNumber);
        }
Exemplo n.º 28
0
        static BsonValue ToBsonValue(object value, DocumentInput input, int depth)
        {
            IncSerializationDepth(ref depth);

            if (value == null)
            {
                return(BsonNull.Value);
            }

            PSObject custom;

            value = BaseObject(value, out custom);

            // case: custom
            if (custom != null)
            {
                return(ToBsonDocumentFromProperties(null, custom, input, null, depth));
            }

            // case: BsonValue
            var bson = value as BsonValue;

            if (bson != null)
            {
                return(bson);
            }

            // case: string
            var text = value as string;

            if (text != null)
            {
                return(new BsonString(text));
            }

            // case: document
            var cd = value as IConvertibleToBsonDocument;

            if (cd != null)
            {
                return(cd.ToBsonDocument());
            }

            // case: dictionary
            var dictionary = value as IDictionary;

            if (dictionary != null)
            {
                return(ToBsonDocumentFromDictionary(null, dictionary, input, null, depth));
            }

            // case: collection
            var enumerable = value as IEnumerable;

            if (enumerable != null)
            {
                var array = new BsonArray();
                foreach (var it in enumerable)
                {
                    array.Add(ToBsonValue(it, input, depth));
                }
                return(array);
            }

            // try to create BsonValue
            try
            {
                Register();
                return(BsonValue.Create(value));
            }
            catch (ArgumentException ae)
            {
                if (input == null)
                {
                    throw;
                }

                try
                {
                    value = input.ConvertValue(value);
                }
                catch (RuntimeException re)
                {
                    throw new ArgumentException(                     //! use this type
                              string.Format(null, @"Converter script was called on ""{0}"" and failed with ""{1}"".", ae.Message, re.Message), re);
                }

                if (value == null)
                {
                    throw;
                }

                // do not call converter twice
                return(ToBsonValue(value, null, depth));
            }
        }
Exemplo n.º 29
0
 public BsonValue GetDocumentBsonKey()
 {
     return(BsonValue.Create(GetDocumentKey()));
 }
        public async Task TestPutAsyncSuccess()
        {
            var repository = Substitute.For <ISiteAvailabilityRepository>();
            var controller = new SiteAvailabilityController(repository);
            var id         = Guid.NewGuid();
            var site       = new Site {
                Id = id, Url = "url1", IsAvailable = false
            };

            repository.UpdateSiteUrlAsync(id, site.Url).Returns(Task.FromResult <UpdateResult>(new UpdateResult.Acknowledged(1, 1, BsonValue.Create(id))));
            var result = await controller.PutAsync(id.ToString(), site);

            Assert.IsTrue(result is OkResult);
        }