コード例 #1
0
        public override void Build(MongoDB.Bson.BsonDocument bsonPanelSetOrder, int panelSetId)
        {
            base.Build(bsonPanelSetOrder, panelSetId);

            BsonElement panelOrderCollectionElement = bsonPanelSetOrder.GetElement("PanelOrderCollection");
            BsonArray   panelOrderCollectionArray   = bsonPanelSetOrder["PanelOrderCollection"].AsBsonArray;

            MongoCollection panelOrderCytologyTable = this.m_SQLTransferDatabase.GetCollection <BsonDocument>("tblPanelOrderCytology");

            foreach (BsonDocument bsonPanelOrder in panelOrderCollectionArray)
            {
                int panelId = bsonPanelOrder.GetValue("PanelOrderId").ToInt32();
                if (panelId == 38) //cant' be acid wash
                {
                    BsonDocument bsonPODerived = panelOrderCytologyTable.FindOneAs <BsonDocument>(Query.EQ("PanelOrderId", bsonPanelOrder.GetValue("PanelOrderId")));
                    foreach (BsonElement bsonElement in bsonPODerived)
                    {
                        if (bsonElement.Name != "_id" && bsonElement.Name != "PanelOrderId")
                        {
                            bsonPanelOrder.Add(bsonElement);
                        }
                    }
                }
            }
        }
コード例 #2
0
ファイル: Form1.cs プロジェクト: aitsrp/ExcelToMongoDB
        public void JSONToMongoDB(string file, string act, string field, string val)
        {
            var connectionString = "mongodb://192.168.42.85:27017";
            var client           = new MongoClient(connectionString);
            var db         = client.GetDatabase("local");
            var collection = db.GetCollection <BsonDocument>("ztest");

            MongoDB.Bson.BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(file);

            switch (act)
            {
            case "insert":
                collection.InsertOne(document);
                break;

            case "replace":
                var filter = new BsonDocument(field, val);
                collection.FindOneAndReplace(filter, document);
                break;

            default:
                Console.WriteLine("You just broke the code.");
                break;
            }
        }
コード例 #3
0
        static void Main(string[] args)
        {
            string line1;

            using (StreamReader reader = new StreamReader("user.json"))
            {
                line1 = reader.ReadToEnd();
            }
            string line2;

            using (StreamReader reader = new StreamReader("user2.json"))
            {
                line2 = reader.ReadToEnd();
            }

            var combinedJson = JsonConvert.SerializeObject(new
            {
                obj1 = JObject.Parse(line1),
                obj2 = JObject.Parse(line2)
            });

            MongoDB.Bson.BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(combinedJson);
            FitBitContext             ctx      = new FitBitContext();
            //if (ctx.Users.Find<BsonDocument> document["user"]["age"].AsString)
            //FilterDefinition<BsonDocument> filter = "{ age: 2 }";
            //var found = ctx.Users.Find<BsonDocument>(filter);
            var filter = Builders <BsonDocument> .Filter.Eq("age", "28");

            var result = ctx.Users.Find(filter).ToListAsync();

            // NE RADI
            Console.WriteLine(result);
            ctx.Users.InsertOne(document);
        }
コード例 #4
0
        public async Task <ActionResult> Posts()
        {
            var currentClaims = await UserManager.GetClaimsAsync(HttpContext.User.Identity.GetUserId());

            var accestoken = currentClaims.FirstOrDefault(x => x.Type == "urn:tokens:facebook");

            if (accestoken == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NotFound, "Token not found"));
            }

            string         url     = String.Format("https://graph.facebook.com/me?fields=id,name,feed.limit(500){{link,height,width,type,message,story,created_time,id,target,full_picture}}&access_token={0}", accestoken.Value);
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.Method = "GET";
            using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string       result = await reader.ReadToEndAsync();

                dynamic jsonObj = System.Web.Helpers.Json.Decode(result);
                Models.SocialMedia.Facebook.posts posts = new Models.SocialMedia.Facebook.posts(jsonObj);
                ViewBag.JSON = result;
                string json = JsonConvert.SerializeObject(jsonObj);
                string path = @"C:\Big Data Analytics\Social data mining Technique\Assignment\fbdata.json";
                using (TextWriter tw = new StreamWriter(path))
                {
                    //foreach (var p in json)
                    // {
                    tw.WriteLine(json);
                    // }
                }
                var connectionString = "mongodb+srv://test:[email protected]/test?retryWrites=true&w=majority";


                var client = new MongoClient(connectionString);

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

                string text       = System.IO.File.ReadAllText(path);
                var    collection = database.GetCollection <BsonDocument>("FacebookR");
                var    aa         = new BsonDocument
                {
                    { "a", "aa" },
                    { "b", "bb" }
                };
                await collection.InsertOneAsync(aa);

                client.DropDatabase("SocialMedia" +
                                    "");
                MongoDB.Bson.BsonDocument docu
                    = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(result);
                await collection.InsertOneAsync(docu);


                return(View(posts));
            }
        }
