예제 #1
0
        public void SerializeOpQueryMessage()
        {
            const Int32 requestId = 1;
            const Int32 responseTo = 0;
            const OpQueryMessage.OpQueryFlags flags = OpQueryMessage.OpQueryFlags.AwaitData;
            const String fullCollectionName = "reactive.coll";
            const Int32 numberToSkip = 0;
            const Int32 numberToReturn = 1;

            var serializer = new BsonSerializer(ReflectionCache.None);
            var rawQuery = serializer.Serialize(new Query {id = 3});

            var expected = new Byte[]
                {
                    55, 0, 0, 0,
                    1, 0, 0, 0,
                    0, 0, 0, 0,
                    212, 7, 0, 0,
                    32, 0, 0, 0,
                    114, 101, 97, 99,
                    116, 105, 118, 101,
                    46, 99, 111, 108,
                    108, 0, 0, 0,
                    0, 0, 1, 0,
                    0, 0, 13, 0,
                    0, 0, 16, 105,
                    100, 0, 3, 0,
                    0, 0, 0
                };
            var buffer = new byte[expected.Length];
            var message = new OpQueryMessage(flags,
                                             fullCollectionName,
                                             numberToSkip,
                                             numberToReturn,
                                             rawQuery);
            message.Write(ref buffer, requestId, responseTo);

            Assert.Equal(expected, buffer);
        }
예제 #2
0
 protected WriteProtocolException(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     _result = BsonSerializer.Deserialize <BsonDocument>((byte[])info.GetValue("_result", typeof(byte[])));
 }
예제 #3
0
 public static void RegisterCommonSerializers() => BsonSerializer.RegisterSerializer(typeof(DateTime), new AssumeUtcDateTimeSerializer());
예제 #4
0
        static private void WritePropertyValue(BsonSerializer file, DesignerPropertyInfo property, object o) {
            string str = property.GetExportValue(o);
            string[] tokens = str.Split(' ');
            string valueString = null;

            if (tokens.Length == 3 && tokens[0] == "const") {
                valueString = tokens[2];

            } else if (tokens.Length == 1) {
                valueString = str;
            }

            bool bW = false;

            if (valueString != null) {
                object obj = property.Property.GetValue(o, null);

                object v = null;

                Type valueType = null;
                VariableDef varType = obj as VariableDef;

                if (varType != null) {
                    valueType = varType.GetValueType();

                } else {
                    RightValueDef rvarType = obj as RightValueDef;

                    if (rvarType != null) {
                        if (rvarType.Method == null) {
                            valueType = rvarType.ValueType;
                        }

                    } else {
                        MethodDef mType = obj as MethodDef;

                        if (mType != null) {
                            Debug.Check(true);

                        } else {
                            valueType = obj.GetType();
                        }
                    }
                }

                if (valueType != null && Plugin.InvokeTypeParser(null, valueType, valueString, (object value) => v = value, null))
                {
                    file.WriteAttribute(property.Property.Name, v);
                    bW = true;
                }
            }

            if (!bW) {
                file.WriteAttributeString(property.Property.Name, str);
            }
        }
예제 #5
0
 static private void WritePar(BsonSerializer file, string valueName, ParInfo par) {
     //WriteParValue(file, valueName, par);
     WriteParString(file, valueName, par);
 }
예제 #6
0
        /// <summary>
        /// Exports a node to the given file.
        /// </summary>
        /// <param name="file">The file we want to export to.</param>
        /// <param name="behavior">The behaviour we are currently exporting.</param>
        /// <param name="node">The node we want to export.</param>
        protected void ExportNode(BsonSerializer file, BehaviorNode behavior, Node node) {
            if (!node.Enable)
            { return; }

            file.WriteStartElement("node");

            file.WriteString(node.ExportClass);
            file.WriteString(node.Id.ToString());

            {
                // export the properties
                this.ExportProperties(file, node);

                this.ExportAttachments(file, node);

                if (!node.IsFSM && !(node is ReferencedBehavior))
                {
                    // export the child nodes
                    foreach (Node child in node.Children)
                    {
                        if (!node.GetConnector(child).IsAsChild)
                        {
                            file.WriteStartElement("custom");
                            this.ExportNode(file, behavior, child);
                            file.WriteEndElement();
                        }
                        else
                        {
                            this.ExportNode(file, behavior, child);
                        }
                    }
                }
            }

            file.WriteEndElement();
        }
예제 #7
0
        private void ExportDescritorRefs(BsonSerializer file, Behavior b)
        {
            if (b.DescriptorRefs.Count == 0)
                return;

            string propValue = DesignerArray.RetrieveExportValue(b.DescriptorRefs);
            file.WriteAttributeString("DescriptorRefs", propValue);
        }
