public void TestUpdates() { SessionStateItemCollection items = new SessionStateItemCollection(); items["Val1"] = "value"; byte[] serializedItems = Serialize(items); Binary b = new Binary(serializedItems); List<string> ids = new List<string>(); ICursor allSessions; using (var mongo = new Mongo(config)) { mongo.Connect(); allSessions = mongo["session_store"]["sessions"].FindAll(); foreach (Document session in allSessions.Documents) { string id = (string)session["SessionId"]; ids.Add(id); } } foreach (string s in ids) { var sessionStore = new SessionStore("test"); sessionStore.UpdateSession(s, 2, b, "AppName", items.Count, 0); } }
public MongoService() { var mongo = new Mongo(); mongo.Connect(); IMongoDatabase mongoDatabase = mongo.GetDatabase(ConfigurationManager.AppSettings["Database"]); _collection = mongoDatabase.GetCollection<Entity>("entity"); }
void Test() { //Create a default mongo object. This handles our connections to the database. //By default, this will connect to localhost, //port 27017 which we already have running from earlier. var mongo = new Mongo(); mongo.Connect(); //Get the blog database. If it doesn't exist, that's ok because MongoDB will create it //for us when we first use it. Awesome!!! var db = mongo.GetDatabase("blog"); //Get the Post collection. By default, we'll use //the name of the class as the collection name. Again, //if it doesn't exist, MongoDB will create it when we first use it. var collection = db.GetCollection<Test>(); //this deletes everything out of the collection so we can run this over and over again. collection.Delete(p => true); //Create a Post to enter into the database. var test = new Test("Test1", null, Types.Programming, "Lesnik"); //Save the post. This will perform an upsert. As in, if the post //already exists, update it, otherwise insert it. collection.Save(test); }
static void Main(string[] args) { Mongo mongo = new Mongo(connectionString); //定义一个文档对象,存入两个键值对 mongo.Connect(); //获取databaseName对应的数据库,不存在则自动创建 MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; //获取collectionName对应的集合,不存在则自动创建 MongoCollection <Document> mongoCollection = mongoDatabase.GetCollection <Document>(collectionName) as MongoCollection <Document>; try { Document doc = new Document(); doc["ID"] = 1; doc["Msg"] = "Hello World!"; //将这个文档对象插入集合 mongoCollection.Insert(doc); //在集合中查找键值对为ID=1的文档对象 Document docFind = mongoCollection.FindOne(new Document { { "ID", 1 } }); //输出查找到的文档对象中键“Msg”对应的值,并输出 Console.WriteLine(Convert.ToString(docFind["Msg"])); } finally { //关闭链接 mongo.Disconnect(); } }
public Session Get(string id, string applicationName) { Document selector = new Document() { { "SessionId", id }, { "ApplicationName", applicationName } }; Session session; try { Document sessionDoc; using (var mongo = new Mongo(config)) { mongo.Connect(); sessionDoc = mongo["session_store"]["sessions"].FindOne(selector); } if (sessionDoc == null) { session = null; } else { session = new Session(sessionDoc); } } catch (MongoException ex) { throw new Exception("Could not insert a new session", ex); } return session; }
public void GetMongoDBData() { var mongo = new Mongo(); mongo.Connect(); //Get the blog database. If it doesn't exist, that's ok because MongoDB will create it //for us when we first use it. Awesome!!! var db = mongo.GetDatabase("blog"); //Get the Post collection. By default, we'll use //the name of the class as the collection name. Again, //if it doesn't exist, MongoDB will create it when we first use it. var collection = db.GetCollection<Post>(); //this deletes everything out of the collection so we can run this over and over again. collection.Remove(p => true); //Create a Post to enter into the database. var post = new Post() { Title = "My First Post", Body = "This isn't a very long post.", CharCount = 27, Comments = new List<Comment> { { new Comment() { TimePosted = new DateTime(2010,1,1), Email = "*****@*****.**", Body = "This article is too short!" } }, { new Comment() { TimePosted = new DateTime(2010,1,2), Email = "*****@*****.**", Body = "I agree with Bob." } } } }; collection.Save(post); }
public long CountAll(out string msg) { Mongo mongo = new Mongo(connectionString); MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>; try { mongo.Connect(); List<EndUser> userList = new List<EndUser>(); IEnumerable<Document> doc = mongoCollection.FindAll().Documents; foreach (Document d in doc) { EndUser user = new EndUser(); user.AutoID = d["AutoID"].ToString(); user.EnduserName = d["EnduserName"].ToString(); user.Identities = d["Identities"].ToString().Split('|'); user.IsValid = bool.Parse(d["IsValid"].ToString()); user.LastModifyTime = DateTime.Parse(d["LastModifyTime"].ToString()); user.SimCardNo = d["SimCardNo"].ToString(); userList.Add(user); } //Document[] docs= doc.ToArray<Document>(); msg = "查询成功"; mongo.Disconnect(); return userList.Count; } catch (Exception ex) { msg = ex.Message; mongo.Disconnect(); return 0; } }
static void Main(string[] args) { var firstNames = new[] { "Tim", "Dave", "Craig", "Noah", "Mark", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; var lastNames = new[] { "Rayburn", "O'Hara", "Neuwirt", "Coad", "Mikaelis" }; var daf = new DictionaryAdapterFactory(); var da = daf.GetAdapter<IPatient>(new Document() .Add("FirstName", "Tim") .Add("LastName", "Rayburn") .Add("Address", new Document().Add("Line1","Dallas,TX"))); using (var mongo = new Mongo()) { var db = mongo.GetDatabase("StElmo"); var coll = db.GetCollection<Patient>().Linq().Select(p => p.FirstName == "Tim").ToList(); var query = from p in db.GetCollection<Patient>().Linq() where p.FirstName == "Tim" select p; } Console.WriteLine(da.FirstName); Console.WriteLine(da.Address.Line1); Console.WriteLine("Complete"); Console.ReadLine(); }
/// <summary> /// 删除操作 /// </summary> /// <param name="person"></param> /// <returns></returns> public void Delete(Expression <Func <T, bool> > func) { using (MongoDB.Mongo mongo = new MongoDB.Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection <T>(collectionName); //这个地方要注意,一定要加上T参数,否则会当作object类型处理 //导致删除失败 collection.Remove <T>(func); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } }
/// <summary> ///读取单条记录 /// </summary> /// <param name="person"></param> /// <returns></returns> public T Single(Expression <Func <T, bool> > func) { using (MongoDB.Mongo mongo = new MongoDB.Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection <T>(collectionName); var single = collection.Linq().FirstOrDefault(func); mongo.Disconnect(); return(single); } catch (Exception) { mongo.Disconnect(); throw; } } }
/// <summary> ///获取集合 /// </summary> /// <param name="person"></param> /// <returns></returns> public List <T> List(int pageIndex, int pageSize, Expression <Func <T, bool> > func, out int pageCount) { pageCount = 0; using (MongoDB.Mongo mongo = new MongoDB.Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection <T>(collectionName); pageCount = Convert.ToInt32(collection.Count()); var personList = collection.Linq().Where(func).Skip(pageSize * (pageIndex - 1)) .Take(pageSize).Select(i => i).ToList(); mongo.Disconnect(); return(personList); } catch (Exception) { mongo.Disconnect(); throw; } } }
static void Main(string[] args) { int numItems = 100000; DateTime start, end; var mongo = new Mongo(); mongo.Connect(); var db = mongo.GetDatabase("test"); var logs = db.GetCollection("logs"); var query = logs.FindAll(); start = DateTime.Now; for (int i = 0; i < numItems; i++) { var log = new Document(); log["DateInserted"] = DateTime.Now; log["SeqNum"] = Guid.NewGuid(); log["Reference"] = String.Format("Hey {0}", i.ToString()); logs.Insert(log); } end = DateTime.Now; Console.WriteLine("Inserted " + numItems + " in " + end.Subtract(start).TotalMilliseconds + "ms"); Console.ReadLine(); }
public bool DeleteEnduser(string iSimCardNo, out string msg) { Mongo mongo = new Mongo(connectionString); MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>; try { mongo.Connect(); //List<EndUser> userList = new List<EndUser>(); IEnumerable<Document> doc = mongoCollection.Find(new Document { { "SimCardNo", iSimCardNo } }).Documents; mongoCollection.Remove(new Document { { "SimCardNo", iSimCardNo } }); //foreach (Document d in doc) //{ // EndUser user = new EndUser(); // user.AutoID = d["AutoID"].ToString(); // user.EnduserName = d["EnduserName"].ToString(); // user.Identities = d["Identities"].ToString().Split('|'); // user.IsValid = bool.Parse(d["IsValid"].ToString()); // user.LastModifyTime = DateTime.Parse(d["LastModifyTime"].ToString()); // user.SimCardNo = d["SimCardNo"].ToString(); // userList.Add(user); //} msg = "删除成功"; mongo.Disconnect(); return true; } catch (Exception ex) { msg = ex.Message; mongo.Disconnect(); return false; } }
public static void Init() { LoadedDBConnections = new Dictionary<String, IMongoDatabase>(); DbConnection = new Mongo(); DbConnection.Connect(); RunTests(); }
public void TearDown() { using (var mongo = new Mongo(config)) { mongo.Connect(); mongo["session_store"]["$cmd"].FindOne(new Document().Add("drop", "sessions")); } }
internal Mongo Connect( MongoProvider provider ) { var cxn = BuildMongoConnectionString(_driveParameters, provider.Credential); var mongo = new Mongo( cxn ); mongo.Connect(); return mongo; }
public static IMongo ConnectMongo() { var url = ConfigurationManager.AppSettings["mongo-connection"]; var mongo = new Mongo(url); mongo.Connect(); return mongo; }
public MongoEventStore(string connectionString, ITypeCatalog typeCatalog) { var connectionStringBuilder = new MongoConnectionStringBuilder(connectionString); var configuration = BuildMongoConfiguration(typeCatalog, connectionString); var mongo = new Mongo(configuration); mongo.Connect(); database = mongo.GetDatabase(connectionStringBuilder.Database); }
public static void Main(string[] args) { SetupDocuments(); Mongo m = new Mongo(); m.Connect(); IMongoDatabase db = m["benchmark"]; db.Metadata.DropDatabase(); Console.WriteLine("Starting Tests"); RunEncodeTest("encode (small)",small); RunEncodeTest("encode (medium)", medium); RunEncodeTest("encode (large)", large); RunDecodeTest("decode (small)",small); RunDecodeTest("decode (medium)", medium); RunDecodeTest("decode (large)", large); db.Metadata.DropDatabase(); RunInsertTest("insert (small, no index)", db, "small_none",small,false,false); RunInsertTest("insert (medium, no index)", db, "medium_none",medium,false,false); RunInsertTest("insert (large, no index)", db, "large_none",large,false,false); RunInsertTest("insert (small, indexed)", db, "small_index",small,true,false); RunInsertTest("insert (medium, indexed)", db, "medium_index",medium,true,false); RunInsertTest("insert (large, indexed)", db, "large_index",large,true,false); RunInsertTest("batch insert (small, no index)", db, "small_bulk",small,false,true); RunInsertTest("batch insert (medium, no index)", db, "medium_bulk",medium,false,true); RunInsertTest("batch insert (large, no index)", db, "large_bulk",large,false,true); Document fonespec = new Document().Add("x",perTrial/2); RunFindTest("find_one (small, no index)", db, "small_none",fonespec,false); RunFindTest("find_one (medium, no index)", db, "medium_none",fonespec,false); RunFindTest("find_one (large, no index)", db, "large_none",fonespec,false); RunFindTest("find_one (small, indexed)", db, "small_index",fonespec,false); RunFindTest("find_one (medium, indexed)", db, "medium_index",fonespec,false); RunFindTest("find_one (large, indexed)", db, "large_index",fonespec,false); RunFindTest("find (small, no index)", db, "small_none",fonespec,true); RunFindTest("find (medium, no index)", db, "medium_none",fonespec,true); RunFindTest("find (large, no index)", db, "large_none",fonespec,true); RunFindTest("find (small, indexed)", db, "small_index",fonespec,true); RunFindTest("find (medium, indexed)", db, "medium_index",fonespec,true); RunFindTest("find (large, indexed)", db, "large_index",fonespec,true); Document findRange = new Document().Add("x",new Document().Add("$gt",perTrial/2).Add("$lt", perTrial/2 + batchSize)); RunFindTest("find range (small, indexed)", db, "small_index",findRange,true); RunFindTest("find range (medium, indexed)", db, "medium_index",findRange,true); RunFindTest("find range (large, indexed)", db, "large_index",findRange,true); System.Console.WriteLine("Press any key to continue..."); System.Console.ReadKey(); }
public MongoUnitOfWorkFactory(string connection) { var builder = new MongoConfigurationBuilder(); builder.ConnectionString(connection); builder.Mapping(m => m.DefaultProfile(profile => profile .UseIdUnsavedValueConvention(new UnsavedIdConvention()))); _mongo = new Mongo(builder.BuildConfiguration()); }
public void EvictSession(Session session) { Document selector = new Document() { { "SessionId", session.SessionID }, { "ApplicationName", session.ApplicationName }, { "LockId", session.LockID } }; using (var mongo = new Mongo(connectionString)) { mongo.Connect(); mongo[applicationName]["sessions"].Remove(selector); } }
public void insertData(qzsImgModel model) { using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); var db = mongo.GetDatabase(databaseString); var collection = db.GetCollection<qzsImgModel>(); collection.Insert(model); } }
public void EvictSession(string id, string applicationName, object lockId) { Document selector = new Document() { { "SessionId", id }, { "ApplicationName", applicationName }, { "LockId", lockId } }; using (var mongo = new Mongo(connectionString)) { mongo.Connect(); mongo[applicationName]["sessions"].Remove(selector); } }
public void Insert(IEnumerable<DomainEvent> domainEvents) { using(var mongo = new Mongo(configuration)) { mongo.Connect(); var database = mongo.GetDatabase(databaseName); var eventsCollection = database.GetCollection<DomainEvent>("events"); eventsCollection.Insert(domainEvents); } }
public void EvictExpiredSession(string id, string applicationName) { Document selector = new Document() { { "SessionId", id }, { "ApplicationName", applicationName }, {"Expires",new Document(){{"$lt",DateTime.Now}} }}; using (var mongo = new Mongo(connectionString)) { mongo.Connect(); mongo[applicationName]["sessions"].Remove(selector); } }
public List<qzsImgModel> selectData100() { List<qzsImgModel> im = new List<qzsImgModel>(); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); var db = mongo.GetDatabase(databaseString); var collecton = db.GetCollection<qzsImgModel>().Find(x => x.qzsFormat == 100).Sort("{qzsUpdateTime:-1}").Documents.ToList(); im.AddRange(collecton); } return im; }
public IEnumerable<DomainEvent> GetEventsByEventTypes(IEnumerable<Type> domainEventTypes) { using(var mongo = new Mongo(configuration)) { mongo.Connect(); var database = mongo.GetDatabase(databaseName); var selector = new Document {{"_t", new Document {{"$in", domainEventTypes.Select(t => t.Name).ToArray()}}}}; var cursor = database.GetCollection<DomainEvent>("events").Find(selector); return cursor.Documents.ToList(); } }
/// <summary> /// 记录日志 /// </summary> /// <param name="ex">出错的信息</param> public static void LogRecord(Exception ex) { Mongo mongoDBLog = null; try { mongoDBLog = new Mongo(ConfigurationManager.AppSettings["mongoDBConfig"]); mongoDBLog.Connect(); var dbLog = mongoDBLog.GetDatabase("USTALogs"); var collection = dbLog.GetCollection<USTALogs>(DateTime.Now.Date.ToString("yyyy-MM-dd")); USTALogs ustaLogs = new USTALogs { errorTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), errorURL = HttpContext.Current.Request.Url.ToString(), accessIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], errorCode = System.Runtime.InteropServices.Marshal.GetHRForException(ex).ToString(), errorObject = ex.Source, errorStackTrace = ex.StackTrace, errorMessage = ex.Message, errorHelpLink = ex.HelpLink, errorMethod = (ex.TargetSite == null ? string.Empty : ex.TargetSite.ToString()) }; collection.Insert(ustaLogs); } catch (Exception mongoDBLogException) { string mongoDBInfoError = HttpContext.Current.Server.MapPath("/LogFiles/WriteMongoDBInfoError_" + DateTime.Now.Date.ToString("yyyy-MM-dd")); if (!System.IO.File.Exists(mongoDBInfoError)) { System.IO.File.Create(mongoDBInfoError); } } finally { if (mongoDBLog != null) { mongoDBLog.Disconnect(); mongoDBLog.Dispose(); } } ////错误信息 //string exceptionMessage = "\n出错页面地址为:" + HttpContext.Current.Request.Url.ToString() + "\n\n访问者IP为:" + HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] + "\n" + "\n异常码为:" + System.Runtime.InteropServices.Marshal.GetHRForException(ex) + "\n出错对象为:" + ex.Source + "\n堆栈信息为:" + ex.StackTrace + "\n出错函数为:" + ex.TargetSite + "\n出错信息为:" + ex.Message + "\n参考帮助链接为:" + ex.HelpLink + "\n\n"; ////记录错误日志 //log.Error(exceptionMessage); }
public IEnumerable<DomainEvent> GetEvents(Guid aggregateRootId, int startSequence) { using(var mongo = new Mongo(configuration)) { mongo.Connect(); var database = mongo.GetDatabase(databaseName); var eventsCollection = database.GetCollection<DomainEvent>("events").Linq(); return (from domainEvent in eventsCollection where domainEvent.AggregateRootId == aggregateRootId where domainEvent.Sequence > startSequence select domainEvent).ToList(); } }
/// <summary> /// Setup the collection and insert some data into it. /// </summary> public void Setup() { var connstr = ConfigurationManager.AppSettings["simple"]; if(String.IsNullOrEmpty(connstr)) throw new ArgumentNullException("Connection string not found."); mongo = new Mongo(connstr); mongo.Connect(); simple = mongo["simple"]; categories = simple.GetCollection<Document>("categories"); Clean(); var names = new[] {"Bluez", "Jazz", "Classical", "Rock", "Oldies", "Heavy Metal"}; foreach(var name in names) categories.Insert(new Document {{"name", name}}); }
public void GivenIHaveNoProfileProperties() { using (var mongo = new Mongo()) { mongo.Connect(); IMongoDatabase db = mongo.GetDatabase("MetaProfiler"); IMongoCollection mongoCollection = db.GetCollection("ProfileProperties"); mongoCollection.Remove(new Document()); mongo.Disconnect(); } }
public void Connect2Mongo(string ip, string port, string database) { try { var connstr = @"Server=" + ip + ":" + port; //外网地址 //var connstr = @"Server=localhost:27017"; _gMongo = new Mongo(connstr); _gMongo.Connect(); _gTest = _gMongo[database]; } catch (Exception ex) { MessageBox.Show(ex.Message, "异常信息"); } }
static void FlushExpiredSession() { try { using (var mongo = new Mongo(config)) { mongo.Connect(); Document expiredSelector = new Document() { { "Expires", new Document() { { "$lt", DateTime.Now } } } }; mongo["session_store"]["sessions"].Delete(expiredSelector); } Console.WriteLine("Successfully flushed any expired sessions."); } catch (MongoException e) { Console.WriteLine("Error while flushing expired sessions: " + e.Message); } }
static void Main(string[] args) { WebClient wc = new WebClient(); string dane = wc.DownloadString("http://nbp.pl/kursy/xml/LastA.xml"); //sciagniety xml XmlSerializer serial = new XmlSerializer(typeof(TabelaKursow)); byte[] bajts = Encoding.UTF8.GetBytes(dane); TabelaKursow tk = serial.Deserialize(new MemoryStream(bajts)) as TabelaKursow; Mongo mg = new Mongo(); mg.Connect(); var db = mg.GetDatabase("waluty"); var collection = db.GetCollection<TabelaKursow>(); Console.WriteLine("Ilosc dokumentow: {0}", collection.Count()); collection.Insert(tk); }
/// <summary> /// 插入操作 /// </summary> /// <param name="person"></param> /// <returns></returns> public void Insert(T t) { using (MongoDB.Mongo mongo = new MongoDB.Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection <T>(collectionName); collection.Insert(t, true); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } }
/// <summary> /// 更新操作 /// </summary> /// <param name="person"></param> /// <returns></returns> public void Update(T t, Expression <Func <T, bool> > func) { using (MongoDB.Mongo mongo = new MongoDB.Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection <T>(collectionName); collection.Update <T>(t, func, true); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } }