Esempio n. 1
0
        public void importData(string data)
        {
            var options = new MongoInsertOptions()
            {
                Flags = InsertFlags.ContinueOnError
            };

            BsonDocument doc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(data);

            foreach (string name in doc.Names)
            {
                try
                {
                    var result = mongodb.getDB().GetCollection(name).InsertBatch(doc[name].AsBsonArray, options);
                }
                catch { errors++; }
                //.Insert(doc[name].AsBsonArray); //Untested
            }

            /*int errors = 0;
             * foreach(string name in doc.Names)
             * {
             *  foreach (BsonDocument entry in doc[name].AsBsonArray)
             *      try
             *      {
             *          mongodb.getCollection(name).Insert(entry);
             *      }
             *      catch { errors++;  }
             * }*/
        }
Esempio n. 2
0
        private void Initialize()
        {
            lock (Sync)
            {
                var mongoUrl    = MongoUrl.Create(_connectionString);
                var mongoClient = new MongoClient(mongoUrl);
                var server      = mongoClient.GetServer();
                var database    = server.GetDatabase(mongoUrl.DatabaseName);
                if (!database.CollectionExists(_collectionName))
                {
                    var options = CollectionOptions
                                  .SetCapped(true)
                                  .SetAutoIndexId(true)
                                  .SetMaxSize(_maxSize);

                    if (_maxDocuments != int.MaxValue)
                    {
                        options.SetMaxDocuments(_maxDocuments);
                    }

                    database.CreateCollection(_collectionName, options);
                }

                _collection         = database.GetCollection(_collectionName);
                _mongoInsertOptions = new MongoInsertOptions {
                    CheckElementNames = false
                };
            }
        }
Esempio n. 3
0
        public void Save(IEnumerable <Object> docs)
        {
            var mongoInsertOptions = new MongoInsertOptions();

            mongoInsertOptions.WriteConcern = WriteConcern.Acknowledged;
            _collection.InsertBatch(docs, mongoInsertOptions);
        }
Esempio n. 4
0
        public override SafeModeResult Save(Type nominalType, object document, MongoInsertOptions options)
        {
            if (!this.AllowSave)
            {
                throw new MongoDB.Driver.MongoCommandException(
                          string.Format("Cannot save document {0}, this collection does not allow saving objects of type {1}", document, nominalType));
            }

            if (writer != null)
            {
                this.writer.WriteLine("Save:");
                this.writer.WriteLine("Type: " + (nominalType == null ? "Null" : nominalType.ToString()));
                if (document == null)
                {
                    this.writer.WriteLine("Document: Null");
                }
                else
                {
                    var id = GetId(document);
                    if (id == null)
                    {
                        this.writer.WriteLine("Document: " + document.ToString());
                    }
                    else
                    {
                        this.writer.WriteLine(string.Format("Document ID: \"{0}\"", id));
                    }
                }
                this.writer.WriteLine();
                this.writer.Flush();
            }

            return(mCollection.Save(nominalType, document, options));
        }
Esempio n. 5
0
 public virtual WriteConcernResult Add(TEntity document, MongoInsertOptions iOptions = null)
 {
     if (iOptions == null)
     {
         return(this.context.GetCollection <TEntity>().Insert(document));
     }
     return(this.context.GetCollection <TEntity>().Insert(document, iOptions));
 }
Esempio n. 6
0
 public static WriteConcernResult zSave(this MongoCollection collection, BsonDocument document, MongoInsertOptions options = null)
 {
     if (options == null)
     {
         options = new MongoInsertOptions();
     }
     MongoLog.CurrentMongoLog.LogSave(collection, document, options);
     return(MongoLog.CurrentMongoLog.ExecuteAndLogResult(() => collection.Save(document, options)));
 }
Esempio n. 7
0
 public static void zSave(this IEnumerable <BsonDocument> documents, MongoCollection collection, MongoInsertOptions options = null)
 {
     if (options == null)
     {
         options = new MongoInsertOptions();
     }
     foreach (BsonDocument document in documents)
     {
         collection.zSave(document, options);
     }
 }
Esempio n. 8
0
 public void LogSave(MongoCollection collection, BsonDocument document, MongoInsertOptions options = null)
 {
     if (_writeToFile == null)
     {
         return;
     }
     _writeToFile.Write("{0:yyyy-MM-dd HH:mm:ss.ffffff} ", DateTime.Now);
     _writeToFile.Write("Save : {0} document ", collection.zGetFullName());
     _writeToFile.Write(document.ToJson());
     _writeToFile.Write(" options ");
     _writeToFile.Write(options.ToJson());
 }
Esempio n. 9
0
        public WriteConcernResult Save(T item, MongoInsertOptions options)
        {
            OnBeforeSave(item);

            AuditAddEdit(item);

            var ret = Collection.Save(item, options);

            OnAfterSave(item);

            return(ret);
        }
Esempio n. 10
0
        private void addNewUser()
        {
            var options = new MongoInsertOptions(names)
            {
                SafeMode = SafeMode.True
            };
            BsonDocument name = new BsonDocument {
                { "name", newName }
            };

            names.Save(name, options);
        }