예제 #8
0
        private void ExportParameters(BsonSerializer file, Node node)
        {
            if (node.Pars.Count == 0)
                return;

            file.WriteStartElement("pars");

            for (int i = 0; i < node.Pars.Count; ++i)
            {
                string parType = Plugin.GetNativeTypeName(node.Pars[i].Type);

                file.WriteStartElement("par");

                file.WriteString(node.Pars[i].Name);
                file.WriteString(parType);
                file.WriteString(node.Pars[i].DefaultValue);

                file.WriteEndElement();
            }

            file.WriteEndElement();
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", "options", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            // CosmosDB Parameters, retrieved via environment variables
            string databaseName            = Environment.GetEnvironmentVariable("cosmosdbDatabaseName");
            string collectionName          = Environment.GetEnvironmentVariable("cosmosdbCollectionName");
            string mongodbConnectionString = Environment.GetEnvironmentVariable("cosmosdbMongodbConnectionString");

            // This endpoint is valid for all MongoDB
            var client     = new MongoClient(mongodbConnectionString);
            var database   = client.GetDatabase(databaseName);
            var collection = database.GetCollection <BsonDocument>(collectionName);

            // Get Parameters
            dynamic contentdata = await req.Content.ReadAsAsync <object>();

            // Backup Size (source)
            decimal size = Convert.ToDecimal(GetParameter("size", "0", req));

            size = SetMinimum(size, 0);
            log.Info("Backup Size : " + size.ToString());
            // # of Daily backups
            decimal daily = Convert.ToDecimal(GetParameter("daily", "0", req));

            daily = SetMinimum(daily, 0);
            log.Info("Daily : " + daily.ToString());
            // # of Weekly backups
            decimal weekly = Convert.ToDecimal(GetParameter("weekly", "0", req));

            weekly = SetMinimum(weekly, 0);
            log.Info("Weekly : " + weekly.ToString());
            // # of Monthly backups
            decimal monthly = Convert.ToDecimal(GetParameter("monthly", "0", req));

            monthly = SetMinimum(monthly, 0);
            log.Info("Monthly : " + monthly.ToString());
            // # of Yearly backups
            decimal yearly = Convert.ToDecimal(GetParameter("yearly", "0", req));

            yearly = SetMinimum(yearly, 0);
            log.Info("Yearly : " + yearly.ToString());
            // Region #
            string region = GetParameter("region", "europe-west", req).ToLower();

            log.Info("Region : " + region.ToString());
            // Currency #
            string currency = GetParameter("currency", "EUR", req).ToUpper();

            log.Info("Currency : " + currency.ToString());
            // Resiliency
            string resiliency = GetParameter("resiliency", "lrs", req).ToLower();

            log.Info("Resiliency : " + resiliency.ToString());
            // Churn Rate (%)
            decimal churn = Convert.ToDecimal(GetParameter("churn", "2", req));

            churn = SetMinimum(churn, 0);
            churn = SetMaximum(churn, 100);
            log.Info("Churn : " + churn.ToString());
            // Compression Gain (%)
            decimal compression = Convert.ToDecimal(GetParameter("compression", "30", req));

            compression = SetMinimum(compression, 0);
            compression = SetMaximum(compression, 100);
            log.Info("Compression : " + compression.ToString());

            // Load Application Insights
            string          ApplicationInsightsKey = TelemetryConfiguration.Active.InstrumentationKey = System.Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", EnvironmentVariableTarget.Process);
            TelemetryClient telemetry = new TelemetryClient()
            {
                InstrumentationKey = ApplicationInsightsKey
            };

            // Create Return Object
            dynamic documents = new System.Dynamic.ExpandoObject();

            // Get Backup Instance Cost
            var filterBuilder = Builders <BsonDocument> .Filter;
            var filter        = filterBuilder.Eq("type", "backup")
                                & filterBuilder.Eq("dimension", "backup-instance")
                                & filterBuilder.Eq("region", region)
            ;
            var sort = Builders <BsonDocument> .Sort.Ascending("price");

            var cursor = collection.Find <BsonDocument>(filter).Sort(sort).Limit(1).ToCursor();

            foreach (var document in cursor.ToEnumerable())
            {
                // Get RequestCharge
                var LastRequestStatistics = database.RunCommand <BsonDocument>(new BsonDocument {
                    { "getLastRequestStatistics", 1 }
                });
                double RequestCharge = (double)LastRequestStatistics["RequestCharge"];
                telemetry.TrackMetric("RequestCharge", RequestCharge);

                // Get Document
                log.Info(document.ToString());
                VmBackupInstance myVmBackupInstance = BsonSerializer.Deserialize <VmBackupInstance>(document);
                myVmBackupInstance.setCurrency(currency);
                decimal VmBackupInstanceCost = myVmBackupInstance.calculateBackupInstance(size);
                documents.CostInstance = VmBackupInstanceCost.ToString();
            }

            // Get Backup Storage Cost
            filterBuilder = Builders <BsonDocument> .Filter;
            filter        = filterBuilder.Eq("type", "backup")
                            & filterBuilder.Eq("dimension", "backup-storage-" + resiliency)
                            & filterBuilder.Eq("region", region)
            ;
            sort = Builders <BsonDocument> .Sort.Ascending("price");

            cursor = collection.Find <BsonDocument>(filter).Sort(sort).Limit(1).ToCursor();
            foreach (var document in cursor.ToEnumerable())
            {
                // Get RequestCharge
                var LastRequestStatistics = database.RunCommand <BsonDocument>(new BsonDocument {
                    { "getLastRequestStatistics", 1 }
                });
                double RequestCharge = (double)LastRequestStatistics["RequestCharge"];
                telemetry.TrackMetric("RequestCharge", RequestCharge);

                // Get Document
                log.Info(document.ToString());
                VmBackupStorage myVmBackupStorage = BsonSerializer.Deserialize <VmBackupStorage>(document);
                myVmBackupStorage.setCurrency(currency);
                decimal VmBackupStorageSize = myVmBackupStorage.calculateBackupSize(size, daily, weekly, monthly, yearly, churn, compression);
                decimal VmBackupStorageCost = myVmBackupStorage.calculateBackupStorageCost(VmBackupStorageSize);
                documents.SizeTotal   = VmBackupStorageSize.ToString();
                documents.CostStorage = VmBackupStorageCost.ToString();
            }

            // Convert to JSON & return it
            var json = JsonConvert.SerializeObject(documents, Formatting.Indented);

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            });
        }
        public void Awake()
        {
            Type[] types = typeof(NodeType).Assembly.GetTypes();
            foreach (Type type in types)
            {
                if (type.IsSubclassOf(typeof(NP_NodeDataBase)) || type.IsSubclassOf(typeof(NP_ClassForStoreAction)) ||
                    type.IsSubclassOf(typeof(BuffNodeDataBase)) || type.IsSubclassOf(typeof(BuffDataBase)) ||
                    type.IsSubclassOf(typeof(ListenBuffEvent_Normal)) || type.IsSubclassOf(typeof(NP_DataSupportorBase)))
                {
                    BsonClassMap.LookupClassMap(type);
                }
            }

            BsonClassMap.LookupClassMap(typeof(NP_BBValue_Int));
            BsonClassMap.LookupClassMap(typeof(NP_BBValue_Bool));
            BsonClassMap.LookupClassMap(typeof(NP_BBValue_Float));
            BsonClassMap.LookupClassMap(typeof(NP_BBValue_String));
            BsonClassMap.LookupClassMap(typeof(NP_BBValue_Vector3));
            BsonClassMap.LookupClassMap(typeof(NP_BBValue_Long));
            BsonClassMap.LookupClassMap(typeof(NP_BBValue_List_Long));
#if SERVER
            DirectoryInfo directory = new DirectoryInfo(NPDataPath);
            FileInfo[]    fileInfos = directory.GetFiles();

            foreach (var fileInfo in fileInfos)
            {
                byte[] mfile = File.ReadAllBytes(fileInfo.FullName);

                if (mfile.Length == 0)
                {
                    Log.Info("没有读取到文件");
                }

                try
                {
                    NP_DataSupportor MnNpDataSupportor = BsonSerializer.Deserialize <NP_DataSupportor>(mfile);

                    Log.Info($"反序列化行为树:{fileInfo.FullName}完成");

                    NpRuntimeTreesDatas.Add(MnNpDataSupportor.RootId, MnNpDataSupportor);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
#else
            ResourcesComponent resourcesComponent = Game.Scene.GetComponent <ResourcesComponent>();
            GameObject         skillConfigs       = resourcesComponent.LoadAsset <GameObject>(ABPathUtilities.GetSkillConfigPath("SkillConfigs"));
            foreach (var referenceCollectorData in skillConfigs.GetComponent <ReferenceCollector>().data)
            {
                TextAsset textAsset = skillConfigs.GetTargetObjectFromRC <TextAsset>(referenceCollectorData.key);

                if (textAsset.bytes.Length == 0)
                {
                    Log.Info("没有读取到文件");
                }

                try
                {
                    NP_DataSupportor MnNpDataSupportor = BsonSerializer.Deserialize <NP_DataSupportor>(textAsset.bytes);

                    Log.Info($"反序列化行为树:{referenceCollectorData.key}完成");

                    this.m_NpRuntimeTreesDatas.Add(MnNpDataSupportor.NpDataSupportorBase.RootId, MnNpDataSupportor);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    throw;
                }
            }
#endif
        }
예제 #11
0
        public AutoMapper_UserAPI_AttemptsProfile()
        {
            #region DB -> API
            #region AttemptsDB_AttemptDTO -> UserAPI_GetAttemptDTO
            CreateMap <AttemptsDB_ChoiceOption, UserAPI_AttemptCommonOptionDTO>();
            CreateMap <AttemptsDB_PositionalOption, UserAPI_AttemptCommonOptionDTO>();
            CreateMap <AttemptsDB_FillInOption, UserAPI_AttemptCommonOptionDTO>();

            CreateMap <AttemptsDB_ChoiceOptionsContainer, UserAPI_AttemptCommonOptionDTO[]>()
            .ConstructUsing(x =>
                            Mapper.Map <UserAPI_AttemptCommonOptionDTO[]>(x.Options));
            CreateMap <AttemptsDB_MatchingOptionsContainer, UserAPI_AttemptCommonOptionDTO[]>()
            .ConstructUsing(x =>
            {
                var optionsLength = x.LeftSequence.Length;
                var sequence      = new UserAPI_AttemptCommonOptionDTO[optionsLength];
                for (var i = 0; i < optionsLength; i++)
                {
                    sequence[i] = new UserAPI_AttemptCommonOptionDTO {
                        LeftText      = x.LeftSequence[i].Text,
                        LeftImageUrl  = x.LeftSequence[i].ImageUrl,
                        RightText     = x.RightSequence[i].Text,
                        RightImageUrl = x.RightSequence[i].ImageUrl
                    }
                }
                ;

                return(sequence);
            });
            CreateMap <AttemptsDB_SequenceOptionsContainer, UserAPI_AttemptCommonOptionDTO[]>()
            .ConstructUsing(x =>
                            Mapper.Map <UserAPI_AttemptCommonOptionDTO[]>(x.Sequence));

            CreateMap <AttemptsDB_QuestionDTO, UserAPI_GetAttemptQuestionDTO>()
            .ForMember(x => x.Options,
                       x => x.MapFrom(m =>
                                      m.Type == QuestionTypes.SingleChoice || m.Type == QuestionTypes.MultipleChoice ?
                                      Mapper.Map <UserAPI_AttemptCommonOptionDTO[]>(
                                          BsonSerializer.Deserialize <AttemptsDB_ChoiceOptionsContainer>(m.Options, null)) :

                                      m.Type == QuestionTypes.Matching ?
                                      Mapper.Map <UserAPI_AttemptCommonOptionDTO[]>(
                                          BsonSerializer.Deserialize <AttemptsDB_MatchingOptionsContainer>(m.Options, null)) :

                                      m.Type == QuestionTypes.Sequence ?
                                      Mapper.Map <UserAPI_AttemptCommonOptionDTO[]>(
                                          BsonSerializer.Deserialize <AttemptsDB_SequenceOptionsContainer>(m.Options, null)) :

                                      m.Type == QuestionTypes.FillIn ?
                                      Mapper.Map <UserAPI_AttemptCommonOptionDTO[]>(
                                          BsonSerializer.Deserialize <AttemptsDB_FillInOptionsContainer>(m.Options, null).Options) :

                                      new UserAPI_AttemptCommonOptionDTO[0]
                                      ));
            CreateMap <KeyValuePair <string, AttemptsDB_QuestionDTO>, KeyValuePair <string, UserAPI_GetAttemptQuestionDTO> >()
            .ConstructUsing(x => new KeyValuePair <string, UserAPI_GetAttemptQuestionDTO>(
                                x.Key,
                                Mapper.Map <UserAPI_GetAttemptQuestionDTO>(x.Value)));

            CreateMap <AttemptsDB_SectionDTO, UserAPI_GetAttemptSectionDTO>()
            .ForMember(x => x.Questions,
                       x => x.MapFrom(m =>
                                      Mapper.Map <Dictionary <string, UserAPI_GetAttemptQuestionDTO> >(m.Questions)));
            CreateMap <KeyValuePair <string, AttemptsDB_SectionDTO>, KeyValuePair <string, UserAPI_GetAttemptSectionDTO> >()
            .ConstructUsing(x => new KeyValuePair <string, UserAPI_GetAttemptSectionDTO>(
                                x.Key,
                                Mapper.Map <UserAPI_GetAttemptSectionDTO>(x.Value)));

            CreateMap <AttemptsDB_AttemptDTO, UserAPI_GetAttemptDTO>()
            .ForMember(x => x.Sections,
                       x => x.MapFrom(m => Mapper.Map <Dictionary <string, UserAPI_GetAttemptSectionDTO> >(m.Sections)));
            #endregion

            CreateMap <AttemptsDB_AttemptDTO, UserAPI_GetAttemptsItemDTO>();
            #endregion

            #region API -> DB

            #endregion
        }
예제 #12
0
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="DistinctCommandResultSerializer{TValue}"/> class.
 /// </summary>
 public DistinctCommandResultSerializer()
     : this(BsonSerializer.LookupSerializer <TValue>())
 {
 }
예제 #13
0
 public object DeserializeFrom(Type type, string str)
 {
     return(BsonSerializer.Deserialize(str, type));
 }
예제 #14
0
 public T DeserializeFrom <T>(string str)
 {
     return(BsonSerializer.Deserialize <T>(str));
 }
예제 #15
0
        protected void ExportAttachments(BsonSerializer file, Node node)
        {
            if (node.Attachments.Count > 0)
            {
                file.WriteStartElement("attachments");

                foreach (Attachments.Attachment a in node.Attachments)
                {
                    file.WriteStartElement("attachment");

                    Type type = a.GetType();

                    file.WriteString(a.ExportClass);
                    file.WriteString(a.Id.ToString());

                    this.ExportProperties(file, a);
                    this.ExportParameters(file, a);

                    file.WriteEndElement();
                }

                file.WriteEndElement();
            }
        }
예제 #16
0
        /// <summary>
        /// Exports a node to the given file.
        /// </summary>
        /// <param name="file">The file we want to export to.</param>
        /// <param name="namspace">The namespace of the behaviour we are currently exporting.</param>
        /// <param name="behavior">The behaviour we are currently exporting.</param>
        /// <param name="parentName">The name of the variable of the node which is the parent of this node.</param>
        /// <param name="node">The node we want to export.</param>
        /// <param name="indentDepth">The indent of the ocde we are exporting.</param>
        /// <param name="nodeID">The current id used for generating the variables for the nodes.</param>
        protected void ExportNode(BsonSerializer file, BehaviorNode behavior, Node parent, Node node)
        {
            if (!node.Enable)
                return;

            file.WriteStartElement("node");

            file.WriteString(node.ExportClass);
            file.WriteString(node.Version.ToString());
            file.WriteString(node.Id.ToString());

            //// we have to handle a referenced behaviour differently
            //if (node is ReferencedBehaviorNode)
            //{
            //    // generate the namespace and name of the behaviour we are referencing
            //    string refRelativeFilename = behavior.MakeRelative(((ReferencedBehaviorNode)node).ReferenceFilename);
            //    string refBehaviorName = Path.GetFileNameWithoutExtension(((ReferencedBehaviorNode)node).ReferenceFilename.Replace(" ", string.Empty));

            //    file.WriteStartElement("property");
            //    file.WriteAttributeString("referencefilename", refBehaviorName);
            //    file.WriteEndElement();
            //}
            //else
            {
                // export the properties
                this.ExportProperties(file, node);

                this.ExportParameters(file, node);

                this.ExportAttachments(file, node);

                // add the node to its parent
                //file.Write(string.Format("{0}\t{1}.AddChild({1}.GetConnector(\"{2}\"), {3});\r\n", indent, parentName, node.ParentConnector.Identifier, nodeName));

                if (!(node is ReferencedBehavior))
                {
                    // export the child nodes
                    foreach (Node child in node.Children)
                    {
                        this.ExportNode(file, behavior, node, child);
                    }
                }
            }

            file.WriteEndElement();
        }
 public Object Deserialize(BsonDocument doc, Type type)
 {
     return(BsonSerializer.Deserialize(doc, type));
 }
예제 #18
0
        /// <summary>
        /// Exports all the properties of a ode and assigns them.
        /// </summary>
        /// <param name="file">The file we are exporting to.</param>
        /// <param name="nodeName">The name of the node we are setting the properties for.</param>
        /// <param name="node">The node whose properties we are exporting.</param>
        /// <param name="indent">The indent for the currently generated code.</param>
        private void ExportProperties(BsonSerializer file, Node n)
        {
            IList<DesignerPropertyInfo> properties = n.GetDesignerProperties();

            file.WriteStartElement("properties");

            foreach (DesignerPropertyInfo p in properties)
            {
                // we skip properties which are not marked to be exported
                if (p.Attribute.HasFlags(DesignerProperty.DesignerFlags.NoExport))
                    continue;

                bool bDo = true;
                if (p.Attribute.HasFlags(DesignerProperty.DesignerFlags.BeValid))
                {
                    object obj = p.Property.GetValue(n, null);

                    if (obj == null || obj.ToString() == "null_method")
                    {
                        bDo = false;
                    }
                }

                if (bDo)
                {

                    // create the code which assigns the value to the node's property
                    //file.Write(string.Format("{0}\t{1}.{2} = {3};\r\n", indent, nodeName, properties[p].Property.Name, properties[p].GetExportValue(node)));
                    string propValue = p.GetExportValue(n);
                    if (propValue != string.Empty && propValue != "\"\"")
                    {
                        WriteProperty(file, p, n);
                    }
                }
            }

            #if QUERY_EANBLED
            Behavior b = n as Behavior;
            if (b != null)
            {
                this.ExportDescritorRefs(file, b);
            }
            #endif

            file.WriteEndElement();
        }
        public void AddData(string data)
        {
            List <BrowserDBData> dbData = JsonConvert.DeserializeObject <List <BrowserDBData> >(data);

            foreach (var dbObj in dbData)
            {
                if (dbObj.type == AvailableDataType.WalletAddress.ToString())
                {
                    _addresses[dbObj.id] =
                        _bsonMapper.ToObject <WalletAddress>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }
                else if (dbObj.type == AvailableDataType.Transaction.ToString())
                {
                    string[] parsedId = dbObj.id.Split(Convert.ToChar("/"));
                    string   id       = parsedId[0];
                    string   currency = parsedId[1];

                    BsonDocument bd = BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data));
                    _transactions[$"{id}:{currency}"] = (IBlockchainTransaction)_bsonMapper.ToObject(doc: bd,
                                                                                                     type: _currencies.GetByName(currency).TransactionType);
                }
                else if (dbObj.type == AvailableDataType.Swap.ToString())
                {
                    _swaps[long.Parse(dbObj.id)] =
                        _bsonMapper.ToObject <Swap>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }
                else if (dbObj.type == AvailableDataType.Output.ToString())
                {
                    string[] parsedId = dbObj.id.Split(Convert.ToChar("/"));
                    string   id       = parsedId[0];
                    string   currency = parsedId[1];
                    string   address  = parsedId[2];

                    BsonDocument       bd = BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data));
                    BitcoinBasedConfig BtcBasedCurrency = _currencies.Get <BitcoinBasedConfig>(currency);
                    ITxOutput          output           =
                        (ITxOutput)_bsonMapper.ToObject(doc: bd, type: BtcBasedCurrency.OutputType());

                    _outputs[id] = new OutputEntity {
                        Output = output, Currency = currency, Address = address
                    };
                }
                else if (dbObj.type == AvailableDataType.Order.ToString())
                {
                    _orders[dbObj.id] =
                        _bsonMapper.ToObject <Order>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }

                else if (dbObj.type == AvailableDataType.TezosTokenAddress.ToString())
                {
                    _tezosTokensAddresses[dbObj.id] = _bsonMapper.ToObject <WalletAddress>(
                        BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }

                else if (dbObj.type == AvailableDataType.TezosTokenContract.ToString())
                {
                    _tezosTokensContracts[dbObj.id] =
                        _bsonMapper.ToObject <TokenContract>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }

                else if (dbObj.type == AvailableDataType.TezosTokenTransfer.ToString())
                {
                    _tezosTokensTransfers[dbObj.id] =
                        _bsonMapper.ToObject <TokenTransfer>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }
            }
        }
