private static void Log(MongoDatabase database)
        {
            var createOptions = CollectionOptions
                                .SetCapped(true)
                                .SetMaxSize(5000)
                                .SetMaxDocuments(10000);

            createOptions.SetCapped(true);
            createOptions.SetMaxDocuments(5000);
            createOptions.SetMaxSize(10000);


            if (!database.CollectionExists("site.log"))
            {
                database.CreateCollection("site.log", createOptions);
            }

            var logCollection = database.GetCollection("site.log");
            var logIndexes    = logCollection.GetIndexes();

            if (logIndexes.All(c => c.Name != "CreateDate"))
            {
                var keys    = IndexKeys.Ascending("CreateDate");
                var options = IndexOptions.SetName("CreateDate");
                logCollection.CreateIndex(keys, options);
            }
        }
Exemple #2
0
        public static void MongoFsConnect()
        {
            var strconn = "mongodb://" + MongoXml.GetMongoIp() + ":" + MongoXml.GetMongoPort();
            var server = MongoServer.Create(strconn);

            _db = server[MongoXml.GetConfig()[2]];
        }
Exemple #3
0
        } // End Sub CreateIndex

        // Following example show how to save file and read back from gridfs(using official mongodb driver):
        // http://www.mongovue.com/
        public void Test()
        {
            MongoDB.Driver.MongoServer   server   = MongoServer.Create("mongodb://localhost:27020");
            MongoDB.Driver.MongoDatabase database = server.GetDatabase("tesdb");

            string fileName    = "D:\\Untitled.png";
            string newFileName = "D:\\new_Untitled.png";

            using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open))
            {
                MongoDB.Driver.GridFS.MongoGridFSFileInfo gridFsInfo = database.GridFS.Upload(fs, fileName);
                BsonValue fileId = gridFsInfo.Id;

                ObjectId oid = new ObjectId(fileId.AsByteArray);
                MongoDB.Driver.GridFS.MongoGridFSFileInfo file = database.GridFS.FindOne(Query.EQ("_id", oid));

                using (System.IO.Stream stream = file.OpenRead())
                {
                    byte[] bytes = new byte[stream.Length];
                    stream.Read(bytes, 0, (int)stream.Length);
                    using (System.IO.FileStream newFs = new System.IO.FileStream(newFileName, System.IO.FileMode.Create))
                    {
                        newFs.Write(bytes, 0, bytes.Length);
                    } // End Using newFs
                }     // End Using stream
            }         // End using fs
        }             // End Sub Test
Exemple #4
0
        } // End Sub Test2

        // http://stackoverflow.com/questions/7201847/how-to-get-the-mongo-database-specified-in-connection-string-in-c-sharp
        public void Test3()
        {
            string      connectionString = "mongodb://localhost:27020/mydb";
            MongoServer _server          = new MongoClient(connectionString).GetServer();

            // var _serverOld = MongoServer.Create(connectionString);

            //take database name from connection string
            string _databaseName = MongoUrl.Create(connectionString).DatabaseName;


            //and then get database by database name:
            MongoDB.Driver.MongoDatabase thedb = _server.GetDatabase(_databaseName);


            // Connectionstring:
            MongoDB.Driver.MongoUrl csb = MongoUrl.Create(connectionString);
            string omdb = csb.DatabaseName;

            // E.g.
            MongoClient   client = new MongoClient(connectionString);
            MongoDatabase db     = client.GetServer().GetDatabase(new MongoUrl(connectionString).DatabaseName);
            MongoCollection <MongoDB.Bson.BsonDocument> collection = db.GetCollection("mycollection");

            // var spec = new Document("Name", new MongoRegex(string.Format("^{0}",searchKey), "i"));
            // collection.Find(spec);
        } // End Sub Test3