Esempio n. 11
0
        public static void UpdateDocuments(string databaseName, string collectionName, string query, Action <BsonDocument> updateDocument, string sort = null, int limit = 0, string queryOptions = null,
                                           MongoInsertOptions saveOptions = null, string server = null)
        {
            MongoCollection collection = MongoCommand.GetDatabase(server, databaseName).GetCollection(collectionName);

            Trace.Write("UpdateDocuments : {0} query ", collection.zGetFullName());

            QueryDocument queryDoc = query.zToQueryDocument();

            Trace.Write(queryDoc.ToJson());

            SortByWrapper sortByWrapper = null;

            if (sort != null)
            {
                sortByWrapper = sort.zToSortByWrapper();
                Trace.Write(" sort {0}", sortByWrapper.ToJson());
            }

            if (limit != 0)
            {
                Trace.Write(" limit {0}", limit);
            }

            BsonDocument queryOptionsDoc = null;

            if (queryOptions != null)
            {
                queryOptionsDoc = queryOptions.zDeserializeToBsonDocument();
                Trace.Write(" options {0}", queryOptionsDoc.ToJson());
            }

            Trace.WriteLine();

            if (saveOptions == null)
            {
                saveOptions = new MongoInsertOptions();
            }

            foreach (BsonDocument document in collection.zFind <BsonDocument>(queryDoc, sort: sortByWrapper, limit: limit, options: queryOptionsDoc))
            {
                updateDocument(document);

                Trace.Write("  Save : {0} document ", collection.zGetFullName());
                Trace.Write(document.ToJson());
                Trace.Write(" options ");
                Trace.Write(saveOptions.ToJson());
                Trace.WriteLine();

                collection.zSave(document, saveOptions);
            }
        }
Esempio n. 12
0
        public void Flush()
        {
            long tobson = 0;

            int index = 0;

            Task[] tasks = new Task[_inMemoryDatabase.Collections.Keys.Count];

            foreach (var pair in _inMemoryDatabase.Collections)
            {
                var mongoSettings = new MongoCollectionSettings {
                    AssignIdOnInsert = false
                };

                var mongoCollection    = Database.GetCollection(typeof(BsonDocument), pair.Key.CollectionName, mongoSettings);
                var inMemoryCollection = (IInMemoryCollection)pair.Value;

                var stopwatch = Stopwatch.StartNew();
                var docs      = BsonDocumentWrapper.CreateMultiple(inMemoryCollection.Documents.Values);
                stopwatch.Stop();
                //Console.WriteLine("Collection {0} serialized to bson in {1:n0} ms", pair.Key, stopwatch.ElapsedMilliseconds);
                tobson += stopwatch.ElapsedMilliseconds;

                stopwatch.Start();

                tasks[index] = Task.Factory.StartNew(() =>
                {
                    var mongoInsertOptions          = new MongoInsertOptions();
                    mongoInsertOptions.WriteConcern = WriteConcern.Acknowledged;
                    mongoCollection.InsertBatch(docs);
                }, TaskCreationOptions.LongRunning);


                stopwatch.Stop();
                //Console.WriteLine("Collection {0} inserted to MongoDB in {1:n0} ms", pair.Key, stopwatch.ElapsedMilliseconds);

                index++;
            }

            Task.WaitAll(tasks);

            //Console.WriteLine("Total time for serialization: {0:n0} ms", tobson);
        }
        public void TestEmptyElementNameAllowed()
        {
            var collection = Configuration.GetTestCollection <BsonDocument>();

            collection.Drop();
            var document = new BsonDocument {
                { "_id", 1 }, { "", 2 }
            };
            var insertOptions = new MongoInsertOptions {
                CheckElementNames = false
            };

            collection.Insert(document, insertOptions);
            var rehydrated = collection.FindOne();

            Assert.AreEqual(2, rehydrated.ElementCount);
            Assert.AreEqual(1, rehydrated["_id"].AsInt32);
            Assert.AreEqual(2, rehydrated[""].AsInt32);
        }
Esempio n. 14
0
        public void Modify <T>(ICommandRepository commandRepository, Action <T> modifyAction, T entity) where T : class
        {
            var mongoDatabase = commandRepository.ObjectContext as MongoDatabase;

            if (mongoDatabase == null)
            {
                throw new NotSupportedException("Modify can only be used with a MongoDatabase context");
            }

            var mongoInsertOptions = new MongoInsertOptions
            {
                WriteConcern      = WriteConcern,
                CheckElementNames = CheckElementNames
            };

            WriteConcernResult = mongoDatabase.GetCollection <T>(typeof(T).FullName).Save(entity, mongoInsertOptions);

            var evnt = new MongoDbEntityModifiedEvent(commandRepository, entity, WriteConcernResult);

            commandRepository.RaiseEvent(evnt);
        }