예제 #20
0
        private void ExportPar(BsonSerializer file, ParInfo par, bool bExportValue) {
            file.WriteStartElement("par");

            file.WriteString(par.BasicName);
            file.WriteString(par.NativeType);

            if (bExportValue) {
                file.WriteString(par.DefaultValue);

            } else {
                file.WriteString("");
            }

            file.WriteEndElement();
        }
예제 #21
0
 private byte[] ToBson(string json)
 {
     return(BsonSerializer.Deserialize <BsonDocument>(json).ToBson());
 }
예제 #22
0
        private void ExportProperties(BsonSerializer file, Attachments.Attachment a) {
            DesignerPropertyInfo propertyEffector = new DesignerPropertyInfo();
            file.WriteStartElement("properties");
            IList<DesignerPropertyInfo> properties = a.GetDesignerProperties(true);
            foreach(DesignerPropertyInfo p in properties) {
                // we skip properties which are not marked to be exported
                if (p.Attribute.HasFlags(DesignerProperty.DesignerFlags.NoExport))
                { continue; }

                object v = p.Property.GetValue(a, null);
                bool bExport = !Plugin.IsExportArray(v);

                if (bExport) {
                    if (p.Property.Name == "Effectors") {
                        propertyEffector = p;

                    } else {
                        WriteProperty(file, p, a);
                    }
                }
            }

            file.WriteEndElement();

            if (propertyEffector.Property != null) {
                List<TransitionEffector> listV = (List<TransitionEffector>)propertyEffector.Property.GetValue(a, null);

                if (listV != null) {
                    file.WriteStartElement("attachments");
                    foreach(TransitionEffector te in listV) {
                        file.WriteStartElement("attachment");
                        file.WriteStartElement("properties");
                        IList<DesignerPropertyInfo> effectorProperties = te.GetDesignerProperties();
                        foreach(DesignerPropertyInfo p in effectorProperties) {
                            // we skip properties which are not marked to be exported
                            if (p.Attribute.HasFlags(DesignerProperty.DesignerFlags.NoExport))
                            { continue; }

                            WriteProperty(file, p, te);
                        }

                        file.WriteEndElement();
                        file.WriteEndElement();
                    }

                    file.WriteEndElement();
                }
            }
        }
 /// <summary>
 /// 将BsonDocument反序列化成对象
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="document"></param>
 /// <returns></returns>
 static public T Deserialize <T>(BsonDocument document) where T : MongoIdModel
 {
     return(BsonSerializer.Deserialize <T>(document));
 }