Exemple #5
0
        private void button2_Click(object sender, EventArgs e)
        {
            string userSql = string.Format("Select u.UserID, u.FirstName, u.LastName, u.DisplayName From [User] u " +
                                           "inner join usercontract uc on u.userid = uc.userid " +
                                           "inner join contract c on uc.contractid = c.contractid " +
                                           "where c.number = '{0}'", txtContract.Text);

            string sqlConn = txtSQLNGConn.Text;

            DataSet users = Phytel.Services.SQLDataService.Instance.ExecuteSQLDirect(sqlConn, userSql, 0);

            foreach (DataRow dr in users.Tables[0].Rows)
            {
                string mongoConnString = txtMongoConn.Text;

                MongoDB.Driver.MongoDatabase mongoDB = Phytel.Services.MongoService.Instance.GetDatabase(mongoConnString);

                IMongoQuery query = Query.EQ(MEContact.ResourceIdProperty, dr["UserID"].ToString());

                MEContact existsC = mongoDB.GetCollection("Contact").FindOneAs <MEContact>(query);

                if (existsC != null)
                {
                    continue;
                }

                List <Phytel.API.DataDomain.Contact.DTO.CommMode> modes = new List <Phytel.API.DataDomain.Contact.DTO.CommMode>();

                modes.Add(new Phytel.API.DataDomain.Contact.DTO.CommMode {
                    ModeId = ObjectId.Parse("52e17cc2d433232028e9e38f"), OptOut = false, Preferred = false
                });
                modes.Add(new Phytel.API.DataDomain.Contact.DTO.CommMode {
                    ModeId = ObjectId.Parse("52e17ce6d433232028e9e390"), OptOut = false, Preferred = false
                });
                modes.Add(new Phytel.API.DataDomain.Contact.DTO.CommMode {
                    ModeId = ObjectId.Parse("52e17d08d433232028e9e391"), OptOut = false, Preferred = false
                });
                modes.Add(new Phytel.API.DataDomain.Contact.DTO.CommMode {
                    ModeId = ObjectId.Parse("52e17d10d433232028e9e392"), OptOut = false, Preferred = false
                });

                MEContact newC = new MEContact("5368ff2ad4332316288f3e3e", null)
                {
                    FirstName        = dr["FirstName"].ToString(),
                    LoweredFirstName = dr["FirstName"].ToString().ToLower(),
                    LastName         = dr["LastName"].ToString(),
                    LoweredLastName  = dr["LastName"].ToString().ToLower(),
                    PreferredName    = dr["DisplayName"].ToString(),
                    ResourceId       = dr["UserID"].ToString(),
                    Modes            = modes,
                    Status           = Status.Active,
                    DataSource       = "Engage",
                    Gender           = "N",
                    Deceased         = Deceased.No,
                    ContactTypeId    = ObjectId.Parse("56f1a1ad078e10eb86038519"),
                    Version          = 1.0
                };
                mongoDB.GetCollection("Contact").Insert(newC);
            }
        }
Exemple #6
0
        public static void MongoFsConnect()
        {
            var strconn = "mongodb://" + MongoXml.GetMongoIp() + ":" + MongoXml.GetMongoPort();
            var server  = MongoServer.Create(strconn);

            _db = server[MongoXml.GetConfig()[2]];
        }
 static Database()
 {
     mongodb = MongoDB.Driver.MongoServer.Create(
         string.Format("mongodb://127.0.0.1:{0}/?safe=true;connectTimeoutMS=10000",
                       StationRegistry.GetValue("dbPort", 10319)));                                           // TODO: Remove Hard code
     wammer = mongodb.GetDatabase("wammer");
 }
Exemple #8
0
 private MongoDB.Driver.MongoCollection getMongoCollection(string collection)
 {
     MongoDB.Driver.MongoDatabase mongoDataBase = getMongoServer();
     if (!mongoDataBase.CollectionExists(collection))
     {
         mongoDataBase.CreateCollection(collection);
     }
     MongoDB.Driver.MongoCollection mongoCollection = mongoDataBase.GetCollection(collection);//选择集合,相当于表
     return(mongoCollection);
 }