コード例 #5
0
        public static void AddActivity(int ID, int IDGracza, string aktywnosc, string conn)
        {
            //BsonDateTime data = new BsonDateTime(DateTime.Now);

            string json = "{_id:" + ID + ", IDGracza:" + IDGracza + ", Aktywnosc:" + aktywnosc + ", Czas:'" + DateTime.Now + "'}";

            MongoDB.Bson.BsonDocument document
                = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(json);

            var mc       = new MongoClient(conn);
            var database = mc.GetDatabase("bazy");
            IMongoCollection <BsonDocument> col = database.GetCollection <BsonDocument>("Activity");

            col.InsertOne(document);
        }
コード例 #6
0
        internal async Task createDoc()
        {
            MongoDB_OptionSpreadExpression osefdb = new MongoDB_OptionSpreadExpression();

            osefdb.cqgSymbol = "test";

            string json = Newtonsoft.Json.JsonConvert.SerializeObject(osefdb);

            //Bsondo

            MongoDB.Bson.BsonDocument document
                = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(json);

            var collection = _database.GetCollection <BsonDocument>("restaurants");
            await collection.InsertOneAsync(document);
        }
コード例 #7
0
        private async Task SaveObjectToMongoDb(string jsonPayload)
        {
            var client = new MongoClient(
                "mongodb://34.246.18.10:27017"
                );
            var database   = client.GetDatabase("twitter");
            var collection = database.GetCollection <BsonDocument>("stream");

            MongoDB.Bson.BsonDocument document
                = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(jsonPayload);

            var sw = Stopwatch.StartNew();
            await collection.InsertOneAsync(document).ConfigureAwait(false);

            sw.Stop();
            Console.WriteLine($"Insert document take {sw.ElapsedMilliseconds} ms");
        }
コード例 #8
0
        // Functions for sending GET requests for the scope we have been granted to access to

        public void SendRequest()
        {
            var    userID     = "36XJP9";
            string jsonUserID = @"{userID:'36XJP9'}";

            string urlworkout = "https://api.fitbit.com/1/user/" + userID + "/activities/date/2016-01-01.json";


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlworkout);

            request.Method = "GET";
            request.Headers["Authorization"] = "Bearer " + _accesToken;
            request.Accept = "application/json";


            //Response results - contains requested data
            WebResponse response;
            var         results = "";

            response = request.GetResponse();
            StreamReader HttpStreamReader = new StreamReader(response.GetResponseStream());

            results = HttpStreamReader.ReadToEnd();

            JObject resultsJSON = JObject.Parse(results);

            Console.Write(resultsJSON);

            var combinedJson = JsonConvert.SerializeObject(new
            {
                jsonUserID,
                resultsJSON
            });

            MongoDB.Bson.BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(combinedJson);
            FitBitContext             ctx      = new FitBitContext();

            ctx.Users.InsertOne(document);



            response.Close();
            HttpStreamReader.Close();
        }
コード例 #9
0
        public int parse_json_file(string json_full_filename)
        {
            if (json_full_filename != "")
            {
                bool json_file_exist = System.IO.File.Exists(json_full_filename);

                if (json_file_exist)
                {
                    // read file
                    string json_str = System.IO.File.ReadAllText(@json_full_filename);

                    // parse and deserialize bson
                    bson = BsonSerializer.Deserialize<BsonDocument>(json_str);

                    return 0;
                }
            }
            return 1;
        }