예제 #24
0
 static private void WriteProperty(BsonSerializer file, DesignerPropertyInfo property, object o) {
     //WritePropertyValue(file, property, o);
     WritePropertyString(file, property, o);
 }
예제 #25
0
 /// <summary>
 /// Gets the Id generator for an Id member.
 /// </summary>
 /// <param name="memberInfo">The member.</param>
 /// <returns>An Id generator.</returns>
 public IIdGenerator GetIdGenerator(MemberInfo memberInfo)
 {
     return(BsonSerializer.LookupIdGenerator(BsonClassMap.GetMemberInfoType(memberInfo)));
 }
예제 #26
0
 public object DeserializeFrom(Type type, byte[] bytes)
 {
     return(BsonSerializer.Deserialize(bytes, type));
 }
예제 #27
0
        public static PixelCoordinates toPixelCoordinate(this BsonValue value)
        {
            var coord = BsonSerializer.Deserialize <PixelCoordinates>(value.ToJson());

            return(coord);
        }
예제 #28
0
        /// <summary>
        /// Get all document using an indexInfo as start point (_id index).
        /// </summary>
        public IEnumerable <BsonDocument> GetDocuments(IndexInfo index)
        {
            var indexPages = this.VisitIndexPages(index.HeadPageID);

            foreach (var indexPageID in indexPages)
            {
                var indexPage = this.ReadPage(indexPageID);

                foreach (var node in indexPage["nodes"].AsArray)
                {
                    var dataBlock = node["dataBlock"];

                    // if datablock link to a data page
                    if (dataBlock["pageID"].AsInt32 != -1)
                    {
                        // read dataPage and data block
                        var dataPage = this.ReadPage((uint)dataBlock["pageID"].AsInt32);

                        if (dataPage["pageType"].AsInt32 != 4)
                        {
                            continue;
                        }

                        var block = dataPage["blocks"].AsArray.FirstOrDefault(x => x["index"] == dataBlock["index"]).AsDocument;

                        if (block == null)
                        {
                            continue;
                        }

                        // read byte[] from block or from extend pages
                        var data = block["extendPageID"] == -1 ?
                                   block["data"].AsBinary :
                                   this.ReadExtendData((uint)block["extendPageID"].AsInt32);

                        if (data.Length == 0)
                        {
                            continue;
                        }

                        // BSON format still same from all version
                        var doc = BsonSerializer.Deserialize(data);

                        // change _id PK in _chunks collection
                        if (index.Collection == "_chunks")
                        {
                            var parts = doc["_id"].AsString.Split('\\');

                            if (!int.TryParse(parts[1], out var n))
                            {
                                throw LiteException.InvalidFormat("_id");
                            }

                            doc["_id"] = new BsonDocument
                            {
                                ["f"] = parts[0],
                                ["n"] = n
                            };
                        }

                        yield return(doc);
                    }
                }
            }
        }