Esempio n. 15
0
        public void TestInsertUpdateAndSaveWithElementNameStartingWithDollarSign()
        {
            // starting with version 2.5.2 the server got stricter about dollars in element names
            // so this test should only be run when testing against older servers
            var server = Configuration.TestServer;

            if (server.BuildInfo.Version < new Version(2, 6, 0))
            {
                var database   = Configuration.TestDatabase;
                var collection = Configuration.TestCollection;
                collection.Drop();

                var document = new BsonDocument
                {
                    { "_id", 1 },
                    { "v", new BsonDocument("$x", 1) } // server doesn't allow "$" at top level
                };
                var insertOptions = new MongoInsertOptions {
                    CheckElementNames = false
                };
                collection.Insert(document, insertOptions);
                document = collection.FindOne();
                Assert.AreEqual(1, document["v"]["$x"].AsInt32);

                document["v"]["$x"] = 2;
                var query         = Query.EQ("_id", 1);
                var update        = Update.Replace(document);
                var updateOptions = new MongoUpdateOptions {
                    CheckElementNames = false
                };
                collection.Update(query, update, updateOptions);
                document = collection.FindOne();
                Assert.AreEqual(2, document["v"]["$x"].AsInt32);

                document["v"]["$x"] = 3;
                collection.Save(document, insertOptions);
                document = collection.FindOne();
                Assert.AreEqual(3, document["v"]["$x"].AsInt32);
            }
        }
Esempio n. 16
0
        public static void Insert <TDocument>(string databaseName, string collectionName, TDocument document, MongoInsertOptions options = null, string server = null)
        {
            MongoCollection collection = MongoCommand.GetDatabase(server, databaseName).GetCollection(collectionName);

            Trace.Write("Insert : {0}", collection.zGetFullName());
            Trace.Write(" document ");
            Trace.Write(document.ToJson());
            if (options == null)
            {
                options = new MongoInsertOptions();
            }
            Trace.Write(" check element names {0} flags {1}", options.CheckElementNames, options.Flags);
            try
            {
                WriteConcernResult result = collection.zInsert(document, options);
                TraceResult(result);
            }
            finally
            {
                Trace.WriteLine();
            }
        }
Esempio n. 17
0
        public void TestInsertUpdateAndSaveWithElementNameStartingWithDollarSign()
        {
            var server     = MongoServer.Create("mongodb://localhost/?safe=true;slaveOk=true");
            var database   = server["onlinetests"];
            var collection = database["test"];

            collection.Drop();

            var document = new BsonDocument {
                { "_id", 1 },
                { "v", new BsonDocument("$x", 1) } // server doesn't allow "$" at top level
            };
            var insertOptions = new MongoInsertOptions(collection)
            {
                CheckElementNames = false
            };

            collection.Insert(document, insertOptions);
            document = collection.FindOne();
            Assert.AreEqual(1, document["v"].AsBsonDocument["$x"].AsInt32);

            document["v"].AsBsonDocument["$x"] = 2;
            var query         = Query.EQ("_id", 1);
            var update        = Update.Replace(document);
            var updateOptions = new MongoUpdateOptions(collection)
            {
                CheckElementNames = false
            };

            collection.Update(query, update, updateOptions);
            document = collection.FindOne();
            Assert.AreEqual(2, document["v"].AsBsonDocument["$x"].AsInt32);

            document["v"].AsBsonDocument["$x"] = 3;
            collection.Save(document, insertOptions);
            document = collection.FindOne();
            Assert.AreEqual(3, document["v"].AsBsonDocument["$x"].AsInt32);
        }
Esempio n. 18
0
        public virtual void Add(T item)
        {
            var database = client.GetServer().GetDatabase("tabletop");

            var bsonDoc = new BsonDocument();
            var bsonDocumentWriterSettings = new BsonDocumentWriterSettings();

            bsonDocumentWriterSettings.GuidRepresentation = GuidRepresentation.Standard;
            var bsonDocumentWriter = new BsonDocumentWriter(bsonDoc, bsonDocumentWriterSettings);

            BsonSerializer.Serialize(bsonDocumentWriter, item);
            var collection  = database.GetCollection(Util.Mongo.MongoUtilities.GetCollectionFromType(item.GetType()));
            var saveOptions = new MongoInsertOptions();

            saveOptions.WriteConcern = WriteConcern.Acknowledged;

            var succeeded = collection.Save(bsonDoc, saveOptions);

            if (!succeeded.Ok)
            {
                throw new Exception(succeeded.LastErrorMessage);
            }
        }
Esempio n. 19
0
        public void TestInsertUpdateAndSaveWithElementNameStartingWithDollarSign()
        {
            var server     = Configuration.TestServer;
            var database   = Configuration.TestDatabase;
            var collection = Configuration.TestCollection;

            collection.Drop();

            var document = new BsonDocument
            {
                { "_id", 1 },
                { "v", new BsonDocument("$x", 1) } // server doesn't allow "$" at top level
            };
            var insertOptions = new MongoInsertOptions {
                CheckElementNames = false
            };

            collection.Insert(document, insertOptions);
            document = collection.FindOne();
            Assert.AreEqual(1, document["v"].AsBsonDocument["$x"].AsInt32);

            document["v"].AsBsonDocument["$x"] = 2;
            var query         = Query.EQ("_id", 1);
            var update        = Update.Replace(document);
            var updateOptions = new MongoUpdateOptions {
                CheckElementNames = false
            };

            collection.Update(query, update, updateOptions);
            document = collection.FindOne();
            Assert.AreEqual(2, document["v"].AsBsonDocument["$x"].AsInt32);

            document["v"].AsBsonDocument["$x"] = 3;
            collection.Save(document, insertOptions);
            document = collection.FindOne();
            Assert.AreEqual(3, document["v"].AsBsonDocument["$x"].AsInt32);
        }
