public void Setup() { _server = Configuration.TestServer; _server.Connect(); _database = Configuration.TestDatabase; _collection = Configuration.TestCollection; }
private void button3_Click(object sender, EventArgs e) { try { MongoClient mc = new MongoClient("mongodb://*****:*****@ds153123.mlab.com:53123/store_games"); MongoServer ms = mc.GetServer(); MongoDatabase db = ms.GetDatabase("store_games"); ms.Connect(); // creo q este no hace falta ahorita veo MongoCollection collection = db.GetCollection <Persona>("persona"); var query = Query <Persona> .EQ(p => p.Cedula, textBox1.Text); var persona = collection.FindAs <Persona>(query); foreach (Persona item in persona) { if (item.Cedula == "12") { textBox1.Text = item.Cedula; textBox2.Text = item.Name; } } }catch (Exception error) { MessageBox.Show("ERROR " + error); } }
public static bool SetupMongo(String aHost, String aDatabase, String aUsername, String aPassword) { try { sLogger.Debug("[MONGO] Trying to connect to {0}...", aHost); if (!String.IsNullOrWhiteSpace(aUsername) && !String.IsNullOrWhiteSpace(aPassword)) { sClient = new MongoClient(String.Format("mongodb://{0}:{1}@{2}/{3}", aUsername, aPassword, aHost, aDatabase)); } else { sClient = new MongoClient(String.Format("mongodb://{0}/{1}", aHost, aDatabase)); } sServer = sClient.GetServer(); sServer.Connect(); sDatabase = sServer.GetDatabase("zfserver"); return(true); } catch (MongoConnectionException exc) { sLogger.Error("[MONGO] {0}", exc.Message); return(false); } }
// Use this for initialization void Start() { //gets the vumark manager vmm = TrackerManager.Instance.GetStateManager().GetVuMarkManager(); //connectst to the server & collections client = new MongoClient(new MongoUrl(connectionString)); server = client.GetServer(); server.Connect(); db = server.GetDatabase("documents"); coll = db.GetCollection <Statue>("Other"); //queries the database List <Statue> query = coll.AsQueryable <Statue>().Where <Statue>(u => u.vumark == num).ToList(); Debug.Log(query); foreach (var x in query) { Debug.Log(x.name); } //whenever a new vumark is registered, call SetVumark vb = GameObject.Find("VuMark").GetComponent <VuMarkBehaviour> (); vb.RegisterVuMarkTargetAssignedCallback(new System.Action(this.SetVumark)); }
public static MongoServer Connect() { MongoServer server = MongoServer.Create(DatabaseSettings.Instance.ConnectionString); server.Connect(); return(server); }
public static void Open(){ client = new MongoClient("mongodb://*****:*****@ds159200.mlab.com:59200/game"); server = client.GetServer(); server.Connect (); db = server.GetDatabase ("game"); times = db.GetCollection<Time> ("times"); }
public void Setup() { server = MongoServer.Create(); server.Connect(); database = server["onlinetests"]; collection = database["testcollection"]; }
static void Main(string[] args) { MongoServer dbServer = MongoServer.Create(); dbServer.Connect(); MongoDatabase db = dbServer.GetDatabase("test"); if (db.GetCollection("items") == null) { db.CreateCollection("items"); BsonDocument document = new BsonDocument { { "SKU", "I001" }, { "Variant", "Tubes" }, { "Quantity", "10" }, { "Cost", "150.50" } }; db["items"].Insert <BsonDocument>(document); } Console.WriteLine(db["items"].FindOne()); dbServer.Disconnect(); Console.ReadLine(); }
public MongoRepository(MongoUrl mongoUrl, string databaseName) { _client = new MongoClient(mongoUrl); _server = _client.GetServer(); _database = databaseName; _server.Connect(); }
public void Setup() { server = MongoServer.Create(); server.Connect(); server.DropDatabase("onlinetests"); database = server["onlinetests"]; }
/// <summary> /// 初始化MongoDB /// </summary> /// <param name="dbList">数据库列表</param> /// <param name="defaultDbName">默认数据库名称</param> /// <param name="port">默认端口号27017</param> /// <returns></returns> public static bool Init(string[] dbList, string defaultDbName, string ConnectionString = @"mongodb://localhost:27017") { try { _innerServer = new MongoClient(ConnectionString).GetServer(); _innerServer.Connect(); for (var i = 0; i < dbList.Length; i++) { //2017年5月26日 //新版本的MongoDB,不能新建一个空的数据库,必须要带一个数据集 //但是,这里程序一直保有对于数据库的引用,所以即使不创建一个新的数据集,也没有问题。 //以后使用的时候,自然会在创建数据集的时候,创建数据库的。 DatabaseList.Add(dbList[i], _innerServer.GetDatabase(dbList[i])); } _defaultDatabaseName = defaultDbName; InnerDefaultDatabase = GetDatabaseByType(defaultDbName); //http://mongodb.github.io/mongo-csharp-driver/1.10/serialization/ var pack = new ConventionPack(); pack.Add(new IgnoreExtraElementsConvention(true)); pack.Add(new IgnoreIfNullConvention(true)); ConventionRegistry.Register("CustomElementsConvention", pack, t => { return(true); }); //DateTime Localize BsonSerializer.RegisterSerializer(typeof(DateTime), new DateTimeSerializer(DateTimeKind.Local)); return(true); } catch (Exception) { return(false); } }
/// <summary> /// Synchronous connection. This method or <see cref="ConnectAsyncDelegate"/> must be called prior to utilizing the ServerConnection. /// </summary> public void Connect() { _mongoServer = null; MongoClient client = new MongoClient(ConnectionString); _mongoServer = client.GetServer(); _mongoServer.Connect(); }
public async void ConnectAsyncTask() { _mongoServer = null; MongoClient client = new MongoClient(ConnectionString); _mongoServer = await Task.Run(() => client.GetServer()); await Task.Run(() => _mongoServer.Connect()); }
/// <summary> /// 连接数据库 /// </summary> /// <returns></returns> private MongoServer Connect(MongoDbConfig config) { if (_mongoSever == null) { try { var mongoSettings = new MongoServerSettings(); mongoSettings.Server = new MongoServerAddress(config.Server, config.Port); if (config.HasCredential) { mongoSettings.DefaultCredentials = new MongoCredentials(config.UserName, config.Password, true); } _mongoSever = new MongoServer(mongoSettings); _mongoSever.Connect(); } catch (Exception ex) { throw (new Exception("_conn:" + config.ServerConn + "\r\n" + ex)); } } return(_mongoSever); }
public void Setup() { server = MongoServer.Create("mongodb://localhost/?safe=true"); server.Connect(); server.DropDatabase("onlinetests"); database = server["onlinetests"]; }
static void Main(string[] args) { var mongoServerAddress = new MongoServerAddress("127.0.0.1", 27017); var mongoServerSettings = new MongoServerSettings(); mongoServerSettings.Server = mongoServerAddress; var mongoServer = new MongoServer(mongoServerSettings); mongoServer.Connect(); IEnumerable <string> databases = mongoServer.GetDatabaseNames(); var mongoDatabase = mongoServer.GetDatabase("classfrogdb"); var classCollection = mongoDatabase.GetCollection("classes"); classCollection.RemoveAll(); var documents = classCollection.FindAll(); ClassInstance instance = new ClassInstance(); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); mongoServer.Disconnect(); }
public MongoDbUserReadModelStore(string mongoDbConnectionString) { _MongoClient = new MongoClient(mongoDbConnectionString); _MongoServer = _MongoClient.GetServer(); _MongoServer.Connect(); _MongoDatabase = _MongoServer.GetDatabase(DbName); }
public void Setup() { _server = Configuration.TestServer; _server.Connect(); _database = Configuration.TestDatabase; _database.Drop(); }
static void ShardCollection(MongoCollection col, MongoDBAppender appender) { var cmd = new CommandDocument { { "shardCollection", col.Database.Name + '.' + col.Name }, { "key", new BsonDocument(appender.ShardKey, 1) }, }; try { CreateIndex(col, appender.ShardKey); MongoServer server = col.Database.Server; var dbCfg = new MongoDatabaseSettings(); var adminDb = new MongoDatabase(server, "admin", dbCfg); server.Connect(); CommandResult shcr = adminDb.RunCommand(cmd); } catch (MongoCommandException mex) { if (!mex.Message.ToLower().Contains("already ")) { throw; } else { Console.WriteLine("Sharding already enabled!"); } } }
public void Setup() { server = MongoServer.Create("mongodb://localhost/?safe=true"); server.Connect(); database = server["onlinetests"]; collection = database["testcollection"]; }
}//end insertClient public int loginClient(string mail, string pass) { int ret = 0; try{ MongoClient mc = new MongoClient("mongodb://*****:*****@ds139428.mlab.com:39428/info_aplicada_ucr"); MongoServer ms = mc.GetServer(); MongoDatabase db = ms.GetDatabase("info_aplicada_ucr"); ms.Connect(); MongoCollection collection = db.GetCollection <Client>("Client"); List <Client> clients = selectClient(); foreach (Client item in clients) { if (item.mail.Equals(mail) && item.pass.Equals(pass)) { ret = 1; break; } else { ret = 0; } //End if (item.mail.Equals(mail) && item.pass.Equals(pass)) } //End foreach (Client item in clients) }catch (Exception error) { ret = 0; } return(ret); }//end insertClient
public void Connect() { if (server != null) { server.Connect(); } }
// static constructor static Configuration() { var connectionString = SuiteConfiguration.ConnectionString.ToString(); var mongoUrl = new MongoUrl(connectionString); var clientSettings = MongoClientSettings.FromUrl(mongoUrl); if (!clientSettings.WriteConcern.IsAcknowledged) { clientSettings.WriteConcern = WriteConcern.Acknowledged; // ensure WriteConcern is enabled regardless of what the URL says } __testClient = new MongoClient(clientSettings); #pragma warning disable 618 __testServer = __testClient.GetServer(); #pragma warning restore __testDatabase = __testServer.GetDatabase(mongoUrl.DatabaseName ?? SuiteConfiguration.DatabaseNamespace.DatabaseName); __testCollection = __testDatabase.GetCollection("testcollection"); // connect early so BuildInfo will be populated __testServer.Connect(); var isMasterResult = __testDatabase.RunCommand("isMaster").Response; BsonValue setName = null; if (isMasterResult.TryGetValue("setName", out setName)) { __testServerIsReplicaSet = true; } }
public void Save(InspectOriginalData oData, List <InspectItemData> itemDatas) { //创建数据库链接 MongoClient mc = new MongoClient(ConnectionManager.MongodbConectionStr); MongoServer server = mc.GetServer(); server.Connect(); //获得数据库 MongoDatabase db = server.GetDatabase("InspectDB"); MongoCollection colOdata = db.GetCollection("InspectOriginalData"); MongoCollection colItemdata = db.GetCollection("InspectItemData"); try { //插入原始监测数据 colOdata.Insert <InspectOriginalData>(oData); //插入监测项目数据 colItemdata.InsertBatch <InspectItemData>(itemDatas); } catch (Exception ex) { throw ex; } finally { //关闭数据库连接 if (server != null) { server.Disconnect(); } } }
/// <summary> /// 初始化MongoDB /// </summary> /// <returns></returns> public static bool Init() { innerServer = MongoServer.Create(connectionstring); innerServer.Connect(); innerDatabase = innerServer.GetDatabase("Trip"); return(true); }
} //end deleteProduct public Boolean updateProduct(String name, String category, int price, int quantity, String status, String path) { Boolean ret = false;// return variable try { MongoClient mc = new MongoClient("mongodb://*****:*****@ds139428.mlab.com:39428/info_aplicada_ucr"); MongoServer ms = mc.GetServer(); MongoDatabase db = ms.GetDatabase("info_aplicada_ucr"); ms.Connect(); MongoCollection collection = db.GetCollection <Product>("Product"); var query = Query.EQ("name", name); // comparacion para hacer el update del documento de la bd var product = collection.FindOneAs <Product>(query); product.name = name; product.category = category; product.price = price; product.quantity = quantity; product.status = status; product.path = path; collection.Save(product); ret = true; } catch (Exception error) { ret = true; } //catch return(ret); } //end updateProduct
/// <summary> /// 获取子表数据 /// </summary> /// <param name="deviceList"></param> /// <returns></returns> public List <InspectItemData> getInspectItemData(string DeviceSN, DateTime st, DateTime et) { //创建数据库链接 MongoClient mc = new MongoClient(ConnectionManager.MongodbConectionStr); MongoServer server = mc.GetServer(); server.Connect(); //获得数据库 MongoDatabase db = server.GetDatabase("InspectDB"); MongoCollection colOdata = db.GetCollection("InspectItemData"); List <InspectItemData> list = null; try { //插入原始监测数据 QueryDocument query = new QueryDocument(); list = colOdata.FindAllAs <InspectItemData>().Where(x => x.DeviceSN == DeviceSN && x.InspectTime >= st && x.InspectTime < et) .OrderBy(x => x.InspectTime).ToList <InspectItemData>(); return(list); } catch (Exception ex) { throw ex; } finally { //关闭数据库连接 if (server != null) { server.Disconnect(); } } }
}//End selectManager public Boolean loginManager(String name, String pass) { Boolean ret = false; try{ MongoClient mc = new MongoClient("mongodb://*****:*****@ds139428.mlab.com:39428/info_aplicada_ucr"); MongoServer ms = mc.GetServer(); MongoDatabase db = ms.GetDatabase("info_aplicada_ucr"); ms.Connect(); MongoCollection collection = db.GetCollection <Manager>("Manager"); Manager client = new Manager(); List <Manager> clients = selectManager(); foreach (Manager item in clients) { if (item.name.Equals(name) && item.password.Equals(pass)) { ret = true; break; } else { ret = false; } //End if (item.mail.Equals(mail) && item.pass.Equals(pass)) } //End foreach (Client item in clients) } catch (Exception error) { ret = false; } //End try-catch (Exception error) return(ret); } //End loginManager
/// <summary> /// 封装对MongoDB 的操作处理。 /// </summary> public MongoDBHelper(bool createNewCollection) { var cfgs = CONNECTION_STRING.Split(':'); if (cfgs.Length != 2) { throw new MB.Util.APPException("请先配置Mongo数据库连接字符窜配置有误.例如:MongoDbConnection=IP:database", Util.APPMessageType.SysErrInfo); } _ConnectionString = string.Format("mongodb://{0}", cfgs[0]); _DataBaseName = cfgs[1]; _Server = MongoServer.Create(_ConnectionString); string collectionName = typeof(T).FullName; //获取databaseName对应的数据库,不存在则自动创建 MongoDatabase mongoDatabase = _Server.GetDatabase(_DataBaseName) as MongoDatabase; if (createNewCollection) { mongoDatabase.DropCollection(collectionName); } if (mongoDatabase.CollectionExists(collectionName)) { mongoDatabase.CreateCollectionSettings <T>(collectionName); } _DataCollection = mongoDatabase.GetCollection <T>(collectionName); //链接数据库 _Server.Connect(); }
public void Setup() { _server = MongoServer.Create("mongodb://localhost/?safe=true"); _server.Connect(); _database = _server["onlinetests"]; _collection = _database["linqtests"]; }
// static constructor static Configuration() { var connectionString = Environment.GetEnvironmentVariable("MONGO_URI") ?? "mongodb://localhost/?w=1"; var mongoUrl = new MongoUrl(connectionString); var clientSettings = MongoClientSettings.FromUrl(mongoUrl); if (!clientSettings.WriteConcern.Enabled) { clientSettings.WriteConcern = WriteConcern.Acknowledged; // ensure WriteConcern is enabled regardless of what the URL says } __testClient = new MongoClient(clientSettings); __testServer = __testClient.GetServer(); __testDatabase = __testServer.GetDatabase(mongoUrl.DatabaseName ?? "csharpdriverunittests"); __testCollection = __testDatabase.GetCollection("testcollection"); // connect early so BuildInfo will be populated __testServer.Connect(); var isMasterResult = __testDatabase.RunCommand("isMaster").Response; BsonValue setName = null; if (isMasterResult.TryGetValue("setName", out setName)) { __testServerIsReplicaSet = true; } }
} //end deleteCustomerPurchase public Boolean updateCustomerPurchase(String clientName, String productName, int quantity, int totalPay) { Boolean ret = false;// return variable try { MongoClient mc = new MongoClient("mongodb://*****:*****@ds139428.mlab.com:39428/info_aplicada_ucr"); MongoServer ms = mc.GetServer(); MongoDatabase db = ms.GetDatabase("info_aplicada_ucr"); ms.Connect(); MongoCollection collection = db.GetCollection <CustomerPurchase>("Client_Report"); var query = Query.EQ("clientName", clientName); // comparacion para hacer el update del documento de la bd var customerPurchase = collection.FindOneAs <CustomerPurchase>(query); customerPurchase.clientName = clientName; customerPurchase.productName = productName; customerPurchase.quantity = quantity; customerPurchase.totalPay = totalPay; collection.Save(customerPurchase); ret = true; }//try catch (Exception error) { ret = true; } //catch return(ret); } //end updateCustomerPurchase
public bool InitMongoDB(string connectionString, string connectionString2 = null) { try { this.conn = connectionString; client = new MongoClient(conn); server = client.GetServer(); server.Connect(); DBNames = server.GetDatabaseNames().ToList(); if (server.Instance.State != MongoServerState.Connected) { //cons .Show("服务器连接失败"); Console.WriteLine("mongodb数据库连接失败"); return(false); } if (connectionString2 != null) { clientTarget = new MongoClient(connectionString2); serverTarget = clientTarget.GetServer(); serverTarget.Connect(); DBNamesTarget = serverTarget.GetDatabaseNames().ToList(); if (serverTarget.Instance.State != MongoServerState.Connected) { //cons .Show("服务器连接失败"); Console.WriteLine("mongodb数据库2连接失败"); clientTarget = null; } } //var xxxx = client.GetDatabase("local"); database = client.GetDatabase(dbName); //database.CreateCollectionAsync("test"); //xxxx.CreateCollectionAsync("test"); //var ll = xxxx.GetCollection<Entity>("test"); //var lx = database.GetCollection<Entity>("test"); //Entity ee = new Entity() { Name = "JHJ" }; //ll.InsertOneAsync(ee); //lx.InsertOneAsync(ee); //var x = ee.Id; //ee.Name = "new"; //ll.InsertOneAsync(ee); collection = database.GetCollection <Tiled>("Titles");//数据库表 this.CollectionList.Add(dbName, collection); Console.WriteLine("mongodb数据库连接成功"); Console.WriteLine(server.Instance.GetServerDescription().ToString()); } catch (Exception) { Console.WriteLine("mongodb数据库连接失败"); return(false); } return(true); }
private void btnConnect_Click(object sender, EventArgs e) { Card.CardUtility.Init(); innerServer = MongoServer.Create(@"mongodb://localhost:28030"); innerServer.Connect(); innerDatabase = innerServer.GetDatabase("HearthStone"); innerCollection = innerDatabase.GetCollection("Card"); }
private void Init(string conStr) { MongoUrl url = new MongoUrl(conStr); string dbName = string.IsNullOrEmpty(url.DatabaseName) ? "TEST" : url.DatabaseName; Server = MongoServer.Create(conStr); Server.Connect(); Database = Server.GetDatabase(dbName); }
public void Insert(EmployeeListDTO _Obj) { try { server.Connect(); MongoCollection <EmployeeListDTO> Collection_ = Database_.GetCollection <EmployeeListDTO>("employee"); Collection_.Insert(_Obj); } catch { throw; } finally { server.Disconnect(); } }
public MongoRepository( string connectionString, string database) { _Server = MongoServer.Create(connectionString); _Database = connectionString.ParseDatabaseName() ?? database; _Server.Connect(); }
public MongoRepository( MongoServerSettings settings, string database) { _Server = new MongoServer(settings); _Database = database; _Server.Connect(); }
/// <summary> /// 导入按钮事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnImport_Click(object sender, EventArgs e) { innerServer = MongoServer.Create(@"mongodb://localhost:28030"); innerServer.Connect(); innerDatabase = innerServer.GetDatabase("HearthStone"); innerCollection = innerDatabase.GetCollection("Card"); if (String.IsNullOrEmpty(ExcelPicker.SelectedPathOrFileName)) return; Import(); GC.Collect(); innerServer.Disconnect(); }
protected virtual void OnTestFixtureSetUp() { if(IoC.IsNotInitialized) IoC.Initialize(); if(IsDebugEnabled) log.Debug("MongoDB 서버에 접속합니다. connectionString=[{0}]", DefaultConnectionString); Server = MongoServer.Create(DefaultConnectionString); Server.Connect(); Server.DropDatabase(DefaultDatabaseName); Database = Server[DefaultDatabaseName]; }
/// <summary> /// Connects to the upstream MongoDB server and returns if successful. /// </summary> private static bool ConnectToUpstream( ) { try { upstream = MongoServer.Create( ); upstream.Connect( ); upstream.Ping( ); return true; } catch ( MongoConnectionException ) { return false; } }
public void Setup() { _server = Configuration.TestServer; _server.Connect(); _database = Configuration.TestDatabase; _collection = Configuration.GetTestCollection<C>(); _collection.Drop(); _collection.Insert(new C { X = 1, Y = 11 }); _collection.Insert(new C { X = 2, Y = 12 }); _collection.Insert(new C { X = 3, Y = 13 }); _collection.Insert(new C { X = 4, Y = 14 }); _collection.Insert(new C { X = 5, Y = 15 }); }
public void Setup() { server = MongoServer.Create("mongodb://localhost/?safe=true"); server.Connect(); database = server["onlinetests"]; collection = database.GetCollection<C>("linqtests"); collection.Drop(); collection.Insert(new C { X = 1, Y = 11 }); collection.Insert(new C { X = 2, Y = 12 }); collection.Insert(new C { X = 3, Y = 13 }); collection.Insert(new C { X = 4, Y = 14 }); collection.Insert(new C { X = 5, Y = 15 }); }
public static MongoDatabase GetSessionStoreDatabase(MongoServer server, string catalogName) { MongoDatabase database = null; try { if (server.State == MongoServerState.Disconnected || server.State == MongoServerState.None) server.Connect(); database = server.GetDatabase(catalogName); } catch (Exception ex) { throw ex; } return database; }
public MongoEventStore(string connectionString) { var connectionStringBuilder = new MongoConnectionStringBuilder(connectionString); _databaseName = connectionStringBuilder.DatabaseName; _server = MongoServer.Create(connectionString); _server.Connect(); _database = _server.GetDatabase(_databaseName); Collection.EnsureIndex( new IndexKeysBuilder() .Ascending("AggregateRootId") .Ascending("Sequence") ); }
public MongoServerState connect() { try { var connectionString = "mongodb://10.109.83.122/?safe=true"; mongo = MongoServer.Create(connectionString); mongo.Connect(); return mongo.State; } catch (Exception ex) { MessageBox.Show(ex.Message, "SEQuipt - MongoDB Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return mongo.State; } }
private static bool TestConnection(MongoServer server) { bool result = false; try { server.Connect(); if (server.State == MongoServerState.Connected || server.State == MongoServerState.ConnectedToSubset) { result = true; } } finally { server.Disconnect(); } return result; }
protected void Start() { client = new MongoClient(new MongoUrl("mongodb://*****:*****@ds049624.mlab.com:49624/wordriver")); server = client.GetServer(); server.Connect(); db = server.GetDatabase("wordriver"); allContextPacks = db.GetCollection<BsonDocument>("contextpacks"); allWords = db.GetCollection<BsonDocument>("words"); allWordPacks = db.GetCollection<BsonDocument>("wordpacks"); foreach (BsonDocument item in allWords.FindAll()) { BsonElement name = item.GetElement("name"); string wordValue = name.Value.ToString(); alltiles.Add(wordValue); } Readable.Speak("Welcome to Story Builder!"); }
public MongoDatabase MongoConnection(string dbName) { try { server = GetMongoConnection.GetConnection().GetServer(); server.Connect(); var db = server.GetDatabase(dbName); return db; } catch (System.TimeoutException tmex) { throw new TimeoutException(tmex.Message); } catch (MongoConnectionException monsex) { throw new MongoException(monsex.Message); } }
public MongoServer GetMongoServer() { try { var mongoUrl = new MongoUrl(AircraftMongoDb.ConnectionString); var clientSettings = MongoClientSettings.FromUrl(mongoUrl); if (!clientSettings.WriteConcern.Enabled) { clientSettings.WriteConcern.W = 1; // ensure WriteConcern is enabled regardless of what the URL says } var mongoClient = new MongoClient(clientSettings); this.m_mongoServer = mongoClient.GetServer(); m_mongoServer.Connect(); return m_mongoServer; } catch (Exception ex) { throw ex; } }
private void btnConnect_Click(object sender, EventArgs e) { MainForm form = this.Owner as MainForm; if (form != null) { MongoServer server = new MongoServer(txtServerName.Text, int.Parse(txtPortNumber.Text), false); try { server.Connect(); } catch (SocketException exc) { MessageBox.Show("Unable to connect: " + exc.Message, "Unable to connect!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } form.Server = server; this.Close(); } }
public void Connect(string host, ushort port, string database) { if (Mongo != null) { try { Mongo.Disconnect(); } catch { } } Mongo = MongoServer.Create(string.Format("mongodb://{0}:{1}", host, port)); try { Mongo.Connect(); } catch (Exception) { Mongo = null; throw; } Database = Mongo.GetDatabase(database); GridFS = new MongoGridFS(Database); }
static void Main(string[] args) { var mongoServerAddress = new MongoServerAddress("127.0.0.1", 27017); var mongoServerSettings = new MongoServerSettings(); mongoServerSettings.Server = mongoServerAddress; var mongoServer = new MongoServer(mongoServerSettings); mongoServer.Connect(); IEnumerable<string> databases = mongoServer.GetDatabaseNames(); var mongoDatabase = mongoServer.GetDatabase("classfrogdb"); var classCollection = mongoDatabase.GetCollection("classes"); classCollection.RemoveAll(); var documents = classCollection.FindAll(); ClassInstance instance = new ClassInstance(); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); classCollection.Insert(instance.NewDocument()); mongoServer.Disconnect(); }
public Agenda() { _server = MongoServer.Create(URL_MONGO); _server.Connect(); }