Exemple #9
0
        private MongoDB.Driver.MongoDatabase getMongoServer()
        {
            //string collection = "CommLog";
            MongoServerSettings msSettings  = new MongoServerSettings();
            MongoClient         mongoClient = new MongoClient(conn);
            MongoServer         mongodb     = mongoClient.GetServer();                  // MongoServer.Create(conn);//连接数据库new MongoServer(msSettings); //

            MongoDB.Driver.MongoDatabase mongoDataBase = mongodb.GetDatabase(database); //选择数据库名
            mongodb.Connect();
            return(mongoDataBase);
        }
        private static void FsFiles(MongoDatabase database)
        {
            var usersCollection = database.GetCollection("fs.files");
            var userIndexes     = usersCollection.GetIndexes();

            if (userIndexes.All(c => c.Name != "SiteId"))
            {
                var keys    = IndexKeys.Ascending("metadata.id", "metadata.type");
                var options = IndexOptions.SetName("SiteId");
                usersCollection.CreateIndex(keys, options);
            }
        }
        private static void Users(MongoDatabase database)
        {
            var usersCollection = database.GetCollection("site.user");
            var userIndexes     = usersCollection.GetIndexes();

            if (userIndexes.All(c => c.Name != "UserLogins"))
            {
                var keys    = IndexKeys.Ascending("Logins.LoginProvider", "Logins.ProviderKey");
                var options = IndexOptions.SetName("Logins");
                usersCollection.CreateIndex(keys, options);
            }
        }
        /// <summary>
        ///     Gets a collection with the given <paramref name="name" /> and converts them to objects of type
        ///     <typeparamref name="T" />
        /// </summary>
        /// <typeparam name="T">Type to serialize the documents to from the mongo collection</typeparam>
        /// <param name="name">The name of the mongo collection.</param>
        /// <returns>A <see cref="MongoCollection{TDefaultDocument}" /> of type <typeparamref name="T" /></returns>
        public MongoCollection <T> GetCollection <T>(string name)
        {
            string databaseName = MongoUrl.Create(_connectionString).DatabaseName;
            var    client       = new MongoClient(_connectionString);

            // "GetServer(MongoClient) is obsolete: 'Use the new API instead.'"
            // The new API appears to be stricly asynchronous,
            // which is not supported by upstream dependencies
#pragma warning disable 618
            MongoServer server = client.GetServer();
#pragma warning restore 618

            MongoDB.Driver.MongoDatabase database = server.GetDatabase(databaseName);
            return(database.GetCollection <T>(name));
        }
    public void Init()
    {
        client = new MongoClient(MONGO_URI);
        server = client.GetServer();
        mdb    = server.GetDatabase(DB_NAME);

        //init collections(tables) here
        accountCollection = mdb.GetCollection <DB_Account>(COLLECTIONS.ACCOUNTS);
        playerCollection  = mdb.GetCollection <DB_Player>(COLLECTIONS.PLAYERS);
        workerCollection  = mdb.GetCollection <DB_Worker>(COLLECTIONS.WORKERS);
        shipCollection    = mdb.GetCollection <DB_Ship>(COLLECTIONS.SHIPS);

        Debug.Log("Initialized " + DB_NAME);

        //TODO remove this
        //setting ship0 to NONE, so player can request sail
        DB_Ship ship = FetchShipByName("ship0");

        ship.activity = SHIP_ACTIVITY.NONE;
        updateShip(ship);
        ship                   = FetchShipByName("ship1");
        ship.activity          = SHIP_ACTIVITY.NONE;
        updateShip(ship); ship = FetchShipByName("ship2");
        ship.activity          = SHIP_ACTIVITY.NONE;
        updateShip(ship);

        /*
         * for (int i = 0; i < 50; i++)
         * {
         *  DB_Ship ship2 = new DB_Ship();
         *  ship2.shipName = "ship" + i;
         *  ship2.sector = SECTOR_CODE.REDSECTOR;
         *  ship2.velX = 0;
         *  ship2.velY = 0;
         *  ship2.posX = i + 5;
         *  ship2.posY = 5;
         *  ship2.frame = 0;
         *  ship2.color1 = 1;
         *  ship2.color2 = 2;
         *  ship2.color3 = 3;
         *  ship2.activity = SHIP_ACTIVITY.NONE;
         *  ship2.workersOnBoard = new List<MongoDBRef>();
         *  shipCollection.Insert(ship2);
         * } */
    }