Esempio n. 20
0
 /// <summary>
 /// 指定插入选项向该集合中插入一条文档
 /// </summary>
 /// <param name="document">要写入的文档</param>
 /// <param name="options">插入选项</param>
 /// <returns>写入结果</returns>
 public virtual WriteConcernResult Insert(TDocument document, MongoInsertOptions options)
 {
     return(this.collection.Insert(document, options));
 }
Esempio n. 21
0
 /// <summary>
 /// 指定插入选项向该集合中保存一条文档
 /// </summary>
 /// <param name="document">要保存的文档</param>
 /// <param name="options">插入选项</param>
 /// <returns>保存结果</returns>
 public virtual WriteConcernResult Save(TDocumentWithID document, MongoInsertOptions options)
 {
     return(this.collection.Save(document, options));
 }
Esempio n. 22
0
 /// <summary>
 /// 指定插入选项向该集合中插入文档集合
 /// </summary>
 /// <param name="documents">要写入的文档集合</param>
 /// <param name="options">插入选项</param>
 /// <returns>写入结果</returns>
 public virtual IEnumerable <WriteConcernResult> InsertBatch(IEnumerable <TDocument> documents, MongoInsertOptions options)
 {
     return(this.collection.InsertBatch(documents, options));
 }
Esempio n. 23
0
        //        private static void LoadHandlingEventData()
        //        {
        //            const string handlingEventSql =
        //                "insert into HandlingEvent (completionTime, registrationTime, type, location_id, voyage_id, cargo_id) " +
        //                "values (?, ?, ?, ?, ?, ?)";
        //
        //            var handlingEventArgs = new[]
        //                {
        //                    //XYZ (SESTO-FIHEL-DEHAM-CNHKG-JPTOK-AUMEL)
        //                    new object[] {Ts(0), Ts((0)), "RECEIVE", 1, null, 1},
        //                    new object[] {Ts((4)), Ts((5)), "LOAD", 1, 1, 1},
        //                    new object[] {Ts((14)), Ts((14)), "UNLOAD", 5, 1, 1},
        //                    new object[] {Ts((15)), Ts((15)), "LOAD", 5, 1, 1},
        //                    new object[] {Ts((30)), Ts((30)), "UNLOAD", 6, 1, 1},
        //                    new object[] {Ts((33)), Ts((33)), "LOAD", 6, 1, 1},
        //                    new object[] {Ts((34)), Ts((34)), "UNLOAD", 3, 1, 1},
        //                    new object[] {Ts((60)), Ts((60)), "LOAD", 3, 1, 1},
        //                    new object[] {Ts((70)), Ts((71)), "UNLOAD", 4, 1, 1},
        //                    new object[] {Ts((75)), Ts((75)), "LOAD", 4, 1, 1},
        //                    new object[] {Ts((88)), Ts((88)), "UNLOAD", 2, 1, 1},
        //                    new object[] {Ts((100)), Ts((102)), "CLAIM", 2, null, 1},
        //                    //ZYX (AUMEL - USCHI - DEHAM -)
        //                    new object[] {Ts((200)), Ts((201)), "RECEIVE", 2, null, 3},
        //                    new object[] {Ts((202)), Ts((202)), "LOAD", 2, 2, 3},
        //                    new object[] {Ts((208)), Ts((208)), "UNLOAD", 7, 2, 3},
        //                    new object[] {Ts((212)), Ts((212)), "LOAD", 7, 2, 3},
        //                    new object[] {Ts((230)), Ts((230)), "UNLOAD", 6, 2, 3},
        //                    new object[] {Ts((235)), Ts((235)), "LOAD", 6, 2, 3},
        //                    //ABC
        //                    new object[] {Ts((20)), Ts((21)), "CLAIM", 2, null, 2},
        //                    //CBA
        //                    new object[] {Ts((0)), Ts((1)), "RECEIVE", 2, null, 4},
        //                    new object[] {Ts((10)), Ts((11)), "LOAD", 2, 2, 4},
        //                    new object[] {Ts((20)), Ts((21)), "UNLOAD", 7, 2, 4},
        //                    //FGH
        //                    new object[] {Ts(100), Ts(160), "RECEIVE", 3, null, 5},
        //                    new object[] {Ts(150), Ts(110), "LOAD", 3, 3, 5},
        //                    //JKL
        //                    new object[] {Ts(200), Ts(220), "RECEIVE", 6, null, 6},
        //                    new object[] {Ts(300), Ts(330), "LOAD", 6, 3, 6},
        //                    new object[] {Ts(400), Ts(440), "UNLOAD", 5, 3, 6} // Unexpected event
        //                };
        //
        //            ExecuteUpdate(session, handlingEventSql, handlingEventArgs);
        //        }
        //
        //        private static void LoadCarrierMovementData()
        //        {
        //            const string voyageSql = "insert into Voyage (id, voyage_number) values (?, ?)";
        //            var voyageArgs = new[]
        //                {
        //                    new object[] {1, "0101"},
        //                    new object[] {2, "0202"},
        //                    new object[] {3, "0303"}
        //                };
        //            ExecuteUpdate(session, voyageSql, voyageArgs);
        //
        //            const string carrierMovementSql =
        //                "insert into CarrierMovement (id, voyage_id, departure_location_id, arrival_location_id, departure_time, arrival_time, cm_index) " +
        //                "values (?,?,?,?,?,?,?)";
        //
        //            var carrierMovementArgs = new[]
        //                {
        //                    // SESTO - FIHEL - DEHAM - CNHKG - JPTOK - AUMEL (voyage 0101)
        //                    new object[] {1, 1, 1, 5, Ts(1), Ts(2), 0},
        //                    new object[] {2, 1, 5, 6, Ts(1), Ts(2), 1},
        //                    new object[] {3, 1, 6, 3, Ts(1), Ts(2), 2},
        //                    new object[] {4, 1, 3, 4, Ts(1), Ts(2), 3},
        //                    new object[] {5, 1, 4, 2, Ts(1), Ts(2), 4},
        //                    // AUMEL - USCHI - DEHAM - SESTO - FIHEL (voyage 0202)
        //                    new object[] {7, 2, 2, 7, Ts(1), Ts(2), 0},
        //                    new object[] {8, 2, 7, 6, Ts(1), Ts(2), 1},
        //                    new object[] {9, 2, 6, 1, Ts(1), Ts(2), 2},
        //                    new object[] {6, 2, 1, 5, Ts(1), Ts(2), 3},
        //                    // CNHKG - AUMEL - FIHEL - DEHAM - SESTO - USCHI - JPTKO (voyage 0303)
        //                    new object[] {10, 3, 3, 2, Ts(1), Ts(2), 0},
        //                    new object[] {11, 3, 2, 5, Ts(1), Ts(2), 1},
        //                    new object[] {12, 3, 6, 1, Ts(1), Ts(2), 2},
        //                    new object[] {13, 3, 1, 7, Ts(1), Ts(2), 3},
        //                    new object[] {14, 3, 7, 4, Ts(1), Ts(2), 4}
        //                };
        //            ExecuteUpdate(session, carrierMovementSql, carrierMovementArgs);
        //        }
        //
        //        private static void LoadCargoData(ISession session)
        //        {
        //            const string cargoSql =
        //                "insert into Cargo (id, tracking_id, origin_id, spec_origin_id, spec_destination_id, spec_arrival_deadline, transport_status, current_voyage_id, last_known_location_id, is_misdirected, routing_status, calculated_at, unloaded_at_dest) " +
        //                "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        //
        //            var cargoArgs = new[]
        //                {
        //                    new object[]
        //                        {
        //                            1, "XYZ", 1, 1, 2, Ts(10), "IN_PORT", null, 1, false, "ROUTED", Ts(100),
        //                            false
        //                        },
        //                    new object[]
        //                        {
        //                            2, "ABC", 1, 1, 5, Ts(20), "IN_PORT", null, 1, false, "ROUTED", Ts(100),
        //                            false
        //                        },
        //                    new object[]
        //                        {
        //                            3, "ZYX", 2, 2, 1, Ts(30), "IN_PORT", null, 1, false, "NOT_ROUTED", Ts(100),
        //                            false
        //                        },
        //                    new object[]
        //                        {
        //                            4, "CBA", 5, 5, 1, Ts(40), "IN_PORT", null, 1, false, "MISROUTED", Ts(100),
        //                            false
        //                        },
        //                    new object[]
        //                        {
        //                            5, "FGH", 1, 3, 5, Ts(50), "IN_PORT", null, 1, false, "ROUTED", Ts(100),
        //                            false
        //                        }, // Cargo origin differs from spec origin
        //                    new object[]
        //                        {
        //                            6, "JKL", 6, 6, 4, Ts(60), "IN_PORT", null, 1, true, "ROUTED", Ts(100),
        //                            false
        //                        }
        //                };
        //            ExecuteUpdate(session, cargoSql, cargoArgs);
        //        }
        //
        //        private static void LoadLocationData()
        //        {
        //
        //            var locationArgs = new List<Location>
        //                {
        //                    new Location( new UnLocode("SESTO"), "Stockholm") {Id = 1},
        //                    new Location( new UnLocode("AUMEL"), "Melbourne") {Id = 2},
        //                    new Location( new UnLocode("CNHKG"), "Hongkong") {Id = 3},
        //                    new Location( new UnLocode("JPTOK"), "Tokyo") {Id = 4},
        //                    new Location( new UnLocode("FIHEL"), "Helsinki") {Id = 5},
        //                    new Location( new UnLocode("DEHAM"), "Hamburg") {Id = 6},
        //                    new Location( new UnLocode("USCHI"), "Chicago") {Id = 7},
        //                };
        //            ExecuteUpdate(session, locationSql, locationArgs);
        //        }
        //
        //        private static void LoadItineraryData(ISession session)
        //        {
        //            const string legSql =
        //                "insert into Leg (id, cargo_id, voyage_id, load_location_id, unload_location_id, load_time, unload_time, leg_index) " +
        //                "values (?,?,?,?,?,?,?,?)";
        //
        //            var legArgs = new[]
        //                {
        //                    // Cargo 5: Hongkong - Melbourne - Stockholm - Helsinki
        //                    new object[] {1, 5, 1, 3, 2, Ts(1), Ts(2), 0},
        //                    new object[] {2, 5, 1, 2, 1, Ts(3), Ts(4), 1},
        //                    new object[] {3, 5, 1, 1, 5, Ts(4), Ts(5), 2},
        //                    // Cargo 6: Hamburg - Stockholm - Chicago - Tokyo
        //                    new object[] {4, 6, 2, 6, 1, Ts(1), Ts(2), 0},
        //                    new object[] {5, 6, 2, 1, 7, Ts(3), Ts(4), 1},
        //                    new object[] {6, 6, 2, 7, 4, Ts(5), Ts(6), 2}
        //                };
        //            ExecuteUpdate(session, legSql, legArgs);
        //        }


        public static void LoadMongoData(HandlingEventFactory handlingEventFactory,
                                         IHandlingEventRepository handlingEventRepository)
        {
            Console.WriteLine("*** Loading data ***");

            var db                 = Utils.ShippingDb;
            var locations          = GetLocationCollection();
            var mongoInsertOptions = new MongoInsertOptions()
            {
                Flags = InsertFlags.ContinueOnError
            };

            try
            {
                locations.InsertBatch(SampleLocations.GetAll(), mongoInsertOptions);
            }
            catch (WriteConcernException ex)
            {
            }
            var voyages = db.GetCollection <Location>("voyages");


            try
            {
                voyages.InsertBatch(SampleVoyages.GetAll(), mongoInsertOptions);
            }
            catch (WriteConcernException ex)
            {
            }

            var cargo = db.GetCollection <Cargo>("cargo");

            var routeSpecification = new RouteSpecification(SampleLocations.HONGKONG,
                                                            SampleLocations.HELSINKI,
                                                            DateUtil.ToDate("2009-03-15"));
            var trackingId     = new TrackingId("ABC123");
            var abc123exists   = new CargoRepositoryMongo(db).Find(trackingId) != null;
            var handlingEvents = db.GetCollection <HandlingEvent>("handlingEvents");

            if (!abc123exists)
            {
                var abc123    = new Cargo(trackingId, routeSpecification);
                var itinerary = new Itinerary(
                    new List <Leg>
                {
                    new Leg(SampleVoyages.HONGKONG_TO_NEW_YORK, SampleLocations.HONGKONG,
                            SampleLocations.NEWYORK,
                            DateUtil.ToDate("2009-03-02"), DateUtil.ToDate("2009-03-05")),
                    new Leg(SampleVoyages.NEW_YORK_TO_DALLAS, SampleLocations.NEWYORK, SampleLocations.DALLAS,
                            DateUtil.ToDate("2009-03-06"), DateUtil.ToDate("2009-03-08")),
                    new Leg(SampleVoyages.DALLAS_TO_HELSINKI, SampleLocations.DALLAS, SampleLocations.HELSINKI,
                            DateUtil.ToDate("2009-03-09"), DateUtil.ToDate("2009-03-12"))
                });
                abc123.AssignToRoute(itinerary);

                cargo.Insert(abc123);

                HandlingEvent event1 = handlingEventFactory.CreateHandlingEvent(
                    new DateTime(), DateUtil.ToDate("2009-03-01"), trackingId, null, SampleLocations.HONGKONG.UnLocode,
                    HandlingType.RECEIVE
                    );


                handlingEvents.Insert(event1);

                HandlingEvent event2 = handlingEventFactory.CreateHandlingEvent(
                    new DateTime(), DateUtil.ToDate("2009-03-02"), trackingId,
                    SampleVoyages.HONGKONG_TO_NEW_YORK.voyageNumber, SampleLocations.HONGKONG.UnLocode,
                    HandlingType.LOAD
                    );
                handlingEvents.Insert(event2);

                HandlingEvent event3 = handlingEventFactory.CreateHandlingEvent(
                    new DateTime(), DateUtil.ToDate("2009-03-05"), trackingId,
                    SampleVoyages.HONGKONG_TO_NEW_YORK.voyageNumber, SampleLocations.NEWYORK.UnLocode,
                    HandlingType.UNLOAD
                    );
                handlingEvents.Insert(event3);


                HandlingHistory handlingHistory = handlingEventRepository.LookupHandlingHistoryOfCargo(trackingId);
                abc123.DeriveDeliveryProgress(handlingHistory);
                cargo.Save(abc123);
            }


            var trackingId1  = new TrackingId("JKL567");
            var jkl567exists = new CargoRepositoryMongo(db).Find(trackingId) != null;

            if (!jkl567exists)
            {
                var routeSpecification1 = new RouteSpecification(SampleLocations.HANGZOU,
                                                                 SampleLocations.STOCKHOLM,
                                                                 DateUtil.ToDate("2009-03-18"));
                var jkl567 = new Cargo(trackingId1, routeSpecification1);

                var itinerary1 = new Itinerary(new List <Leg>
                {
                    new Leg(SampleVoyages.HONGKONG_TO_NEW_YORK,
                            SampleLocations.HANGZOU, SampleLocations.NEWYORK,
                            DateUtil.ToDate("2009-03-03"),
                            DateUtil.ToDate("2009-03-05")),
                    new Leg(SampleVoyages.NEW_YORK_TO_DALLAS,
                            SampleLocations.NEWYORK, SampleLocations.DALLAS,
                            DateUtil.ToDate("2009-03-06"),
                            DateUtil.ToDate("2009-03-08")),
                    new Leg(SampleVoyages.DALLAS_TO_HELSINKI,
                            SampleLocations.DALLAS, SampleLocations.STOCKHOLM,
                            DateUtil.ToDate("2009-03-09"),
                            DateUtil.ToDate("2009-03-11"))
                });
                jkl567.AssignToRoute(itinerary1);
                cargo.Insert(jkl567);


                HandlingEvent event21 = handlingEventFactory.CreateHandlingEvent(
                    new DateTime(), DateUtil.ToDate("2009-03-01"), trackingId1, null, SampleLocations.HANGZOU.UnLocode,
                    HandlingType.RECEIVE);

                handlingEvents.Insert(event21);

                HandlingEvent event22 = handlingEventFactory.CreateHandlingEvent(
                    new DateTime(), DateUtil.ToDate("2009-03-03"), trackingId1,
                    SampleVoyages.HONGKONG_TO_NEW_YORK.voyageNumber, SampleLocations.HANGZOU.UnLocode,
                    HandlingType.LOAD
                    );
                handlingEvents.Insert(event22);

                HandlingEvent event23 = handlingEventFactory.CreateHandlingEvent(
                    new DateTime(), DateUtil.ToDate("2009-03-05"), trackingId1,
                    SampleVoyages.HONGKONG_TO_NEW_YORK.voyageNumber, SampleLocations.NEWYORK.UnLocode,
                    HandlingType.UNLOAD
                    );
                handlingEvents.Insert(event23);

                HandlingEvent event24 = handlingEventFactory.CreateHandlingEvent(
                    new DateTime(), DateUtil.ToDate("2009-03-06"), trackingId1,
                    SampleVoyages.HONGKONG_TO_NEW_YORK.voyageNumber, SampleLocations.NEWYORK.UnLocode,
                    HandlingType.LOAD
                    );
                handlingEvents.Insert(event24);


                HandlingHistory handlingHistory1 = handlingEventRepository.LookupHandlingHistoryOfCargo(trackingId1);
                jkl567.DeriveDeliveryProgress(handlingHistory1);

                cargo.Save(jkl567);
            }
        }