예제 #29
0
 // constructors
 /// <summary>
 /// Initializes a new instance of the NullableSerializer class.
 /// </summary>
 public NullableSerializer()
 {
     _serializer = BsonSerializer.LookupSerializer(typeof(T));
 }
예제 #30
0
        // protected methods
        /// <summary>
        /// Serializes the wrapped value.
        /// </summary>
        /// <param name="context">The context.</param>
        protected void SerializeWrappedObject(BsonSerializationContext context)
        {
            var serializer = BsonSerializer.LookupSerializer(_nominalType);

            serializer.Serialize(context, _wrapped);
        }
예제 #31
0
 public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Triplet value)
 {
     BsonSerializer.Serialize(context.Writer, value);
 }
예제 #32
0
        /// <summary>
        /// Exports a behaviour to the given file.
        /// </summary>
        /// <param name="file">The file we want to export to.</param>
        /// <param name="behavior">The behaviour we want to export.</param>
        protected void ExportBehavior(BsonSerializer file, BehaviorNode behavior)
        {
            file.WriteComment("EXPORTED BY TOOL, DON'T MODIFY IT!");
            file.WriteComment("Source File: " + behavior.MakeRelative(behavior.FileManager.Filename));

            file.WriteStartElement("behavior");

            Behavior b = behavior as Behavior;
            Debug.Check(b != null);
            Debug.Check(b.Id == -1);

            //'\\' ->'/'
            string behaviorName = b.MakeRelative(b.Filename);
            behaviorName = behaviorName.Replace('\\', '/');
            int pos = behaviorName.IndexOf(".xml");
            if (pos != -1)
            {
                behaviorName = behaviorName.Remove(pos);
            }

            file.WriteString(behaviorName);
            file.WriteString(b.AgentType.AgentTypeName);
            file.WriteString(b.Version.ToString());

            this.ExportProperties(file, b);

            this.ExportParameters(file, (Node)behavior);

            this.ExportAttachments(file, b);

            // export the children
            foreach (Node child in ((Node)behavior).Children)
            {
                this.ExportNode(file, behavior, (Node)behavior, child);
            }

            file.WriteEndElement();
        }
