Example #1
0
 public MongoContext(string connectionString)
 {
     this.connectionString = connectionString;
     this.server = MongoServer.Create(this.connectionString);
     string databaseName = GetDatabaseName(this.connectionString);
     this.database = server.GetDatabase(databaseName);
 }
 public void Setup()
 {
     _server = Configuration.TestServer;
     _server.Connect();
     _database = Configuration.TestDatabase;
     _collection = Configuration.TestCollection;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ShardedMongoServerProxy"/> class.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="instances">The instances.</param>
        /// <param name="connectionQueue">The state change queue.</param>
        /// <param name="connectionAttempt">The connection attempt.</param>
        /// <remarks>This constructor is used when the instances have already been instructed to connect.</remarks>
        protected MultipleInstanceMongoServerProxy(MongoServer server, IEnumerable<MongoServerInstance> instances, BlockingQueue<MongoServerInstance> connectionQueue, int connectionAttempt)
        {
            _state = MongoServerState.Connecting;
            _server = server;
            _connectedInstances = new ConnectedInstanceCollection();
            _connectionAttempt = connectionAttempt;

            _outstandingInstanceConnections = connectionQueue.Count;
            ThreadPool.QueueUserWorkItem(_ =>
            {
                while (connectionQueue.Count > 0)
                {
                    var instance = connectionQueue.Dequeue();
                    Interlocked.Decrement(ref _outstandingInstanceConnections);
                }
            });

            // It's important to have our own copy of this list because it might get modified during iteration. 
            _instances = instances.ToList();
            foreach (var instance in instances)
            {
                instance.StateChanged += InstanceStateChanged;
                ProcessInstanceStateChange(instance);
            }
        }
 public void Setup()
 {
     server = MongoServer.Create();
     server.Connect();
     database = server["onlinetests"];
     collection = database["testcollection"];
 }
 public void Setup()
 {
     _server = Configuration.TestServer;
     _primary = Configuration.TestServer.Primary;
     _database = Configuration.TestDatabase;
     _database.Drop();
 }
Example #6
0
 public HugRepository(string connectionString, string databaseName, IUserProfileRepository userProfileRepository)
 {
     _userProfileRepository = userProfileRepository;
     _server = MongoServer.Create(connectionString);
     _database = _server.GetDatabase(databaseName);
     _mongoCollection = _database.GetCollection<PenedatingMongoUser>("users");
 }
 public void TestFixtureSetup()
 {
     _server = Configuration.TestServer;
     _database = Configuration.TestDatabase;
     _collection = Configuration.TestCollection;
     _collection.Drop();
 }
 public void Setup()
 {
     _server = Configuration.TestServer;
     _primary = Configuration.TestServer.Primary;
     _database = Configuration.TestDatabase;
     _collection = Configuration.TestCollection;
 }
 public void Setup()
 {
     server = MongoServer.Create();
     server.Connect();
     server.DropDatabase("onlinetests");
     database = server["onlinetests"];
 }
 public void Setup()
 {
     _server = Configuration.TestServer;
     _server.Connect();
     _database = Configuration.TestDatabase;
     _database.Drop();
 }
Example #11
0
        public static void FillDataForUser(MongoServer mongosvr)
        {
            MongoDatabase mongodb = mongosvr.GetDatabase("mongodb");

            MongoCollection<BsonDocument> mongoJsCol = mongodb.GetCollection<BsonDocument>("system.js");
            mongoJsCol.Insert<BsonDocument>(
                          new BsonDocument().Add("_id", "sum")
                                            .Add("value", "function (x, y) { return x + y; }"));
            MongoGridFS mongofs = mongodb.GetGridFS(new MongoGridFSSettings());
            MongoCollection<User> mongoCol = mongodb.GetCollection<User>("User");
            mongoCol.RemoveAll();
            Random Ro = new Random();
            ///HugeData
            for (int i = 0; i < 1000; i++)
            {
                mongoCol.Insert(new User()
                {
                    ID = i.ToString(),
                    Name = "Tom",
                    Age = (byte)Ro.Next(100),
                    Age2 = (byte)Ro.Next(100),
                    Age3 = (byte)Ro.Next(100),
                    address = new Address()
                    {
                        street = "123 Main St.",
                        City = "Centerville",
                        state = "PA",
                        Zip = Ro.Next(20)
                    }
                });
            }
        }
 public void TestFixtureSetUp()
 {
     _server = MongoServer.Create(ConnStr);
     if (_server.DatabaseExists(PropSetCollectionsDb))
         _server.DropDatabase(PropSetCollectionsDb);
     _testDb = _server.GetDatabase(PropSetCollectionsDb);
 }
 public void Setup()
 {
     server = MongoServer.Create("mongodb://localhost/?safe=true");
     server.Connect();
     database = server["onlinetests"];
     collection = database["testcollection"];
 }
 /// <summary>
 /// 数据库分片
 /// </summary>
 /// <param name="routeSvr"></param>
 /// <param name="shardingDB"></param>
 /// <returns></returns>
 public static CommandResult EnableSharding(MongoServer routeSvr, String shardingDB)
 {
     CommandDocument mongoCmd = new CommandDocument();
     mongoCmd = new CommandDocument();
     mongoCmd.Add("enablesharding", shardingDB);
     return ExecuteMongoCommand(mongoCmd, routeSvr);
 }
        //Replica Set Commands
        //http://www.mongodb.org/display/DOCS/Replica+Set+Commands
        //rs.help()                       show help
        //rs.status()                     { replSetGetStatus : 1 }
        //rs.initiate()                   { replSetInitiate : null } initiate
        //                                    with default settings
        //rs.initiate(cfg)                { replSetInitiate : cfg }
        //rs.add(hostportstr)             add a new member to the set
        //rs.add(membercfgobj)            add a new member to the set
        //rs.addArb(hostportstr)          add a new member which is arbiterOnly:true
        //rs.remove(hostportstr)          remove a member (primary, secondary, or arbiter) from the set
        //rs.stepDown()                   { replSetStepDown : true }
        //rs.conf()                       return configuration from local.system.replset
        //db.isMaster()                   check who is primary
        /// <summary>
        /// 增加服务器
        /// </summary>
        /// <param name="mongoSvr">副本组主服务器</param>
        /// <param name="HostPort">服务器信息</param>
        /// <param name="IsArb">是否为仲裁服务器</param>
        /// <returns></returns>
        public static CommandResult AddToReplsetServer(MongoServer mongoSvr, String HostPort, int priority, Boolean IsArb)
        {
            CommandResult mCommandResult = new CommandResult(new BsonDocument());
            try
            {
                if (!IsArb)
                {
                    mCommandResult = ExecuteJsShell("rs.add({_id:" + mongoSvr.Instances.Length + 1 + ",host:'" + HostPort + "',priority:" + priority.ToString() + "});", mongoSvr);
                }
                else
                {
                    //其实addArb最后也只是调用了add方法
                    mCommandResult = ExecuteJsShell("rs.addArb('" + HostPort + "');", mongoSvr);
                }
            }
            catch (EndOfStreamException)
            {

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return mCommandResult;
        }
Example #16
0
 public MongoUtil()
 {
     connectionString = "mongodb://localhost";
     client  = new MongoClient(connectionString);
     server = client.GetServer();
     database = server.GetDatabase("testwechat");
 }
 public PersonRepository()
 {
     string connectionString = "mongodb://localhost";
     _server = MongoServer.Create(connectionString);
     _peopleDb = _server.GetDatabase("Mono");
     _people = _peopleDb.GetCollection<Person>("Person");
 }
 public void Setup()
 {
     server = MongoServer.Create("mongodb://localhost/?safe=true");
     server.Connect();
     server.DropDatabase("onlinetests");
     database = server["onlinetests"];
 }
 static MongoRepositoryContext() {
     settings = new MongoRepositorySettings();
     var url = new MongoUrl(ConfigurationManager.ConnectionStrings["SysDB"].ConnectionString);
     client = new MongoClient(url);
     server = client.GetServer();
     database = server.GetDatabase(url.DatabaseName);
 }
 public void Setup()
 {
     _server = Configuration.TestServer;
     _primary = _server.Instances.First(x => ReadPreference.Primary.MatchesInstance(x));
     _database = Configuration.TestDatabase;
     _collection = Configuration.TestCollection;
 }
 public static void EstablishConnection()
 {
     client = new MongoClient(connectionString);
     server = client.GetServer();
     database = server.GetDatabase(DbName);
     entries = database.GetCollection<JSonReport>(collectionName);
 }
        public ExtendedMongoDBCheck(string connectionString, bool isReplSet, bool dbStats)
        {
            _isReplSet = isReplSet;
            _dbStats = dbStats;

            if (connectionString.Contains("mongodb://"))
            {
                _mongoServer = MongoServer.Create(string.Format("{0}{1}?slaveok=true", connectionString, connectionString.EndsWith("/") ? "" : "/"));
            }
            else
            {
                MongoServerSettings settings = new MongoServerSettings();
                if (connectionString.Contains(":"))
                {
                    string[] bits = connectionString.Split(':');
                    settings.Server = new MongoServerAddress(bits[0], Convert.ToInt32(bits[1]));
                }
                else
                {
                    settings.Server = new MongoServerAddress(connectionString);
                }
                settings.SlaveOk = true;
                _mongoServer = MongoServer.Create(settings);
            }
        }
Example #23
0
 public MdbAccount()
 {
     m_Client = new MongoClient(Configuration.Database.Url);
     m_Server = m_Client.GetServer();
     m_Database = m_Server.GetDatabase(Configuration.Database.Name);
     m_Collection = m_Database.GetCollection<Account>(MDBAccountTable);
 }
Example #24
0
 public Server(string connectionString, string databaseName)
 {
     this.m_ConnectionString = connectionString;
     this.m_MongoClient = new MongoClient(this.m_ConnectionString);
     this.m_MongoServer = this.m_MongoClient.GetServer();
     this.m_MongoDatabase = this.m_MongoServer.GetDatabase(databaseName);
 }
 public void TestFixtureSetup()
 {
     server = MongoServer.Create("mongodb://localhost/?safe=true");
     database = server["onlinetests"];
     collection = database["testcollection"];
     collection.Drop();
 }
 private void MongoSetup()
 {
     var connectionString = "mongodb://localhost";
     client = new MongoClient(connectionString);
     server = client.GetServer();
     database = server.GetDatabase("Byob");
 }
Example #27
0
		public MongoImpl(MongoServer connection, WriteConcern writeConcern)
		{
			this.writeConcern = writeConcern;
			Helpers.Random.Value.NextBytes(initialValue);
			collection =
				connection.GetDatabase(typeof (SomeDocument).Name).GetCollection<SomeDocument>(typeof (SomeDocument).Name);
		}
 public void Setup()
 {
     _server = LegacyTestConfiguration.Server;
     _primary = _server.Instances.First(x => x.IsPrimary);
     _database = LegacyTestConfiguration.Database;
     _collection = LegacyTestConfiguration.Collection;
 }
 public void Setup()
 {
     _server = MongoServer.Create("mongodb://localhost/?safe=true");
     _server.Connect();
     _database = _server["onlinetests"];
     _collection = _database["linqtests"];
 }
 internal DirectConnector(
     MongoServer server,
     int connectionAttempt
 ) {
     this.server = server;
     this.connectionAttempt = connectionAttempt;
 }
 public GenericRepository()
 {
     _client = new MongoClient("mongodb://localhost:27017");
     _server = _client.GetServer();
     _db     = _server.GetDatabase("eBilling");
 }
Example #32
0
 public void TestFixtureSetup()
 {
     _server   = Configuration.TestServer;
     _database = Configuration.TestDatabase;
     _primary  = _server.Primary;
 }
Example #33
0
 public void TestFixtureSetup()
 {
     _server   = Configuration.TestServer;
     _database = Configuration.TestDatabase;
 }
Example #34
0
 public void TestFixtureSetup()
 {
     _server     = Configuration.TestServer;
     _database   = Configuration.TestDatabase;
     _collection = Configuration.GetTestCollection <C>();
 }
Example #35
0
 public CollectionStatsResultTests()
 {
     _server     = LegacyTestConfiguration.Server;
     _collection = LegacyTestConfiguration.Collection;
 }
Example #36
0
        public Volunteers()
        {
            var server = MongoServer.Create();

            db = server.GetDatabase("volunteers");
        }
 public QueryBuilderTests()
 {
     _server   = LegacyTestConfiguration.Server;
     _database = LegacyTestConfiguration.Database;
     _primary  = _server.Primary;
 }
 public SystemProfileInfoTests()
 {
     _server     = LegacyTestConfiguration.Server;
     _database   = LegacyTestConfiguration.Database;
     _collection = LegacyTestConfiguration.Collection;
 }
 public void TestFixtureSetup()
 {
     server     = MongoServer.Create("mongodb://localhost/?safe=true");
     database   = server["onlinetests"];
     collection = database["csharp112"];
 }
Example #40
0
 public void TestFixtureSetup()
 {
     _server   = LegacyTestConfiguration.Server;
     _database = LegacyTestConfiguration.Database;
     _primary  = _server.Primary;
 }
Example #41
0
 public void Setup()
 {
     _server     = Configuration.TestServer;
     _database   = Configuration.TestDatabase;
     _collection = Configuration.TestCollection;
 }
Example #42
0
 public void SetupTest()
 {
     this.server = MongoServer.Create(ConnectionString);
 }
 public DatabaseStatsResultTests()
 {
     _server     = LegacyTestConfiguration.Server;
     _database   = LegacyTestConfiguration.Database;
     _collection = LegacyTestConfiguration.Collection;
 }
 public void TestFixtureSetUp()
 {
     _client   = new MongoClient();
     _server   = _client.GetServer();
     _database = _server.GetDatabase("database");
 }
Example #45
0
 public void TestFixtureSetUp()
 {
     _server   = MongoServer.Create();
     _database = _server["test"];
     _gridFS   = _database.GridFS;
 }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var connectionString = "mongodb://localhost/?safe=true";
            var server           = MongoServer.Create(connectionString);
            var database         = server.GetDatabase("agencija");

            var collectionKomentari = database.GetCollection <Komentar>("komentari");

            groupBox1.Controls.Clear();
            groupBox2.Controls.Clear();
            int i = 0;

            foreach (Komentar k in collectionKomentari.FindAll())
            {
                //treba da se sredi da se tu negde uglavi i pictureBox sa slikom koju korisnik uploaduje nisam stigla to
                if (i < 4 && comboBox1.SelectedItem.Equals(k.Ocena.ToString()) && k.Putovanje.Id.Equals(ObjectId.Parse(idLetovanja)))
                {
                    labels[i]          = new Label();
                    labels[i].Text     = k.Ocena + ", " + k.Tekst;
                    labels[i].Location = new Point(labels[i].Location.X, labels[i].Location.Y + i * 80);
                    groupBox1.Controls.Add(labels[i]);


                    if (k.Slika != null)
                    {
                        PictureBox pb = new PictureBox();
                        pb.SizeMode = PictureBoxSizeMode.StretchImage;

                        byte[]       buffer    = k.Slika.ToArray();
                        MemoryStream memStream = new MemoryStream();
                        memStream.Write(buffer, 0, buffer.Length);
                        pb.SizeMode = PictureBoxSizeMode.StretchImage;
                        pb.Location = new Point(pb.Location.X, pb.Location.Y + i * 80);
                        pb.Size     = new Size(groupBox1.Width, groupBox1.Height / 4);
                        pb.Image    = Image.FromStream(memStream);
                        groupBox1.Controls.Add(pb);
                    }

                    i++;
                }

                else if (i < 8 && i >= 4 && comboBox1.SelectedItem.Equals(k.Ocena.ToString()) && k.Putovanje.Id.Equals(ObjectId.Parse(idLetovanja)))
                {
                    labels[i]          = new Label();
                    labels[i].Text     = k.Ocena + ", " + k.Tekst;
                    labels[i].Location = new Point(labels[i].Location.X, labels[i].Location.Y + (i - 4) * 80);
                    groupBox2.Controls.Add(labels[i]);

                    if (k.Slika != null)
                    {
                        PictureBox pb = new PictureBox();
                        pb.SizeMode = PictureBoxSizeMode.StretchImage;
                        byte[]       buffer    = k.Slika.ToArray();
                        MemoryStream memStream = new MemoryStream();
                        memStream.Write(buffer, 0, buffer.Length);
                        pb.SizeMode = PictureBoxSizeMode.StretchImage;
                        pb.Location = new Point(pb.Location.X, pb.Location.Y + (i - 4) * 80);
                        pb.Size     = new Size(groupBox1.Width, groupBox1.Height / 4);
                        pb.Image    = Image.FromStream(memStream);
                        groupBox2.Controls.Add(pb);
                    }

                    i++;
                }
            }
        }
Example #47
0
 public BooksRepository()
 {
     _client = new MongoClient("mongodb://localhost:27017");
     _server = _client.GetServer();
     _db     = _server.GetDatabase("LibraryDB");
 }
Example #48
0
 public MongoQueryProviderTests()
 {
     _server = LegacyTestConfiguration.Server;
     _server.Connect();
     _collection = LegacyTestConfiguration.Collection;
 }
Example #49
0
 public NoteService()
 {
     _client = new MongoClient("mongodb://localhost:27017");
     _server = _client.GetServer();
     _db     = _server.GetDatabase("NotesDb");
 }
Example #50
0
        static void Main()
        {
            // Create seed data

            BsonDocument[] seedData = CreateSeedData();

            // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname

            String uri = "mongodb://*****:*****@host:port/db";

            MongoUrl      url    = new MongoUrl(uri);
            MongoClient   client = new MongoClient(url);
            MongoServer   server = client.GetServer();
            MongoDatabase db     = server.GetDatabase(url.DatabaseName);

            /*
             * First we'll add a few songs. Nothing is required to create the
             * songs collection; it is created automatically when we insert.
             */

            var songs = db.GetCollection <BsonDocument>("songs");

            // Use Insert for single BsonDocument insertion.

            songs.InsertBatch(seedData);

            /*
             * Then we need to give Boyz II Men credit for their contribution to
             * the hit "One Sweet Day".
             */

            QueryDocument updateQuery = new QueryDocument {
                { "Title", "One Sweet Day" }
            };

            songs.Update(updateQuery, new UpdateDocument {
                { "$set", new BsonDocument("Artist", "Mariah Carey ft. Boyz II Men") }
            });

            /*
             * Finally we run a query which returns all the hits that spent 10
             * or more weeks at number 1.
             */

            QueryDocument findQuery = new QueryDocument {
                { "WeeksAtOne", new BsonDocument {
                      { "$gte", 10 }
                  } }
            };
            var cursor = songs.Find(findQuery).SetSortOrder(SortBy.Ascending("Decade"));

            foreach (var song in cursor)
            {
                var test = song["Decade"];
                Console.WriteLine("In the {0}, {1} by {2} topped the charts for {3} straight weeks",
                                  song["Decade"], song["Title"], song["Artist"], song["WeeksAtOne"]);
            }

            // Since this is an example, we'll clean up after ourselves.

            songs.Drop();

            // Only disconnect when your app is terminating.

            server.Disconnect();
        }
Example #51
0
 public static void MyClassInitialize(TestContext testContext)
 {
     mongodb = MongoServer.Create("mongodb://localhost:10319/safe=true");
 }
        private NotificationsService()
        {
            var server = MongoServer.Create("mongodb://127.0.0.1");

            Database = server.GetDatabase("ciudadconectada");
        }
Example #53
0
        /// <summary>
        ///     执行MongoCommand
        /// </summary>
        /// <param name="mCommandDocument">命令Doc</param>
        /// <param name="mongoSvr">目标服务器</param>
        /// <returns></returns>
        public static CommandResult ExecuteMongoSvrCommand(CommandDocument mCommandDocument, MongoServer mongoSvr)
        {
            CommandResult mCommandResult;

            try
            {
                mCommandResult = mongoSvr.GetDatabase(ConstMgr.DatabaseNameAdmin).RunCommand(mCommandDocument);
            }
            catch (MongoCommandException ex)
            {
                mCommandResult = new CommandResult(ex.Result);
            }
            var e = new RunCommandEventArgs
            {
                CommandString = mCommandDocument.ToString(),
                RunLevel      = EnumMgr.PathLevel.Instance,
                Result        = mCommandResult
            };

            OnCommandRunComplete(e);
            return(mCommandResult);
        }
 public MongoEntiryStoreConnection(string connectionString)
 {
     this.server   = MongoServer.Create(connectionString);
     this.database = server.GetDatabase("EntityTagStore");
 }
 public static MongoServer ConnectServer()
 {
     _client = new MongoClient("mongodb://localhost:27017"); //can make it configurable via .config file
     _server = _client.GetServer();
     return(_server);
 }
Example #56
0
        /// <summary>
        ///     在指定服务器上执行指定命令
        /// </summary>
        /// <param name="mMongoCommand"></param>
        /// <param name="mongosrv"></param>
        /// <returns></returns>
        public static CommandResult ExecuteMongoSvrCommand(MongoCommand mMongoCommand, MongoServer mongosrv)
        {
            var command = new CommandDocument {
                { mMongoCommand.CommandString, 1 }
            };

            if (mMongoCommand.RunLevel == EnumMgr.PathLevel.Database)
            {
                throw new Exception();
            }
            return(ExecuteMongoSvrCommand(command, mongosrv));
        }
Example #57
0
 public void TestFixtureSetUp()
 {
     _server   = LegacyTestConfiguration.Server;
     _database = LegacyTestConfiguration.Database;
 }
Example #58
0
 public override void Initialize(string name, NameValueCollection config)
 {
     this.mongoCollection = MongoServer.Create(config["connectionString"] ?? "mongodb://localhost").GetDatabase(config["database"] ?? "ASPNETDB").GetCollection(config["collection"] ?? "OutputCache");
     this.mongoCollection.EnsureIndex("Key");
     base.Initialize(name, config);
 }
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public static void ImportAccessDataBase(Object obj)
        {
            ImportAccessPara parm     = (ImportAccessPara)obj;
            MongoServer      mongoSvr = GetMongoServerBySvrPath(parm.strSvrPathWithTag);

            String[]        fileName     = parm.accessFileName.Split(@"\".ToCharArray());
            String          fileMain     = fileName[fileName.Length - 1];
            String          insertDBName = fileMain.Split(".".ToCharArray())[0];
            MongoDatabase   mongoDB      = mongoSvr.GetDatabase(insertDBName);
            OleDbConnection conn         = new OleDbConnection(ACCESS_CONNECTION_STRING.Replace("@AccessPath", parm.accessFileName));

            try
            {
                conn.Open();
                int       err                = 0;
                DataTable tblTableList       = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
                String    strCreateTableInfo = String.Empty;
                foreach (DataRow recTable in tblTableList.Rows)
                {
                    String strTableName = recTable[2].ToString();
                    try
                    {
                        //不支持UTF....,执行会失败,但是Collection已经添加了
                        String ErrMsg;
                        mongoDB.IsCollectionNameValid(strTableName, out ErrMsg);
                        if (ErrMsg != null)
                        {
                            strCreateTableInfo = strTableName + " Create Error " + System.Environment.NewLine + strCreateTableInfo;
                            OnActionDone(new ActionDoneEventArgs(strTableName + " IsCollectionNameValid Error "));
                            err++;
                            continue;
                        }
                        mongoDB.CreateCollection(strTableName);
                        strCreateTableInfo = strTableName + " Creating " + System.Environment.NewLine + strCreateTableInfo;
                        OnActionDone(new ActionDoneEventArgs(strTableName + " Creating "));
                    }
                    catch (Exception)
                    {
                        if (mongoDB.CollectionExists(strTableName))
                        {
                            mongoDB.DropCollection(strTableName);
                        }
                        strCreateTableInfo = strTableName + " Create Error " + System.Environment.NewLine + strCreateTableInfo;
                        OnActionDone(new ActionDoneEventArgs(strTableName + " Creating Error "));
                        err++;
                        continue;
                    }
                    MongoCollection             mongoCollection = mongoDB.GetCollection(strTableName);
                    DataTable                   tblSchema       = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, strTableName, null });
                    Dictionary <String, String> colPro          = new Dictionary <String, String>();
                    List <String>               colName         = new List <String>();
                    foreach (DataRow item in tblSchema.Rows)
                    {
                        long columnWidth;
                        switch ((long)item["COLUMN_FLAGS"])
                        {
                        case 122:
                            columnWidth = -1;
                            break;

                        case 90:
                            //AutoNumber
                            columnWidth = -2;
                            break;

                        default:
                            if (item["CHARACTER_MAXIMUM_LENGTH"] is DBNull)
                            {
                                columnWidth = -3;
                            }
                            else
                            {
                                columnWidth = (long)item["CHARACTER_MAXIMUM_LENGTH"];
                            }
                            break;
                        }
                        colName.Add(item["COLUMN_NAME"].ToString());
                        colPro.Add(item["COLUMN_NAME"].ToString(), GetDataType((int)item["DATA_TYPE"], columnWidth,
                                                                               item["NUMERIC_PRECISION"] is DBNull ? 0 : (int)item["NUMERIC_PRECISION"],
                                                                               item["NUMERIC_SCALE"] is DBNull ? 0 : (int)item["NUMERIC_SCALE"]));
                    }
                    OleDbCommand cmd = new OleDbCommand();
                    cmd.Connection  = conn;
                    cmd.CommandText = "Select * from " + strTableName;
                    OleDbDataAdapter adapter = new OleDbDataAdapter();
                    DataSet          dateSet = new DataSet();
                    adapter.SelectCommand = cmd;
                    adapter.Fill(dateSet, strTableName);
                    DataTable tblAccessData = dateSet.Tables[0];
                    foreach (DataRow itemRow in tblAccessData.Rows)
                    {
                        BsonDocument insertDoc = new BsonDocument();
                        for (int i = 0; i < colName.Count; i++)
                        {
                            if (!(itemRow[colName[i]] is DBNull))
                            {
                                switch (colPro[colName[i]])
                                {
                                case "VARCHAR":
                                    insertDoc.Add(colName[i], new BsonString(itemRow[colName[i]].ToString()), true);
                                    break;

                                case "BIT":
                                    //System.Boolean Can't Cast To BSonBoolean....
                                    //O,My LadyGaga
                                    if ((bool)itemRow[colName[i]])
                                    {
                                        insertDoc.Add(colName[i], BsonBoolean.True, true);
                                    }
                                    else
                                    {
                                        insertDoc.Add(colName[i], BsonBoolean.False, true);
                                    }
                                    break;

                                case "DATETIME":
                                    //O,My LadyGaga
                                    insertDoc.Add(colName[i], new BsonDateTime((DateTime)itemRow[colName[i]]), true);
                                    break;

                                case "Integer":
                                    Int32 i32 = Convert.ToInt32(itemRow[colName[i]]);
                                    insertDoc.Add(colName[i], (BsonInt32)i32, true);
                                    break;

                                case "Long":
                                    //itemRow[ColName[i]] the default is Int32 without convert
                                    long lng = Convert.ToInt64(itemRow[colName[i]]);
                                    insertDoc.Add(colName[i], (BsonInt64)lng, true);
                                    break;

                                default:
                                    break;
                                }
                            }
                        }
                        mongoCollection.Insert <BsonDocument>(insertDoc);
                    }
                }
                String strSvrPath = SystemManager.GetTagData(parm.strSvrPathWithTag);
                String strKey     = strSvrPath.Split("/".ToCharArray())[(int)MongoDBHelper.PathLv.ConnectionLV] + "/" +
                                    strSvrPath.Split("/".ToCharArray())[(int)MongoDBHelper.PathLv.InstanceLV];
                parm.currentTreeNode.Nodes.Add(FillDataBaseInfoToTreeNode(insertDBName, mongoSvr, strKey));
                MyMessageBox.ShowMessage("Import Message", (tblTableList.Rows.Count - err).ToString() + "Created   " + err + "failed", strCreateTableInfo, true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
Example #60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TypedDataSource" /> class.
 /// </summary>
 /// <param name="server">The server.</param>
 /// <param name="dataContext">The data context.</param>
 public TypedDataSource(MongoServer server, object dataContext)
 {
     Server      = server;
     DataContext = dataContext;
 }