コード例 #10
0
        public override void Build(MongoDB.Bson.BsonDocument bsonPanelSetOrder, int panelSetId)
        {
            base.Build(bsonPanelSetOrder, panelSetId);

            string          reportNo = bsonPanelSetOrder.GetValue("ReportNo").ToString();
            MongoCollection surgicalSpecimenTable = this.m_SQLTransferDatabase.GetCollection <BsonDocument>("tblSurgicalSpecimen");
            MongoCursor     mongoCursor           = surgicalSpecimenTable.FindAs <BsonDocument>(Query.EQ("ReportNo", reportNo));

            BsonArray bsonArray = new BsonArray();

            foreach (BsonDocument bsonSurgicalSpecimen in mongoCursor)
            {
                string surgicalSpecimenId = bsonSurgicalSpecimen.GetValue("SurgicalSpecimenId").AsString;
                this.BuildIC(bsonSurgicalSpecimen, surgicalSpecimenId);
                this.BuildStainResult(bsonSurgicalSpecimen, surgicalSpecimenId);
                this.BuildICD9BillingCode(bsonSurgicalSpecimen, surgicalSpecimenId);

                bsonArray.Add(bsonSurgicalSpecimen);
            }

            bsonPanelSetOrder.Add("SurgicalSpecimenCollection", bsonArray);

            MongoCollection surgicalAuditTable  = this.m_SQLTransferDatabase.GetCollection <BsonDocument>("tblSurgicalAudit");
            MongoCursor     surgicalAuditCursor = surgicalAuditTable.FindAs <BsonDocument>(Query.EQ("ReportNo", reportNo));

            BsonArray surgicalAuditArray = new BsonArray();

            foreach (BsonDocument bsonSurgicalAudit in surgicalAuditCursor)
            {
                string surgicalAuditId = bsonSurgicalAudit.GetValue("SurgicalAuditId").AsString;
                this.BuildSurgicalSpecimenAudit(bsonSurgicalAudit, surgicalAuditId);

                surgicalAuditArray.Add(bsonSurgicalAudit);
            }

            bsonPanelSetOrder.Add("SurgicalAuditCollection", surgicalAuditArray);
        }
コード例 #11
0
        string debug_message_from_constructor = ""; // need to store it and show on 1st tick, otherwise debug messages are wiped out when ticks start to arrive
        public _SMA_Crossing_Response()
            : base()
        {
            string[] args = MyGlobals.args;

            bool show_help = false;
            string kadina_config = "";
            string response_config = "";
            int repeat = 1;

            var p = new OptionSet() {
            { "k|kadina-config=", "response json configuration file",
              v => kadina_config = v },
            { "r|response-config=", "response json configuration file",
              v => response_config = v },
            { "z|zepeat=", 
                "the number of {TIMES} to repeat the greeting.\n" + 
                    "this must be an integer.",
              (int v) => repeat = v },
            { "v", "increase debug message verbosity",
              v => { if (v != null) ++verbosity; } },
            { "h|help",  "show this message and exit", 
              v => show_help = v != null },
        };

            List<string> extra;
            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("greet: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `greet --help' for more information.");
                return;
            }

            if (show_help)
            {
                ShowHelp(p);
                return;
            }



            // get settings from json file
            if (response_config != "")
            {
                response_parameters_holder = new ResponseParametersHolder();
                response_parameters_holder.parse_json_file(response_config);
                bson = response_parameters_holder.bson;
                _slow_ma_bar = BsonSerializer.Deserialize<int>(bson["_slow_ma_bar"].ToJson());
                _fast_ma_bar = BsonSerializer.Deserialize<int>(bson["_fast_ma_bar"].ToJson());

                // Custom name of response set by you
                Name = BsonSerializer.Deserialize<string>(bson["name"].ToJson());

                debug_message_from_constructor = "parsed json file - OK (set slow_ma=" + _slow_ma_bar + " fast_ma=" + _fast_ma_bar;
                D(debug_message_from_constructor); // wtf? why this message never showed up? seems messages are cleaned right before 1st GotTick();
            }


            // track_symbols_NewTxt() called when new text label is added
            track_symbols.NewTxt += new TextIdxDelegate(track_symbols_NewTxt);

            //     Names of the indicators used by your response.  Length must correspond to
            //     actual indicator values send with SendIndicators event
            Indicators = GenericTracker.GetIndicatorNames(gens());

            track_barlists.GotNewBar += new SymBarIntervalDelegate(GotNewBar);
        }