Exemple #14
0
        protected void btnGetConnlections_Click(object sender, EventArgs e)
        {
            BsonDocument docFind = new BsonDocument();

            MongoDB.Driver.MongoServer server = MongoDB.Driver.MongoServer.Create(ConfigurationManager.AppSettings["mongoDBConfig"]);
            server.Connect();
            //获取指定数据库
            MongoDB.Driver.MongoDatabase db = server.GetDatabase(ConfigurationManager.AppSettings["mongoDBName"].ToString());
            string collection = txtCollection.Text.Trim();

            //获取表
            MongoDB.Driver.MongoCollection <BsonDocument> col = db.GetCollection <BsonDocument>(collection);
            lblCollections.Text = "表大小:" + col.GetTotalDataSize() / (1024 * 1024) + "M";//db['119004logs'].totalIndexSize()+db['119004logs'].dataSize()
            this.listBoxCollections.DataSource = col.Database.GetCollectionNames();
            listBoxCollections.DataBind();

            lblDataBaseCount.Text = "数据库大小为:" + db.GetStats().StorageSize / (1024 * 1024) + "M";
        }
        private static void Seo(MongoDatabase database)
        {
            var seoCollection = database.GetCollection("site.seo");
            var seoIndexes    = seoCollection.GetIndexes();

            if (seoIndexes.All(c => c.Name != "Url"))
            {
                var keys    = IndexKeys.Ascending("Url");
                var options = IndexOptions.SetName("Url");
                seoCollection.CreateIndex(keys, options);
            }

            if (seoIndexes.All(c => c.Name != "SiteId"))
            {
                var keys    = IndexKeys.Ascending("SiteId");
                var options = IndexOptions.SetName("SiteId");
                seoCollection.CreateIndex(keys, options);
            }
        }
        private static void Items(MongoDatabase database)
        {
            var itemsCollection = database.GetCollection("site.item");
            var itemIndexes     = itemsCollection.GetIndexes();

            if (itemIndexes.All(c => c.Name != "SiteId"))
            {
                var keys    = IndexKeys.Ascending("SiteId");
                var options = IndexOptions.SetName("SiteId");
                itemsCollection.CreateIndex(keys, options);
            }

            if (itemIndexes.All(c => c.Name != "ParentId"))
            {
                var keys    = IndexKeys.Ascending("SiteId", "ParentId");
                var options = IndexOptions.SetName("ParentId");
                itemsCollection.CreateIndex(keys, options);
            }
        }
        private static void Stats(MongoDatabase database)
        {
            var statsCollection = database.GetCollection("site.stats");
            var statIndexes     = statsCollection.GetIndexes();

            if (statIndexes.All(c => c.Name != "SiteId"))
            {
                var keys    = IndexKeys.Ascending("SiteId");
                var options = IndexOptions.SetName("SiteId");
                statsCollection.CreateIndex(keys, options);
            }

            if (statIndexes.All(c => c.Name != "CreateDate"))
            {
                var keys    = IndexKeys.Ascending("CreateDate");
                var options = IndexOptions.SetName("CreateDate");
                statsCollection.CreateIndex(keys, options);
            }
        }
        private static void Cache(MongoDatabase database)
        {
            var cacheCollection = database.GetCollection("site.cache");
            var cacheIndexes    = cacheCollection.GetIndexes();

            if (cacheIndexes.All(c => c.Name != "SiteId"))
            {
                var keys    = IndexKeys.Ascending("SiteId");
                var options = IndexOptions.SetName("SiteId");
                cacheCollection.CreateIndex(keys, options);
            }

            if (cacheIndexes.All(c => c.Name != "ParentId"))
            {
                var keys    = IndexKeys.Ascending("Key", "Type");
                var options = IndexOptions.SetName("KeyType");
                cacheCollection.CreateIndex(keys, options);
            }
        }