예제 #33
0
 public Triplet Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
 {
     return(BsonSerializer.Deserialize <Triplet>(context.Reader.ReadBytes()));
 }
예제 #34
0
        private static void WriteParValue(BsonSerializer file, string valueName, ParInfo par)
        {
            string parStr = par.DefaultValue;

            object v = null;

            Type valueType = par.Type;

            if (valueType != null && Plugin.InvokeTypeParser(valueType, parStr, (object value) => v = value, null))
            {
                //file.WriteAttribute(valueName, v);
                file.Write(v);
            }
        }
예제 #35
0
 public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
 {
     BsonSerializer.Serialize(context.Writer, typeof(Triplet), value);
 }
예제 #36
0
        private void ExportParameters(BsonSerializer file, Attachments.Attachment attachment)
        {
            Attachments.Event evt = attachment as Attachments.Event;

            if (evt == null || evt.Pars.Count == 0)
                return;

            file.WriteStartElement("pars");

            for (int i = 0; i < evt.Pars.Count; ++i)
            {
                file.WriteStartElement("par");

                file.WriteString(evt.Pars[i].Name);
                file.WriteString(Plugin.GetNativeTypeName(evt.Pars[i].Type));
                file.WriteString(evt.Pars[i].DefaultValue);

                if (!string.IsNullOrEmpty(evt.Pars[i].EventParam))
                {
                    file.WriteString(evt.Pars[i].EventParam);
                }

                file.WriteEndElement();
            }

            file.WriteEndElement();
        }
예제 #37
0
        public void Save(DeviceNotification notification)
        {
            if (notification == null)
            {
                throw new ArgumentNullException("notification");
            }

            if (notification.Device != null)
            {
                notification.DeviceID = notification.Device.ID;
            }

            if (notification.ID == default(int))
            {
                // use findAndModify to get the database-generated timestamp in response
                _mongo.SetIdentity(notification, _mongo.GetIdentityFromBlock(typeof(DeviceNotification).Name));
                var result = _mongo.DeviceNotifications.FindAndModify(new FindAndModifyArgs
                {
                    Query  = Query <DeviceNotification> .EQ(e => e.ID, notification.ID),
                    Update = Update.Combine(
                        notification.Timestamp == default(DateTime) ?
                        Update <DeviceNotification> .CurrentDate(e => e.Timestamp) :
                        Update <DeviceNotification> .Set(e => e.Timestamp, notification.Timestamp),
                        Update <DeviceNotification> .Set(e => e.Notification, notification.Notification),
                        Update.Set("Parameters", notification.Parameters == null ? BsonNull.Value : BsonSerializer.Deserialize <BsonValue>(notification.Parameters)),
                        Update <DeviceNotification> .Set(e => e.DeviceID, notification.DeviceID)),
                    Upsert          = true,
                    VersionReturned = FindAndModifyDocumentVersion.Modified,
                    Fields          = Fields <DeviceNotification> .Include(e => e.Timestamp),
                });
                _mongo.SetTimestamp(notification, result.ModifiedDocument["Timestamp"].ToUniversalTime());
            }
            else
            {
                _mongo.DeviceNotifications.Save(notification);
            }
        }
예제 #38
0
        private void ExportProperties(BsonSerializer file, Attachments.Attachment a)
        {
            file.WriteStartElement("properties");
            IList<DesignerPropertyInfo> properties = a.GetDesignerProperties();
            foreach (DesignerPropertyInfo p in properties)
            {
                // we skip properties which are not marked to be exported
                if (p.Attribute.HasFlags(DesignerProperty.DesignerFlags.NoExport))
                    continue;

                WriteProperty(file, p, a);
            }
            file.WriteEndElement();
        }
예제 #39
0
 /// <summary>
 /// Gets the modified document as a TDocument.
 /// </summary>
 /// <typeparam name="TDocument">The type of the modified document.</typeparam>
 /// <returns>The modified document.</returns>
 public TDocument GetModifiedDocumentAs <TDocument>()
 {
     return(BsonSerializer.Deserialize <TDocument>(ModifiedDocument));
 }
예제 #40
0
        private void ExportPars(BsonSerializer file, Behavior behavior) {
            if (behavior.LocalVars.Count == 0)
            { return; }

            file.WriteStartElement("pars");

            for (int i = 0; i < behavior.LocalVars.Count; ++i) {
                ParInfo par = behavior.LocalVars[i];

                if (par.Display) {
                    ExportPar(file, par, true);
                }
            }

            file.WriteEndElement();
        }
예제 #41
0
        public List <PostModel> Filter(string jsonQuery)
        {
            var queryDoc = new QueryDocument(BsonSerializer.Deserialize <BsonDocument>(jsonQuery));

            return(_collection.Find <PostModel>(queryDoc).ToList());
        }