Esempio n. 24
0
        public static void Import(string databaseName, string collectionName, string file, string server = null, MongoInsertOptions options = null)
        {
            MongoCollection collection = GetDatabase(server, databaseName).GetCollection(collectionName);

            MongoLog.CurrentMongoLog.LogImport(collection, file);
            //foreach (BsonDocument document in zmongo.BsonReader<BsonDocument>(file))
            //{
            //    collection.zSave(document);
            //}
            zMongo.BsonRead <BsonDocument>(file).zSave(collection, options);
        }
Esempio n. 25
0
        //public static void FindAndRemove(string databaseName, string collectionName, string query, string sort = null, string fields = null, string server = null)
        //{
        //    MongoCollection collection = MongoCommand.GetDatabase(server, databaseName).GetCollection(collectionName);

        //    QueryDocument queryDoc = query.zToQueryDocument();

        //    Trace.Write("FindAndRemove : {0} query ", collection.zGetFullName());
        //    Trace.Write(queryDoc.ToJson());

        //    SortByWrapper sortByWrapper = null;
        //    if (sort != null)
        //    {
        //        sortByWrapper = sort.zToSortByWrapper();
        //        Trace.Write(" sort {0}", sortByWrapper.ToJson());
        //    }

        //    FieldsWrapper fieldsWrapper = null;
        //    if (fields != null)
        //    {
        //        fieldsWrapper = fields.zToFieldsWrapper();
        //        Trace.Write(" fields {0}", fieldsWrapper.ToJson());
        //    }

        //    FindAndModifyResult result;
        //    try
        //    {
        //        result = collection.zFindAndRemove(queryDoc, sortByWrapper, fieldsWrapper);
        //        TraceResult(result);
        //    }
        //    finally
        //    {
        //        Trace.WriteLine();
        //    }
        //    Trace.WriteLine("document");
        //    Trace.WriteLine(result.ModifiedDocument.zToJson());
        //}

        public static void Insert(string databaseName, string collectionName, string document, MongoInsertOptions options = null, string server = null)
        {
            Insert(databaseName, collectionName, document.zDeserializeToBsonDocument(), options, server);
        }