Exemple #19
0
        protected void btnGetIndex_Click(object sender, EventArgs e)
        {
            BsonDocument docFind = new BsonDocument();

            MongoDB.Driver.MongoServer server = MongoDB.Driver.MongoServer.Create(ConfigurationManager.AppSettings["mongoDBConfig"]);
            server.Connect();
            //获取指定数据库
            MongoDB.Driver.MongoDatabase db = server.GetDatabase(ConfigurationManager.AppSettings["mongoDBName"].ToString());
            string collection = txtCollection.Text.Trim();

            //获取表
            MongoDB.Driver.MongoCollection <BsonDocument> col = db.GetCollection <BsonDocument>(collection);
            GetIndexesResult indexsResult = col.GetIndexes();
            string           strIndexs    = string.Empty;

            for (int i = 0; i < indexsResult.Count; i++)
            {
                strIndexs += indexsResult[i].Key.ToString() + ";";
            }
            txtGetIndexs.Text = strIndexs;
        }
        /// <summary>
        /// Lets the server know that this thread is about to begin a series of related operations that must all occur
        /// on the same connection. The return value of this method implements IDisposable and can be placed in a
        /// using statement (in which case RequestDone will be called automatically when leaving the using statement).
        /// </summary>
        /// <param name="initialDatabase">One of the databases involved in the related operations.</param>
        /// <param name="readPreference">The read preference.</param>
        /// <returns>A helper object that implements IDisposable and calls <see cref="RequestDone"/> from the Dispose method.</returns>
        public virtual IDisposable RequestStart(MongoDatabase initialDatabase, ReadPreference readPreference)
        {
            var serverSelector = new ReadPreferenceServerSelector(readPreference);

            return(RequestStart(serverSelector, readPreference));
        }
Exemple #21
0
 /// <summary>
 /// Lets the server know that this thread is about to begin a series of related operations that must all occur
 /// on the same connection. The return value of this method implements IDisposable and can be placed in a
 /// using statement (in which case RequestDone will be called automatically when leaving the using statement).
 /// </summary>
 /// <param name="initialDatabase">One of the databases involved in the related operations.</param>
 /// <returns>A helper object that implements IDisposable and calls <see cref="RequestDone"/> from the Dispose method.</returns>
 public virtual IDisposable RequestStart(MongoDatabase initialDatabase)
 {
     return(RequestStart(initialDatabase, ReadPreference.Primary));
 }
Exemple #22
0
        public virtual IDisposable RequestStart(MongoDatabase initialDatabase, bool slaveOk)
        {
            var readPreference = ReadPreference.FromSlaveOk(slaveOk);

            return(RequestStart(initialDatabase, readPreference));
        }
 public void Shutdown()
 {
     client = null;
     server.Shutdown();
     mdb = null;
 }
Exemple #24
0
 public MongoDatabase(string _IPAddress, string _DatabaseName)
 {
     m_Client   = new MongoDB.Driver.MongoClient("mongodb://" + _IPAddress);
     m_Server   = m_Client.GetServer();
     m_Database = m_Server.GetDatabase(_DatabaseName);
 }
Exemple #25
0
 // internal methods
 internal void SetInputDatabase(MongoDatabase inputDatabase)
 {
     _inputDatabase = inputDatabase;
 }