예제 #42
0
        private void ExportDescritorRefs(BsonSerializer file, Behavior b) {
            if (Plugin.IsQueryFiltered)
            {
                return;
            }

            if (b.DescriptorRefs.Count > 0)
            {
                string propValue = DesignerArray.RetrieveExportValue(b.DescriptorRefs);
                file.WriteAttributeString("DescriptorRefs", propValue);
            }

            string propValue2 = b.Domains;
            if (!string.IsNullOrEmpty(propValue2))
            {
                file.WriteAttributeString("Domains", propValue2);
            }
        }
        public void should_deserialize_class_with_abstract_id()
        {
            var instance = BsonSerializer.Deserialize <WithAbstractId>("{ \"AbstractId\" : \"TestAbstract_42\" }");

            Assert.That(instance.AbstractId.Id, Is.EqualTo(42L));
        }
예제 #44
0
        /// <summary>
        /// Exports all the properties of a ode and assigns them.
        /// </summary>
        /// <param name="file">The file we are exporting to.</param>
        /// <param name="nodeName">The name of the node we are setting the properties for.</param>
        /// <param name="node">The node whose properties we are exporting.</param>
        /// <param name="indent">The indent for the currently generated code.</param>
        private void ExportProperties(BsonSerializer file, Node n) {
            IList<DesignerPropertyInfo> properties = n.GetDesignerProperties();

            file.WriteStartElement("properties");

            foreach(DesignerPropertyInfo p in properties) {
                // we skip properties which are not marked to be exported
                if (p.Attribute.HasFlags(DesignerProperty.DesignerFlags.NoExport))
                { continue; }

                object v = p.Property.GetValue(n, null);
                bool bExport = !Plugin.IsExportArray(v); ;

                if (bExport) {

                    // create the code which assigns the value to the node's property
                    //file.Write(string.Format("{0}\t{1}.{2} = {3};\r\n", indent, nodeName, properties[p].Property.Name, properties[p].GetExportValue(node)));
                    string propValue = p.GetExportValue(n);

                    if (propValue != string.Empty && propValue != "\"\"") {
                        WriteProperty(file, p, n);
                    }
                }
            }

            if (n is Task) {
                Task task = n as Task;

                file.WriteAttributeString("IsHTN", task.IsHTN ? "true" : "false");
            }

#if QUERY_EANBLED
            Behavior b = n as Behavior;

            if (b != null) {
                this.ExportDescritorRefs(file, b);
            }

#endif

            file.WriteEndElement();
        }
예제 #45
0
        public void TestBookmark()
        {
            var json = "{ \"x\" : 1, \"y\" : 2 }";

            using (_bsonReader = BsonReader.Create(json))
            {
                // do everything twice returning to bookmark in between
                var bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());

                bookmark = _bsonReader.GetBookmark();
                _bsonReader.ReadStartDocument();
                _bsonReader.ReturnToBookmark(bookmark);
                _bsonReader.ReadStartDocument();

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual("x", _bsonReader.ReadName());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual("x", _bsonReader.ReadName());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(1, _bsonReader.ReadInt32());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(1, _bsonReader.ReadInt32());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual("y", _bsonReader.ReadName());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual("y", _bsonReader.ReadName());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(2, _bsonReader.ReadInt32());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(2, _bsonReader.ReadInt32());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.EndOfDocument, _bsonReader.ReadBsonType());

                bookmark = _bsonReader.GetBookmark();
                _bsonReader.ReadEndDocument();
                _bsonReader.ReturnToBookmark(bookmark);
                _bsonReader.ReadEndDocument();

                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(new StringReader(json)).ToJson());
        }
예제 #46
0
        protected void ExportAttachments(BsonSerializer file, Node node) {
            //int localVars = ReferencedBehaviorLocalVars(node);
            int localVars = 0;

            if (node.Attachments.Count > 0 || localVars > 0) {
                file.WriteStartElement("attachments");

                //this.ExportReferencedBehaviorLocalVars(node, file);

                foreach(Attachments.Attachment a in node.Attachments) {
                    if (!a.Enable)
                        continue;

                    file.WriteStartElement("attachment");

                    Type type = a.GetType();

                    file.WriteString(a.ExportClass);
                    file.WriteString(a.Id.ToString());
                    file.WriteBool(a.IsPrecondition);
                    bool bIsEffector = a.IsEffector;

                    if (a.IsTransition) {
                        bIsEffector = false;
                    }

                    file.WriteBool(bIsEffector);
                    file.WriteBool(a.IsTransition);

                    this.ExportProperties(file, a);

                    //this.ExportEventLocalVars(a, file);

                    file.WriteEndElement();
                }

                file.WriteEndElement();
            }
        }
            public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", "options", Route = null)] HttpRequestMessage req, TraceWriter log)
            {
                string databaseName            = Environment.GetEnvironmentVariable("cosmosdbDatabaseName");
                string collectionName          = Environment.GetEnvironmentVariable("cosmosdbCollectionName");
                string mongodbConnectionString = Environment.GetEnvironmentVariable("cosmosdbMongodbConnectionString");

                // This endpoint is valid for all MongoDB
                var client     = new MongoClient(mongodbConnectionString);
                var database   = client.GetDatabase(databaseName);
                var collection = database.GetCollection <BsonDocument>(collectionName);

                // Get Parameters
                dynamic contentdata = await req.Content.ReadAsAsync <object>();

                // Region #
                string region = GetParameter("region", "europe-west", req).ToLower();

                log.Info("Region : " + region.ToString());
                // Currency #
                string currency = GetParameter("currency", "EUR", req).ToUpper();

                log.Info("Currency : " + currency.ToString());
                // Purchase Model
                string purchasemodel = GetParameter("purchasemodel", "managed", req).ToLower();

                log.Info("Purchase Model : " + purchasemodel.ToString());
                // tier
                string tier = GetParameter("tier", "general-purpose", req).ToLower();

                log.Info("Tier : " + tier.ToString());

                // Load Application Insights
                string          ApplicationInsightsKey = TelemetryConfiguration.Active.InstrumentationKey = System.Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", EnvironmentVariableTarget.Process);
                TelemetryClient telemetry = new TelemetryClient()
                {
                    InstrumentationKey = ApplicationInsightsKey
                };

                // Initialize results object
                List <SqlServiceStorage> documents = new List <SqlServiceStorage>();

                // Get Storage Pricing
                var filterBuilder = Builders <BsonDocument> .Filter;
                var filter        = filterBuilder.Eq("type", "sql-vcore")
                                    & filterBuilder.Eq("purchasemodel", purchasemodel)
                                    & filterBuilder.Eq("compute", "no")
                                    & filterBuilder.Eq("region", region)
                                    & filterBuilder.Eq("tier", tier)
                ;
                var sort = Builders <BsonDocument> .Sort.Ascending("price");

                var cursor = collection.Find <BsonDocument>(filter).Sort(sort).Limit(1).ToCursor();

                foreach (var document in cursor.ToEnumerable())
                {
                    // Get RequestCharge
                    var LastRequestStatistics = database.RunCommand <BsonDocument>(new BsonDocument {
                        { "getLastRequestStatistics", 1 }
                    });
                    double RequestCharge = (double)LastRequestStatistics["RequestCharge"];
                    telemetry.TrackMetric("RequestCharge", RequestCharge);
                    // Get Document
                    SqlServiceStorage mySqlServiceStorage = BsonSerializer.Deserialize <SqlServiceStorage>(document);
                    mySqlServiceStorage.setCurrency(currency);
                    documents.Add(mySqlServiceStorage);
                }

                // Return results
                // Convert to JSON & return it
                var json = JsonConvert.SerializeObject(documents, Formatting.Indented);

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(json, Encoding.UTF8, "application/json")
                });
            }