Esempio n. 26
0
        public override IEnumerable <WriteConcernResult> InsertBatch(Type nominalType, IEnumerable documents, MongoInsertOptions options)
        {
            var documentsList = documents.Cast <object>().ToList();

            var sw = new Stopwatch();

            sw.Start();
            var result = base.InsertBatch(nominalType, documentsList, options);

            sw.Stop();

            var commandStringBuilder = new StringBuilder(512);

            commandStringBuilder.AppendFormat("db.{0}.insert(", Name);

            if (documentsList.Count > 1)
            {
                commandStringBuilder.AppendFormat("<{0} documents>", documentsList.Count);
            }
            else
            {
                // handle ensureIndex specially
                if (Name == "system.indexes")
                {
                    commandStringBuilder.AppendFormat("{0}", documentsList.First().ToBsonDocument());
                }
                else
                {
                    commandStringBuilder.Append("<document>");
                }
            }

            commandStringBuilder.Append(")");

            string commandString = commandStringBuilder.ToString();

            ProfilerUtils.AddMongoTiming(commandString, sw.ElapsedMilliseconds, ExecuteType.Create);

            return(result);
        }
Esempio n. 27
0
 public static WriteConcernResult Insert <TDocument>(string databaseName, string collectionName, TDocument document, MongoInsertOptions options = null, string server = null)
 {
     return(GetDatabase(server, databaseName).GetCollection(collectionName).zInsert(document, options));
 }
        private void bgwDataToNoSQL_DoWork(object sender, DoWorkEventArgs doWorkEventArg)
        {
            List <SystemPhoneAreaWrapper> phoneAreaWrappers = SystemPhoneAreaWrapper.FindAll();

            rowCounts = phoneAreaWrappers.Count;

            string title = string.Format("正在从数据库导入手机号段信息,共(" + rowCounts.ToString() + "条).");

            SetTitle(title, rowCounts);

            var client = new MongoClient(Program.NoSQL_DBConnString);

            var server = client.GetServer();

            var database = server.GetDatabase(Program.NoSQL_DbName);

            var collection = database.GetCollection(Program.NoSQL_CollectionName);

            int i = 0;

            foreach (SystemPhoneAreaWrapper phoneAreaWrapper in phoneAreaWrappers)
            {
                i++;

                if (bgwDataToNoSQL.CancellationPending)
                {
                    break;
                }

                bgwDataToNoSQL.ReportProgress(i, rowCounts);

                ////var query = Query<PhoneArea>.EQ(e => e.PhonePrefix, phoneAreaWrapper.PhonePrefix);

                ////if (collection.FindOne(query) != null)
                ////{
                ////    this.Invoke(new Action(delegate()
                ////    {
                ////        this.lblProcessProgress.Text = "号码数据导入中( " + i.ToString() + "/" + rowCounts.ToString() + ")。。。";
                ////    }));

                ////    continue;
                ////}


                var entity = new PhoneArea()
                {
                    PhonePrefix  = phoneAreaWrapper.PhonePrefix,
                    Province     = phoneAreaWrapper.Province,
                    City         = phoneAreaWrapper.City,
                    OperatorType = phoneAreaWrapper.OperatorType,
                };

                MongoInsertOptions mongoInsert = new MongoInsertOptions()
                {
                    WriteConcern = WriteConcern.Unacknowledged
                };

                rowSuccessCounts++;

                this.Invoke(new Action(delegate()
                {
                    this.lblProcessProgress.Text = "号码数据导入中( " + i.ToString() + "/" + rowCounts.ToString() + ")。。。";
                }));

                collection.Save(entity, mongoInsert);
            }
        }