コード例 #12
0
        string debug_message_from_constructor = ""; // need to store it and show on 1st tick, otherwise debug messages are wiped out when ticks start to arrive
        public _TS_step_by_step()
            : base()
        {
            System.Diagnostics.Debug.WriteLine("class _TS_step_by_step constructor entry point");
            string[] args = MyGlobals.args;     // extract main(args) from MyGlobals (we store main(args) in Kadina Program.cs, ASP, etc.)
            if (args == null)
            {
                throw new Exception("you forgot to set MyGlobals.args (in Kadina or asp or in whatever you use)");
            }

            string response_config = "";
            //string storage_service_config_jsonfile = "";
            string rabbitmq_config_jsonfile = "";

            var p = new OptionSet() {
                { "a|response-config=", "response json configuration file",
                 v => response_config = v },
                //{ "c|storage-service-config=", "path to storage_service json configuration file",
                //  v => storage_service_config_jsonfile = v},
                {"r|rabbitmq-config=", "path to rabbitmq json configuration file",
                  v => rabbitmq_config_jsonfile = v}
            };

            // parse  cmd-line args
            List<string> extra;
            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                System.Diagnostics.Debug.WriteLine("Try `--help' for more information.");
                return;
            }

            // get settings from json file
            if (response_config != "")
            {
                response_parameters_holder = new ResponseParametersHolder();
                response_parameters_holder.parse_json_file(response_config);
                bson = response_parameters_holder.bson;

                //_ema_bar = Convert.ToInt32(bson["_ema_bar"]);
                _ema_bar = BsonSerializer.Deserialize<int>(bson["_ema_bar"].ToJson());
                _response_barsize_s = BsonSerializer.Deserialize<int>(bson["_response_barsize_s"].ToJson());
                _stop_k = BsonSerializer.Deserialize<double>(bson["_stop_k"].ToJson());
                _target_price_k = BsonSerializer.Deserialize<double>(bson["_target_price_k"].ToJson());

                //_target_price_k = Convert.ToDouble(bson["_target_price_k"]);

                // Custom name of response set by you
                Name = BsonSerializer.Deserialize<string>(bson["name"].ToJson());

                //debug_message_from_constructor = "parsed json file - OK (set slow_ma=" + _slow_ma_bar + " fast_ma=" + _fast_ma_bar;
                //D(debug_message_from_constructor); // wtf? why this message never showed up? seems messages are cleaned right before 1st GotTick();

                //ResponseParametersHolder storage_service_parameters_holder = new ResponseParametersHolder();
                //storage_service_parameters_holder.parse_json_file(storage_service_config_jsonfile);
                //storage_service_parameters_bson = storage_service_parameters_holder.bson;

                ResponseParametersHolder rabbitmq_parameters_holder = new ResponseParametersHolder();
                rabbitmq_parameters_holder.parse_json_file(rabbitmq_config_jsonfile);
                rabbitmq_parameters_bson = rabbitmq_parameters_holder.bson;
                call_me_from_child_constructor();
            }


            // track_symbols_NewTxt() called when new text label is added
            track_symbols.NewTxt += new TextIdxDelegate(track_symbols_NewTxt);

            //     Names of the indicators used by your response.  Length must correspond to
            //     actual indicator values send with SendIndicators event
            Indicators = GenericTracker.GetIndicatorNames(gens());

            //[_response_barsize_s, 22]
            track_barlists = new BarListTracker(new int[] { _response_barsize_s, 22 }, new BarInterval[] { BarInterval.CustomTime, BarInterval.CustomTime });
            track_barlists.GotNewBar += new SymBarIntervalDelegate(GotNewBar);
        }