예제 #48
0
 static private void WriteParString(BsonSerializer file, string valueName, ParInfo par) {
     string parStr = par.DefaultValue;
     //file.WriteAttribute(valueName, parStr);
     file.WriteString(parStr);
 }
 static A()
 {
     BsonSerializer.RegisterDiscriminatorConvention(typeof(A), new MagicDiscriminatorConvention());
 }
예제 #50
0
        static private void WritePropertyString(BsonSerializer file, DesignerPropertyInfo property, object o) {
            string str = property.GetExportValue(o);

            file.WriteAttributeString(property.Property.Name, str);
        }
예제 #51
0
 private void RegisterConventions()
 {
     BsonSerializer.RegisterSerializer(typeof(decimal), new DecimalSerializer(BsonType.Decimal128));
     BsonSerializer.RegisterSerializer(typeof(decimal?), new NullableSerializer <decimal>(new DecimalSerializer(BsonType.Decimal128)));
     ConventionRegistry.Register("Conventions", new MongoDbConventions(), x => true);
 }
예제 #52
0
        /// <summary>
        /// Exports a behaviour to the given file.
        /// </summary>
        /// <param name="file">The file we want to export to.</param>
        /// <param name="behavior">The behaviour we want to export.</param>
        protected void ExportBehavior(BsonSerializer file, BehaviorNode behavior) {
            if (behavior.FileManager == null)
            {
                return;
            }

            file.WriteComment("EXPORTED BY TOOL, DON'T MODIFY IT!");
            file.WriteComment("Source File: " + behavior.MakeRelative(behavior.FileManager.Filename));

            file.WriteStartElement("behavior");

            Behavior b = behavior as Behavior;
            Debug.Check(b != null);
            Debug.Check(b.Id == -1);

            //'\\' ->'/'
            string behaviorName = b.MakeRelative(b.Filename);
            behaviorName = behaviorName.Replace('\\', '/');
            int pos = behaviorName.IndexOf(".xml");

            if (pos != -1) {
                behaviorName = behaviorName.Remove(pos);
            }

            file.WriteString(behaviorName);
            file.WriteString(b.AgentType.AgentTypeName);
            file.WriteBool(b.IsFSM);
            file.WriteString(b.Version.ToString());

            this.ExportProperties(file, b);

            this.ExportPars(file, b);

            if (!b.IsFSM) {
                this.ExportAttachments(file, b);
            }

            if (b.IsFSM)
            {
                file.WriteStartElement("node");

                file.WriteString("FSM");
                file.WriteString("-1");

                file.WriteStartElement("properties");
                    file.WriteAttributeString("initialid", behavior.InitialStateId.ToString());
                file.WriteEndElement();

                foreach (Node child in ((Node)behavior).FSMNodes)
                {
                    this.ExportNode(file, behavior, child);
                }

                file.WriteEndElement();
            }
            else
            {
                // export the children
                foreach (Node child in ((Node)behavior).Children)
                {
                    this.ExportNode(file, behavior, child);
                }
            }

            file.WriteEndElement();
        }
예제 #53
0
        public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
        {
            if (value == null)
            {
                bsonWriter.WriteNull();
                return;
            }
            object document;
            Type   type;

            var json = value.ToString();

            Console.WriteLine("serialize");
            Console.WriteLine(json);

            if (json.StarstAndEnds("{", "}"))
            {
                document = BsonDocument.Parse(json);
                type     = typeof(BsonDocument);
            }
            else if (json.StarstAndEnds("[", "]"))
            {
                document = BsonSerializer.Deserialize <BsonArray> (json);
                type     = typeof(BsonArray);
            }
            else if (json.IsBsonISODate())
            {
                document = BsonSerializer.Deserialize <BsonDateTime> (json);
                type     = typeof(BsonDateTime);
            }
            else if (json.IsISOString())
            {
                document = BsonSerializer.Deserialize <BsonDateTime> ("ISODate(\"" + json + "\")");
                type     = typeof(BsonDateTime);
            }
            else if (json.IsMsFormat())
            {
                document = BsonSerializer.Deserialize <BsonDateTime> ("new " + json.Replace("/", ""));
                type     = typeof(BsonDateTime);
            }
            else if (json.IsBool())
            {
                document = BsonSerializer.Deserialize <BsonBoolean> (json);
                type     = typeof(BsonBoolean);
            }
            else if (json.IsInt())
            {
                document = BsonSerializer.Deserialize <BsonInt32> (json);
                type     = typeof(BsonInt32);
            }
            else if (json.IsBsonNumberLong())
            {
                document = BsonSerializer.Deserialize <BsonInt64> (json);
                type     = typeof(BsonInt64);
            }
            else if (json.IsLong())
            {
                document = BsonSerializer.Deserialize <BsonInt64> ("NumberLong(\"" + json + "\")");
                type     = typeof(BsonInt64);
            }
            else if (json.IsDouble())
            {
                document = BsonSerializer.Deserialize <BsonDouble> (json);
                type     = typeof(BsonDouble);
            }
            else
            {
                document = BsonSerializer.Deserialize <BsonString> (json.StarstAndEnds("\"", "\"")
                                        ?json
                                        :"\"" + json + "\"");
                type = typeof(BsonString);
            }

            BsonSerializer.Serialize(bsonWriter, type, document, options);
        }