Esempio n. 29
0
        //public void LogFindAndRemove(MongoCollection collection, QueryDocument query, SortByWrapper sort = null, FieldsWrapper fields = null)
        //{
        //    LogQuery("FindAndRemove", collection, sort: sort, fields: fields);
        //}

        public void LogInsert <TDocument>(MongoCollection collection, TDocument document, MongoInsertOptions options)
        {
            if (_writeToFile == null)
            {
                return;
            }
            _writeToFile.Write("{0:yyyy-MM-dd HH:mm:ss.ffffff} ", DateTime.Now);
            _writeToFile.Write("Insert : {0}", collection.zGetFullName());
            _writeToFile.Write(" document ");
            _writeToFile.Write(document.ToJson());
            _writeToFile.Write(" check element names {0} flags {1}", options.CheckElementNames, options.Flags);
        }
Esempio n. 30
0
        // 将积累的内存对象保存到数据库中
        public int Flush(out string strError)
        {
            strError = "";

            if (this.SearchLogCollection == null)
            {
                this._searchLogCache.Clear();
                return(0);
            }

            try
            {
                List <SearchLogItem> whole = new List <SearchLogItem>();

                // 将打算写入数据库的内存对象移出容器,这样可以减少锁定时间
                if (this.m_lock.TryEnterWriteLock(m_nLockTimeout) == false)
                {
                    throw new ApplicationException("锁定尝试中超时");
                }
                try
                {
                    if (this._searchLogCache.Count == 0)
                    {
                        return(0);
                    }

                    whole.AddRange(this._searchLogCache);
                    this._searchLogCache.Clear();
                    // this.RemoveRange(0, nCount);
                }
                finally
                {
                    this.m_lock.ExitWriteLock();
                }

                if (this.m_lock.TryEnterReadLock(m_nLockTimeout) == false)
                {
                    throw new ApplicationException("锁定尝试中超时");
                }
                try
                {
                    MongoCollection <SearchLogItem> db_items = this.SearchLogCollection;
                    MongoInsertOptions options = new MongoInsertOptions()
                    {
                        WriteConcern = WriteConcern.Unacknowledged
                    };
                    foreach (SearchLogItem item in whole)
                    {
                        db_items.Insert(item, options);
                    }
                }
                finally
                {
                    this.m_lock.ExitReadLock();
                }

                // TODO: 是否考虑失败后把元素重新插入回this数组?

                return(1);
            }
            catch (Exception ex)
            {
                strError = "检索日志写入数据库的过程发生错误: " + ex.Message;
                return(-1);
            }
        }