Exemple #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            string sqlPatientQuery = string.Format("Select Top {0} ID, FirstName, LastName, CONVERT(VARCHAR, BirthDate, 101) as BirthDate, MiddleInitial, Gender, Suffix From ContactEntities where CategoryCode = 'PT' and DeleteFlag = 0", numPatients.Value.ToString());

            string sqlConn = txtSQLConn.Text;

            List <MEPatient>           patients        = new List <MEPatient>();
            List <MEPatientProblem>    patientProblems = new List <MEPatientProblem>();
            List <MECohortPatientView> cohortPatients  = new List <MECohortPatientView>();
            List <MEPatientSystem>     patientSystems  = new List <MEPatientSystem>();
            List <MEContact>           patientContacts = new List <MEContact>();

            List <Problem> problems = null;
            List <State>   states   = null;

            string mongoConnString = txtMongoConn.Text;

            MongoDB.Driver.MongoDatabase mongoDB = Phytel.Services.MongoService.Instance.GetDatabase(mongoConnString);

            mongoDB.GetCollection("Patient").RemoveAll();
            mongoDB.GetCollection("PatientProblem").RemoveAll();
            mongoDB.GetCollection("CohortPatientView").RemoveAll();
            mongoDB.GetCollection("PatientSystem").RemoveAll();
            mongoDB.GetCollection("PatientUser").RemoveAll();
            mongoDB.GetCollection("Contact").RemoveAll();

            //additional collections to clear out since we are reloading patients
            mongoDB.GetCollection("PatientProgram").RemoveAll();
            mongoDB.GetCollection("PatientProgramAttribute").RemoveAll();
            mongoDB.GetCollection("PatientProgramResponse").RemoveAll();

            mongoDB.GetCollection("PatientBarrier").RemoveAll();
            mongoDB.GetCollection("PatientGoal").RemoveAll();
            mongoDB.GetCollection("PatientIntervention").RemoveAll();
            mongoDB.GetCollection("PatientNote").RemoveAll();
            mongoDB.GetCollection("PatientObservation").RemoveAll();
            mongoDB.GetCollection("PatientTask").RemoveAll();
            mongoDB.GetCollection("PatientProgram").RemoveAll();

            IMongoQuery q = Query.EQ("type", 1);

            problems = GetAllProblems(mongoDB.GetCollection("LookUp"));
            states   = GetAllStates(mongoDB.GetCollection("LookUp"));

            System.Random rnd    = new Random();
            int           maxNum = problems.Count() - 1;

            DataSet dsPatients = Phytel.Services.SQLDataService.Instance.ExecuteSQLDirect(sqlConn, sqlPatientQuery, 0);

            int counter = 0;

            foreach (DataRow dr in dsPatients.Tables[0].Rows)
            {
                counter++;
                MECohortPatientView currentPatientView = new MECohortPatientView(txtUserID.Text);

                string patientSystemID = dr["ID"].ToString();

                MEPatient patient = new MEPatient(txtUserID.Text, null)
                {
                    DisplayPatientSystemId = null,
                    FirstName     = dr["FirstName"].ToString(),
                    LastName      = dr["LastName"].ToString(),
                    Gender        = dr["Gender"].ToString().ToUpper(),
                    DOB           = dr["BirthDate"].ToString(),
                    MiddleName    = dr["MiddleInitial"].ToString(),
                    Suffix        = dr["Suffix"].ToString(),
                    PreferredName = dr["FirstName"].ToString() + "o",
                    DeleteFlag    = false,
                    TTLDate       = null,
                    Version       = 1,
                    LastUpdatedOn = DateTime.UtcNow
                };

                List <Address> addresses = new List <Address>();
                List <Email>   emails    = new List <Email>();
                List <Phone>   phones    = new List <Phone>();
                List <Phytel.API.DataDomain.Contact.DTO.CommMode> modes = new List <Phytel.API.DataDomain.Contact.DTO.CommMode>();

                string sqlAddressQuery = string.Format("select top 1 Address1, Address2, City, [State], ZipCode from Address Where OwnerID = {0}", patientSystemID);
                string sqlEmailQuery   = string.Format("select top 1 Address from Email Where OwnerID = {0}", patientSystemID);
                string sqlPhoneQuery   = string.Format("select top 1 DialString from Phone Where OwnerID = {0}", patientSystemID);

                DataSet dsAddress = Phytel.Services.SQLDataService.Instance.ExecuteSQLDirect(sqlConn, sqlAddressQuery, 0);
                DataSet dsEmail   = Phytel.Services.SQLDataService.Instance.ExecuteSQLDirect(sqlConn, sqlEmailQuery, 0);
                DataSet dsPhone   = Phytel.Services.SQLDataService.Instance.ExecuteSQLDirect(sqlConn, sqlPhoneQuery, 0);

                if (dsAddress.Tables[0].Rows.Count > 0)
                {
                    ObjectId stateID = states.Where(x => x.Code == dsAddress.Tables[0].Rows[0]["State"].ToString()).Select(y => y.DataId).FirstOrDefault();

                    addresses.Add(new Address
                    {
                        Id         = ObjectId.GenerateNewId(),
                        Line1      = dsAddress.Tables[0].Rows[0]["Address1"].ToString(),
                        Line2      = dsAddress.Tables[0].Rows[0]["Address2"].ToString(),
                        City       = dsAddress.Tables[0].Rows[0]["City"].ToString(),
                        StateId    = stateID,
                        PostalCode = dsAddress.Tables[0].Rows[0]["ZipCode"].ToString(),
                        TypeId     = ObjectId.Parse("52e18c2ed433232028e9e3a6")
                    });
                }

                if (dsEmail.Tables[0].Rows.Count > 0)
                {
                    emails.Add(new Email {
                        TypeId = ObjectId.Parse("52e18c2ed433232028e9e3a6"), Id = ObjectId.GenerateNewId(), Preferred = true, Text = dsEmail.Tables[0].Rows[0]["Address"].ToString()
                    });
                }

                if (dsPhone.Tables[0].Rows.Count > 0)
                {
                    phones.Add(new Phone {
                        Id = ObjectId.GenerateNewId(), IsText = true, Number = long.Parse(dsPhone.Tables[0].Rows[0]["DialString"].ToString()), PreferredPhone = true, PreferredText = false, TypeId = ObjectId.Parse("52e18c2ed433232028e9e3a6")
                    });
                }

                modes.Add(new Phytel.API.DataDomain.Contact.DTO.CommMode {
                    ModeId = ObjectId.Parse("52e17cc2d433232028e9e38f"), OptOut = false, Preferred = false
                });
                modes.Add(new Phytel.API.DataDomain.Contact.DTO.CommMode {
                    ModeId = ObjectId.Parse("52e17ce6d433232028e9e390"), OptOut = false, Preferred = false
                });
                modes.Add(new Phytel.API.DataDomain.Contact.DTO.CommMode {
                    ModeId = ObjectId.Parse("52e17d08d433232028e9e391"), OptOut = false, Preferred = false
                });
                modes.Add(new Phytel.API.DataDomain.Contact.DTO.CommMode {
                    ModeId = ObjectId.Parse("52e17d10d433232028e9e392"), OptOut = false, Preferred = false
                });

                MEContact patContact = new MEContact(txtUserID.Text, null)
                {
                    Addresses     = addresses,
                    Emails        = emails,
                    FirstName     = string.Empty,
                    Gender        = string.Empty,
                    LastName      = string.Empty,
                    MiddleName    = string.Empty,
                    PatientId     = patient.Id,
                    Phones        = phones,
                    PreferredName = string.Empty,
                    TimeZoneId    = ObjectId.Parse("52e1817dd433232028e9e39e"),
                    Modes         = modes,
                    Version       = 1.0
                };

                MEPatientSystem patSystem = new MEPatientSystem(txtUserID.Text, null)
                {
                    PatientId     = patient.Id,
                    OldSystemId   = patientSystemID,
                    SystemName    = "Atmosphere",
                    DeleteFlag    = false,
                    TTLDate       = null,
                    Version       = 1.0,
                    DisplayLabel  = "ID",
                    LastUpdatedOn = DateTime.UtcNow
                };

                patient.DisplayPatientSystemId = patSystem.Id;

                patients.Add(patient);
                patientSystems.Add(patSystem);
                patientContacts.Add(patContact);

                currentPatientView.PatientID    = patient.Id;
                currentPatientView.LastName     = patient.LastName;
                currentPatientView.Version      = 1.0;
                currentPatientView.SearchFields = new List <SearchField>();
                currentPatientView.SearchFields.Add(new SearchField {
                    Active = true, FieldName = "FN", Value = patient.FirstName
                });
                currentPatientView.SearchFields.Add(new SearchField {
                    Active = true, FieldName = "LN", Value = patient.LastName
                });
                currentPatientView.SearchFields.Add(new SearchField {
                    Active = true, FieldName = "G", Value = patient.Gender.ToUpper()
                });
                currentPatientView.SearchFields.Add(new SearchField {
                    Active = true, FieldName = "DOB", Value = patient.DOB
                });
                currentPatientView.SearchFields.Add(new SearchField {
                    Active = true, FieldName = "MN", Value = patient.MiddleName
                });
                currentPatientView.SearchFields.Add(new SearchField {
                    Active = true, FieldName = "SFX", Value = patient.Suffix
                });
                currentPatientView.SearchFields.Add(new SearchField {
                    Active = true, FieldName = "PN", Value = patient.PreferredName
                });
                currentPatientView.SearchFields.Add(new SearchField {
                    Active = true, FieldName = "PCM"
                });

                List <int> prodIds = new List <int>();
                for (int i = 0; i < numProblems.Value; i++)
                {
                    int probID = rnd.Next(maxNum);
                    while (prodIds.Contains(probID))
                    {
                        probID = rnd.Next(maxNum);
                    }

                    prodIds.Add(probID);
                    patientProblems.Add(new MEPatientProblem(txtUserID.Text)
                    {
                        PatientID     = patient.Id,
                        Active        = true,
                        DeleteFlag    = false,
                        EndDate       = null,
                        Featured      = true,
                        LastUpdatedOn = DateTime.UtcNow,
                        Level         = 1,
                        ProblemID     = problems[probID].DataId,
                        StartDate     = null,
                        TTLDate       = null,
                        Version       = 1.0
                    });
                    currentPatientView.SearchFields.Add(new SearchField {
                        Active = true, FieldName = "Problem", Value = problems[probID].DataId.ToString()
                    });
                }

                cohortPatients.Add(currentPatientView);

                if (counter == 1000)
                {
                    mongoDB.GetCollection("Patient").InsertBatch(patients);
                    mongoDB.GetCollection("PatientProblem").InsertBatch(patientProblems);
                    mongoDB.GetCollection("CohortPatientView").InsertBatch(cohortPatients);
                    mongoDB.GetCollection("PatientSystem").InsertBatch(patientSystems);
                    mongoDB.GetCollection("Contact").InsertBatch(patientContacts);

                    counter = 0;

                    patients        = new List <MEPatient>();
                    patientProblems = new List <MEPatientProblem>();
                    cohortPatients  = new List <MECohortPatientView>();
                    patientSystems  = new List <MEPatientSystem>();
                    patientContacts = new List <MEContact>();
                }
            }
            if (patients.Count > 0)
            {
                mongoDB.GetCollection("Patient").InsertBatch(patients);
                mongoDB.GetCollection("PatientProblem").InsertBatch(patientProblems);
                mongoDB.GetCollection("CohortPatientView").InsertBatch(cohortPatients);
                mongoDB.GetCollection("PatientSystem").InsertBatch(patientSystems);
                mongoDB.GetCollection("Contact").InsertBatch(patientContacts);
            }
        }