コード例 #13
0
        public void main(string[] args)
        {
            // ============================================================================
            // http://stackoverflow.com/questions/5624934/convert-string-into-mongodb-bsondocument
            string json_str = @"{ 
                'some_str' : 'bar', 
                'int_arr' : [1,2,3,4,5],
                'int_val' : 1,
                'decimal_val' : 99.99,
                'double_val' : 88.88
            }";

            // case 1 of 2: we convert json string to bson document
            MongoDB.Bson.BsonDocument bson1
                = BsonSerializer.Deserialize <BsonDocument>(json_str);

            // case 2 of 2: we convert json string to bson document (same, but more elegant)
            //
            BsonDocument bson2 = BsonDocument.Parse(json_str);

            // now we extract values from bson document. Below you'll find several examples (by different data types)
            //
            string some_str3 = BsonSerializer.Deserialize <string>(bson2["some_str"].ToJson());
            string some_str  = BsonSerializer.Deserialize <string>(bson2["some_str"].ToJson());

            int[]   int_arr     = BsonSerializer.Deserialize <int[]>(bson2["int_arr"].ToJson());
            int     int_val     = BsonSerializer.Deserialize <int>(bson2["int_val"].ToJson());
            decimal decimal_val = BsonSerializer.Deserialize <decimal>(bson2["decimal_val"].ToJson());
            double  double_val  = BsonSerializer.Deserialize <double>(bson2["double_val"].ToJson());

            // now same action, but using Json.NET (imho this way is better (more readable and not mongo-library dependant)
            // todo: if we choose this way make sure it's bson docs are really compatible with mongo bson docs.
            // OR may be I like the 1st way better now ...  ;)
            //
            JToken root = JObject.Parse(json_str);

            JToken some_str2_token = root["some_str"];
            string some_str2       = some_str2_token.ToString();

            JToken int_arr_token = root["int_arr"];

            int[] int_arr2 = JsonConvert.DeserializeObject <int[]>(int_arr_token.ToString());

            JToken int_val_token = root["int_val"];
            int    int_val2      = JsonConvert.DeserializeObject <int>(int_val_token.ToString());

            JToken  decimal_val_token = root["decimal_val"];
            decimal decimal_val2      = JsonConvert.DeserializeObject <decimal>(decimal_val_token.ToString());

            JToken double_val_token = root["double_val"];
            double double_val2      = JsonConvert.DeserializeObject <double>(double_val_token.ToString());

            // noop just for breakpoint ;)
            ((Action)(() => { }))();

            //
            // ============================================================================
            // [on topic of Query Mongo]
            // How to deserialize a BsonDocument object back to class
            // http://stackoverflow.com/questions/9478613/how-to-deserialize-a-bsondocument-object-back-to-class
            //
            //QueryDocument _document = new QueryDocument("key", "value");

            //MongoCursor<BsonDocument> _documentsReturned =
            //                          _collection.FindAs<BsonDocument>(_document);

            //foreach (BsonDocument _document1 in _wordOntologies)
            //{
            //    //deserialize _document1
            //    //?
            //}
            // ============================================================================
            // [q] how to create new BsonDocument?
            // [a]
            //var document = new BsonDocument {
            //    { "author", "joe" },
            //    { "title", "yet another blog post" },
            //    { "text", "here is the text..." },
            //    { "tags", new BsonArray { "example", "joe" } },
            //    { "comments", new BsonArray {
            //        new BsonDocument { { "author", "jim" }, { "comment", "I disagree" } },
            //        new BsonDocument { { "author", "nancy" }, { "comment", "Good post" } }
            //    }}
            //};
            //// ============================================================================
            // MongoDB C# - Getting BsonDocument for an Element that doesn't exist
            // http://stackoverflow.com/questions/6628794/mongodb-c-sharp-getting-bsondocument-for-an-element-that-doesnt-exist
            // There is also an overload that lets you provide a default value:
            //
            // BsonDocument document;
            // var firstName = (string)document["FirstName", null];
            // // or
            // var firstName = (string)document["FirstName", "N/A"];
            //
            // OR
            //
            // var b = new BsonDocument();
            // var exists = b.Contains("asdfasdf");
            //// ============================================================================

            //MyGlobals.args = args;
            // .... and then in any other place in app we can access global args:
            //string[] args = MyGlobals.args;

            string storage_service_config_json = "";
            string rabbitmq_config_json        = "";
            string mongodb_config_json         = "";

            var p = new OptionSet()
            {
                { "c|storage-service-config=", "path to storage_service json configuration file",
                  v => storage_service_config_json = v },
                { "r|rabbitmq-config=", "path to rabbitmq json configuration file",
                  v => rabbitmq_config_json = v },
                { "m|mongodb-config=", "path to mongodb json configuration file",
                  v => mongodb_config_json = v }
            };

            // parse  cmd-line args
            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `--help' for more information.");
                return;
            }

            // get parameters documents
            if (storage_service_config_json != "")
            {
                parameters_holder = new ResponseParametersHolder();
                parameters_holder.parse_json_file(storage_service_config_json);
                storage_service_parameters = parameters_holder.response_parameters;

                parameters_holder = new ResponseParametersHolder();
                parameters_holder.parse_json_file(rabbitmq_config_json);
                rabbitmq_parameters = parameters_holder.response_parameters;

                parameters_holder = new ResponseParametersHolder();
                parameters_holder.parse_json_file(mongodb_config_json);
                mongodb_parameters = parameters_holder.response_parameters;

                //_ema_bar = Convert.ToInt32(storage_service_parameters["_ema_bar"]);
                //_response_barsize_s = Convert.ToInt32(storage_service_parameters["_response_barsize_s"]);
                //_stop_k = Convert.ToDouble(storage_service_parameters["_stop_k"]);
                //_target_price_k = Convert.ToDouble(storage_service_parameters["_target_price_k"]);

                // Custom name of response set by you
                //Name = storage_service_parameters["name"];
            }



            // extract individual rabbitmq parameters
            //
            string            exchange_name = rabbitmq_parameters["exchange_name"];
            string            exchange_type = rabbitmq_parameters["exchange_type"];
            ConnectionFactory conn_factory  = new ConnectionFactory();

            conn_factory.HostName = rabbitmq_parameters["host_name"];
            conn_factory.UserName = rabbitmq_parameters["user_name"];
            conn_factory.Password = rabbitmq_parameters["password"];

            // extract storage_service parameters
            //
            string queue_name  = storage_service_parameters["queue_name"];
            string routing_key = storage_service_parameters["routing_key"];   // no need to provide routing key for 'fanout' exchange. "rout";


            // extract mongodb parameters
            //
            mongodb_connection_string = mongodb_parameters["mongodb_connection_string"];
            mongodb_database_name     = mongodb_parameters["mongodb_database_name"];
            mongodb_collection_name   = mongodb_parameters["mongodb_collection_name"];

            //---------------------------------------------------------------- progress bar end --------------
            // Create the thread object. This does not start the thread.
            Worker_console_hartbeat_progressbar worker_console_hartbeat_progressbar = new Worker_console_hartbeat_progressbar();
            Thread workerThread = new Thread(worker_console_hartbeat_progressbar.DoWork);

            // Start the worker thread.
            workerThread.Start();
            //---------------------------------------------------------------- progress bar end --------------

            System.Console.WriteLine("Welcome to storage_service (part of tradelink.afterlife)!");
            System.Console.WriteLine("---------------------------------------------------------");
            System.Console.WriteLine("connecting to mongodb...");


            // prepare mongo
            MongoClient   client   = new MongoClient(mongodb_connection_string);
            MongoServer   server   = client.GetServer();
            MongoDatabase database = server.GetDatabase(mongodb_database_name); // "test" is the name of the database

            mongodb_collection = database.GetCollection <BsonDocument>(mongodb_collection_name);

            System.Console.WriteLine("connecting to rabbitmq... wwarning: sometimes it hungs here");

            // create rabbitmq connection
            IConnection conn = conn_factory.CreateConnection();
            // create channel
            IModel chan = conn.CreateModel();

            chan.ExchangeDeclare(exchange_name,
                                 exchange_type,
                                 false, // durable
                                 false, // autodelete
                                 null); // args
            chan.QueueDeclare(queue_name,
                              false,    // durable
                              false,    // exclusive
                              true,     // autodelete
                              null);    // args
            chan.QueueBind(queue_name, exchange_name, routing_key);

            EventingBasicConsumer c_consumer = new EventingBasicConsumer {
                Model = chan
            };

            c_consumer.Received += my_callback;
            System.Console.WriteLine("ready to consume messages...");

            // blocking call:
            chan.BasicConsume(queue_name,
                              false,
                              c_consumer);

            /*
             * EventingBasicConsumer r_consumer = new EventingBasicConsumer {Model = chan};
             * r_consumer.Received += rate_limit_notify;
             * chan.BasicConsume("rate_limit",
             *                false,
             *                r_consumer);
             */
        }
コード例 #14
0
        public static void TestSer()
        {
            BsonClassMap.RegisterClassMap<SagaTest.MyState>(
                x =>
                {
                    x.AutoMap();
                    x.SetIgnoreExtraElements(true);

                });

            var bd = new MongoDB.Bson.BsonDocument();
            MongoDB.Bson.IO.BsonDocumentWriter bdw = (BsonDocumentWriter) BsonDocumentWriter.Create(bd);

            var obj = new SagaTest.MyState { Collected = new List<int>(), Last = DateTime.Now };

            MongoDB.Bson.Serialization.BsonSerializer.Serialize(bdw, obj);
            bdw.Flush();
            /*
            bd["_t"] = MongoDB.Bson.Serialization.TypeNameDiscriminator.GetDiscriminator(obj.GetType());
            bd["version"] = "3823424";
            Console.WriteLine(bd.ToJson());
            Type t = TypeNameDiscriminator.GetActualType(bd["_t"].AsString);
            var obj2 = BsonSerializer.Deserialize(bd, t);
            Console.WriteLine("deser: " + obj2);
             */
        }