public void TestAsRegexOptionS() { BsonValue v = new BsonRegularExpression("xyz", "s"); BsonValue s = ""; var r = v.AsRegex; Assert.AreEqual(RegexOptions.Singleline, r.Options); Assert.Throws<InvalidCastException>(() => { var x = s.AsRegex; }); }
public LogSearchResponse Get(LogSearchRequest request) { request = request ?? new LogSearchRequest(); IFindFluent<BsonDocument, BsonDocument> cursor; if (!request.IsEmpty) { List<FilterDefinition<BsonDocument>> queries = new List<FilterDefinition<BsonDocument>>(); if (!String.IsNullOrWhiteSpace(request.Query)) { var queryExpr = new BsonRegularExpression(new Regex(request.Query, RegexOptions.IgnoreCase)); queries.Add(Builders< BsonDocument>.Filter.Or( Builders< BsonDocument>.Filter.Regex(FieldNames.Message, queryExpr), Builders<BsonDocument>.Filter.Regex(FieldNames.Loggername, queryExpr) )); } if (!String.IsNullOrWhiteSpace(request.Level)) { var levels = request.Level.Split(',').Select(x => x.Trim()).ToArray(); queries.Add(Builders<BsonDocument>.Filter.In(FieldNames.Level, levels.Select(BsonValue.Create))); } cursor = Logs.Find(Builders<BsonDocument>.Filter.And(queries)); } else { cursor = Logs.Find(Builders<BsonDocument>.Filter.Empty); } var response = new LogSearchResponse { Items = cursor .Sort(Builders<BsonDocument>.Sort.Descending(FieldNames.Timestamp)) .Skip(request.LogsPerPage*(request.Page - 1)) .Limit(request.LogsPerPage) .ToList() .Select(x => x.ToDictionary()), Count = cursor.Count() }; return response; }
/// <summary> /// Mq消费者client status /// </summary> /// <param name="limit"></param> /// <param name="offset"></param> /// <param name="search"></param> /// <returns></returns> public ActionResult ConsumerInfo(int limit, int offset, string search = null) { var query = Query.Null; if (!string.IsNullOrEmpty(search)) { query = Query.Matches("ip", BsonRegularExpression.Create($"/{search}/")); } var total = dataOp.FindCount(MQConsumerInfo, query); var rows = new List <dynamic>(); if (total > 0) { var sortBy = new SortByDocument { { "isStart", -1 }, { "lastStartTime", -1 }, { "lastEndTime", -1 }, { "ip", 1 } }; var docs = dataOp.FindLimitByQuery(MQConsumerInfo, query, sortBy, offset, limit); foreach (var doc in docs) { var consumerId = doc.Int("consumerId"); var ip = doc.String("ip"); var queueType = doc.String("queueType"); var isStart = doc.Int("isStart"); if (isStart > 0) { SystemMonitorBll._().SetIp(ip); } var lastStartTime = doc.String("lastStartTime"); var lastEndTime = doc.String("lastEndTime"); var lastExecTime = doc.String("lastExecTime"); rows.Add(new { consumerId, ip, queueType, isStart, lastStartTime, lastEndTime, lastExecTime }); } } return(Json(new { total, rows }, JsonRequestBehavior.AllowGet)); }
private FilterDefinition <HotelBasic> GetFilters(FilterModel filter) { var builder = Builders <HotelBasic> .Filter; var filters = builder.Exists(x => x.name); if (!string.IsNullOrEmpty(filter.City)) { filters = builder.Regex(x => x.city, BsonRegularExpression.Create(new Regex(filter.City, RegexOptions.IgnoreCase))); } if (!string.IsNullOrEmpty(filter.State)) { filters = filters & builder.Regex(x => x.metroAreaName, BsonRegularExpression.Create(new Regex(filter.State, RegexOptions.IgnoreCase))); } if (filter.Guests != 0) { filters = filters & builder.Gt(x => x.totalSleepingRoom, filter.Guests / 2); } if (filter.MetricValue != 0) { filters = filters & builder.Gt(x => x.largestMeetingSpace.metricValue, filter.MetricValue); } filters = filters & builder.Where(x => x.DateDeleted == null); return(filters); }
public async Task <List <Product> > findProduct(string query) { List <Product> all = new List <Product>(); var builder = Builders <BsonDocument> .Filter; var pattern = new BsonRegularExpression(query, "i"); var emailFilter = builder.Regex("email", pattern); var nameFilter = builder.Regex("nom", pattern); var matriculeFilter = builder.Regex("matricule", new BsonRegularExpression(query, "i")); var combinedOr = builder.Or(matriculeFilter | emailFilter | nameFilter); var count = await getCollection("produits").Find(combinedOr).CountAsync(); Console.WriteLine(count); if (count >= 0) { var result = await getCollection("produits").Find(combinedOr).ToListAsync(); foreach (var doc in result) { all.Add(BsonSerializer.Deserialize <Product>(doc)); } return(all); } else { return(all); } }
private static AstFilter Translate(TranslationContext context, Expression inputExpression, Regex regex) { var inputFieldAst = ExpressionToFilterFieldTranslator.Translate(context, inputExpression); var regularExpression = new BsonRegularExpression(regex); return(AstFilter.Regex(inputFieldAst, regularExpression.Pattern, regularExpression.Options)); }
//public async Task<IEnumerable<Word>> GetWordsByField(string fieldName, string fieldValue) public async Task <IEnumerable <Word> > GetWordsByField(SearchField searchField, string fieldValue, SearchType searchType, string category) { try { var fieldName = Enum.GetName(typeof(SearchField), searchField); var regexExp = searchType == SearchType.Contains ? ".*{0}.*" : @"^{0}"; var regex = new BsonRegularExpression(string.Format(regexExp, fieldValue), "i"); Console.WriteLine(regex.ToString()); var filter = Builders <Word> .Filter.Regex(fieldName, regex); if (!string.IsNullOrEmpty(category)) { filter = Builders <Word> .Filter.Eq(w => w.Categories, category) & filter; } var result = await _context.Words.Find(filter).ToListAsync(); Console.WriteLine(result.Count); return(result); } catch (Exception ex) { throw ex; } }
public async Task DeleteByPrefixAsync(string prefix, CancellationToken ct = default) { var name = GetFileName(prefix, nameof(prefix)); try { var match = new BsonRegularExpression($"^{name}"); var fileQuery = await bucket.FindAsync(Filters.Regex(x => x.Id, match), cancellationToken : ct); await fileQuery.ForEachAsync(async file => { try { await bucket.DeleteAsync(file.Id, ct); } catch (GridFSFileNotFoundException) { return; } }, ct); } catch (GridFSFileNotFoundException) { return; } }
public async Task <List <User> > FilterUsers(string partialUserName) { var regex = new BsonRegularExpression($"{partialUserName}", "i"); var orOptions = new List <BsonDocument> { new BsonDocument { { "SamAccountName", regex } }, new BsonDocument { { "FirstName", regex } }, new BsonDocument { { "LastName", regex } } }; var query = new BsonDocument { { "$or", new BsonArray(orOptions) }, }; var results = await _userCacheDataRepository.FindAsync(query); // TODO: Need to add sort option, instead of this hack return(results.OrderBy(x => x.SamAccountName).ToList()); }
public async Task <IResultList <Subscription> > QueryAsync(string appId, SubscriptionQuery query, CancellationToken ct) { var filters = new List <FilterDefinition <MongoDbSubscription> > { Filter.Eq(x => x.AppId, appId) }; if (!string.IsNullOrWhiteSpace(query.UserId)) { filters.Add(Filter.Eq(x => x.UserId, query.UserId)); } if (!string.IsNullOrWhiteSpace(query.Query)) { var regex = new BsonRegularExpression(query.Query, "i"); filters.Add(Filter.Regex(x => x.TopicPrefix, regex)); } var filter = Filter.And(filters); var resultItems = await Collection.Find(filter).ToListAsync(query, ct); var resultTotal = (long)resultItems.Count; if (query.ShouldQueryTotal(resultItems)) { resultTotal = await Collection.Find(filter).CountDocumentsAsync(ct); } return(ResultList.Create(resultTotal, resultItems.Select(x => x.ToSubscription()))); }
public async Task <IResultList <Subscription> > QueryAsync(string appId, SubscriptionQuery query, CancellationToken ct = default) { var filters = new List <FilterDefinition <MongoDbSubscription> > { Filter.Eq(x => x.AppId, appId) }; if (!string.IsNullOrWhiteSpace(query.UserId)) { filters.Add(Filter.Eq(x => x.UserId, query.UserId)); } if (!string.IsNullOrWhiteSpace(query.Query)) { var regex = new BsonRegularExpression(query.Query, "i"); filters.Add(Filter.Regex(x => x.TopicPrefix, regex)); } var filter = Filter.And(filters); var taskForItems = Collection.Find(filter).ToListAsync(query, ct); var taskForCount = Collection.Find(filter).CountDocumentsAsync(ct); await Task.WhenAll( taskForItems, taskForCount); return(ResultList.Create(taskForCount.Result, taskForItems.Result.Select(x => x.ToSubscription()))); }
public List <Path> Find(string query) { // Если строка для поиска не указана или пуста - просто выводим объекты из коллекции. if (string.IsNullOrEmpty(query)) { return(Get()); } // Создаём регулярное вырашение для поиска в базе данных (для поиска без учёта ресстра символов). // Т.е. не важно, как искать "HeLLo" или "hello", результат должен быть схожим. // Используем функцию Regex.Escape(), // чтобы все символы были поисковой строкой (совпадение символов), // а не частью регулярного выражения. var caseInsensitiveRegExp = new BsonRegularExpression("/" + Regex.Escape(query) + "/i"); // Создаём фильтр поиска элементов по полям "name" и "keywords" var filter = // Объединяем 2 условия через "ИЛИ", т.е. или "name" должен содержать поисковую фразу или "keywords" Builders <Path> .Filter.Or( // Path должен содержать поисковую фразу в поле "name" Builders <Path> .Filter.Regex(path => path.Name, caseInsensitiveRegExp), // Или Path должен содержать поисковую фразу в поле "keywords" (массив слов) Builders <Path> .Filter.Regex(path => path.Keywords, caseInsensitiveRegExp) ); // Выполняем поиск элементов с условиями: // .Name содержит поисковую фразу (без учётра реестра) // или .Keywords содержит поисковую фразу (без учётра реестра) // и сохраняем результат в список элементов. return(_Paths.Find(filter).ToList()); }
public string[] GetLocation(string prefixText, int count) { List <string> lst = new List <string>(); MongoCollection <BasicInfo> objCollection = BaseClass.db.GetCollection <BasicInfo>("c_BasicInfo"); var query = Query.Matches("HomeTown", BsonRegularExpression.Create(new System.Text.RegularExpressions.Regex("^(?i)" + prefixText + ""))); var cursor = objCollection.Find(query); cursor.Limit = 5; System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; System.Globalization.TextInfo txtInfo = cultureInfo.TextInfo; foreach (var item in cursor) { lst.Add(txtInfo.ToTitleCase(item.HomeTown)); } /* var query2 = Query.Matches("HomeTown", BsonRegularExpression.Create(new System.Text.RegularExpressions.Regex("^(?i)" + prefixText + ""))); * * var cursor2 = objCollection.Find(query2); * cursor2.Limit = 5; * foreach (var item in cursor) * { * lst.Add(item.HomeTown); * * }*/ return(lst.Distinct().Take(5).ToArray()); }
public async Task <IEnumerable <ZipCodeEntity> > LookupZip(string zip) { var zipRegEx = new BsonRegularExpression($@"/^{Regex.Escape(zip)}$/i"); var zipFilter = Builders <ZipCodeEntity> .Filter.Regex(z => z.Code, zipRegEx); return(await Lookup(zipFilter)); }
private static FilterDefinition <MongoDbSubscription> BuildFilter(string appId, SubscriptionQuery query) { var filters = new List <FilterDefinition <MongoDbSubscription> > { Filter.Eq(x => x.AppId, appId) }; if (!string.IsNullOrWhiteSpace(query.UserId)) { filters.Add(Filter.Eq(x => x.UserId, query.UserId)); } if (query.Topics != null) { filters.Add(Filter.In(x => x.TopicPrefix, query.Topics)); } else if (!string.IsNullOrWhiteSpace(query.Query)) { var regex = new BsonRegularExpression(Regex.Escape(query.Query), "i"); filters.Add(Filter.Regex(x => x.TopicPrefix, regex)); } return(Filter.And(filters)); }
/// <summary> /// Busca uma lista de tecnologias que o nome seja parecido com o texto digitado /// </summary> /// <param name="name">texto a ser procurado</param> /// <returns></returns> public async Task <List <Techie> > SearchTechiesPerName(string name) { var filter = FilterBuilder.Regex(a => a.Name, BsonRegularExpression.Create(new Regex(name, RegexOptions.IgnoreCase))) & FilterBuilder.Exists(a => a.DeletedAt, false); return(await Collection.Find(filter).ToListAsync()); }
public async Task <Category> GetCategoryByName(string name) { var regex = new BsonRegularExpression($"/^{(name ?? string.Empty).Trim()}$/i"); var filter = Builders <Category> .Filter.Regex(_ => _.Name, regex); return(await Collection.Find(filter).FirstOrDefaultAsync().ConfigureAwait(false)); }
public void TestBsonRegularExpressionConstructors() { var regex = BsonRegularExpression.Create("pattern"); Assert.IsInstanceOf <BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("", regex.Options); regex = BsonRegularExpression.Create("/pattern/i"); Assert.IsInstanceOf <BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("i", regex.Options); regex = BsonRegularExpression.Create(@"/pattern\/withslash/i"); Assert.IsInstanceOf <BsonRegularExpression>(regex); Assert.AreEqual("pattern/withslash", regex.Pattern); Assert.AreEqual("i", regex.Options); regex = BsonRegularExpression.Create("pattern", "i"); Assert.IsInstanceOf <BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("i", regex.Options); regex = BsonRegularExpression.Create(new Regex("pattern")); Assert.IsInstanceOf <BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("", regex.Options); regex = BsonRegularExpression.Create(new Regex("pattern", RegexOptions.IgnoreCase)); Assert.IsInstanceOf <BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("i", regex.Options); }
public async Task <List <BsonDocument> > GetOrdersGroupByZone(int orderStatus, string serviceIdString) { try { var builder = Builders <Order> .Filter; var filter = builder.Eq(o => o.Status, orderStatus); if (!string.IsNullOrWhiteSpace(serviceIdString)) { var regexFilter = ".*" + serviceIdString + ".*"; var bsonRegex = new BsonRegularExpression(regexFilter, "i"); filter = builder.Eq(o => o.Status, orderStatus) & builder.Regex(x => x.ServiceId, bsonRegex); } var projectionDefinition = new BsonDocument { { "Zone", "$_id" }, { "Orders", "$Orders" }, { "Count", "$Count" }, { "Lat", "$Lat" }, { "Lon", "$Lon" }, { "_id", 0 } }; var result = await Collection.Aggregate().Match(filter).Group(new BsonDocument { { "_id", "$Zone" }, { "Orders", new BsonDocument("$push", new BsonDocument { { "Address", "$Address" }, { "Status", "$Status" }, { "Name", "$OrderBy.Name" }, { "PhoneNumber", "$OrderBy.PhoneNumber" }, { "Lat", "$Lat" }, { "Lon", "$Lon" }, { "ServiceId", "$ServiceId" } }) }, { "Count", new BsonDocument("$sum", 1) } }).Project <BsonDocument>(projectionDefinition).ToListAsync(); return(result); } catch (Exception ex) { throw new Exception("Error getting order by zone" + ex); } }
public void TestRegularExpressionStrict() { var tests = new TestData <BsonRegularExpression>[] { new TestData <BsonRegularExpression>(null, "null"), new TestData <BsonRegularExpression>(BsonRegularExpression.Create(""), "{ \"$regex\" : \"\", \"$options\" : \"\" }"), new TestData <BsonRegularExpression>(BsonRegularExpression.Create("a"), "{ \"$regex\" : \"a\", \"$options\" : \"\" }"), new TestData <BsonRegularExpression>(BsonRegularExpression.Create("a/b"), "{ \"$regex\" : \"a/b\", \"$options\" : \"\" }"), new TestData <BsonRegularExpression>(BsonRegularExpression.Create("a\\b"), "{ \"$regex\" : \"a\\\\b\", \"$options\" : \"\" }"), new TestData <BsonRegularExpression>(BsonRegularExpression.Create("a", "i"), "{ \"$regex\" : \"a\", \"$options\" : \"i\" }"), new TestData <BsonRegularExpression>(BsonRegularExpression.Create("a", "m"), "{ \"$regex\" : \"a\", \"$options\" : \"m\" }"), new TestData <BsonRegularExpression>(BsonRegularExpression.Create("a", "x"), "{ \"$regex\" : \"a\", \"$options\" : \"x\" }"), new TestData <BsonRegularExpression>(BsonRegularExpression.Create("a", "s"), "{ \"$regex\" : \"a\", \"$options\" : \"s\" }"), new TestData <BsonRegularExpression>(BsonRegularExpression.Create("a", "imxs"), "{ \"$regex\" : \"a\", \"$options\" : \"imxs\" }"), }; var jsonSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; foreach (var test in tests) { var json = test.Value.ToJson(jsonSettings); Assert.AreEqual(test.Expected, json); Assert.AreEqual(test.Value, BsonSerializer.Deserialize <BsonRegularExpression>(json)); } }
public async Task <IResultList <Event> > QueryAsync(string appId, EventQuery query, CancellationToken ct) { var filters = new List <FilterDefinition <MongoDbEvent> > { Filter.Eq(x => x.Doc.AppId, appId) }; if (!string.IsNullOrWhiteSpace(query.Query)) { var regex = new BsonRegularExpression(query.Query, "i"); filters.Add( Filter.Or( Filter.Regex(x => x.Doc.Topic, regex), Filter.Regex(x => x.SearchText, regex))); } var filter = Filter.And(filters); var resultItems = await Collection.Find(filter).SortByDescending(x => x.Doc.Created).ToListAsync(query, ct); var resultTotal = (long)resultItems.Count; if (query.ShouldQueryTotal(resultItems)) { resultTotal = await Collection.Find(filter).CountDocumentsAsync(ct); } return(ResultList.Create(resultTotal, resultItems.Select(x => x.ToEvent()))); }
/////////////////////////////////////////////////////////////// // SELECT All DATA ////////////////////////////////////////////////////////////// public static List <User> SearchUserbyWorkSpace(string WorkSpace) { List <User> lst = new List <User>(); MongoCollection <Employer> objCollection = db.GetCollection <Employer>("c_Employer"); var query = Query.Matches("Organization", BsonRegularExpression.Create(new System.Text.RegularExpressions.Regex("^(?i)" + WorkSpace + ""))); foreach (Employer item in objCollection.Find(query)) { MongoCollection <User> objUserCollection = db.GetCollection <User>("c_User"); UserBO objClass = new UserBO(); foreach (User Useritem in objUserCollection.Find(Query.EQ("_id", item.UserId))) { lst.Add(Useritem); break; } } return(lst.ToList()); }
/// <summary> /// Writes a BSON regular expression to the writer. /// </summary> /// <param name="regex">A BsonRegularExpression.</param> public override void WriteRegularExpression(BsonRegularExpression regex) { if (Disposed) { throw new ObjectDisposedException("JsonWriter"); } if (State != BsonWriterState.Value && State != BsonWriterState.Initial) { ThrowInvalidState("WriteRegularExpression", BsonWriterState.Value, BsonWriterState.Initial); } var pattern = regex.Pattern; var options = regex.Options; WriteNameHelper(Name); switch (_jsonWriterSettings.OutputMode) { case JsonOutputMode.Strict: _textWriter.Write("{{ \"$regex\" : \"{0}\", \"$options\" : \"{1}\" }}", EscapedString(pattern), EscapedString(options)); break; case JsonOutputMode.Shell: default: var escapedPattern = (pattern == "") ? "(?:)" : pattern.Replace("/", @"\/"); _textWriter.Write("/{0}/{1}", escapedPattern, options); break; } State = GetNextState(); }
/////////////////////////////////////////////////////////////// // SELECT All DATA ////////////////////////////////////////////////////////////// public static List <User> SearchUserbyEducation(string Education, int year) { List <User> lst = new List <User>(); MongoCollection <University> objCollection = db.GetCollection <University>("c_University"); var query = Query.Or( Query.Matches("UniversityName", BsonRegularExpression.Create(new System.Text.RegularExpressions.Regex("^(?i)" + Education + ""))), Query.EQ("ClassYear", year)); foreach (University item in objCollection.Find(query)) { MongoCollection <User> objUserCollection = db.GetCollection <User>("c_User"); UserBO objClass = new UserBO(); foreach (User Useritem in objUserCollection.Find(Query.EQ("_id", item.UserId))) { lst.Add(Useritem); break; } } return(lst.ToList()); }
/////////////////////////////////////////////////////////////// // SELECT All DATA ////////////////////////////////////////////////////////////// public static List <User> SearchUserList(string Name, string userid) { List <User> lst = new List <User>(); MongoCollection <User> objCollection = db.GetCollection <User>("c_User"); string[] words = Name.Split(' '); foreach (string word in words) { var query = Query.Or( Query.Matches("FirstName", BsonRegularExpression.Create(new System.Text.RegularExpressions.Regex("^(?i)" + word + ""))), Query.Matches("LastName", BsonRegularExpression.Create(new System.Text.RegularExpressions.Regex("^(?i)" + word + ""))), Query.Matches("Email", BsonRegularExpression.Create(new System.Text.RegularExpressions.Regex("^(?i)" + Name + "")))); var query2 = Query.And(query, Query.NE("_id", ObjectId.Parse(userid))); foreach (User item in objCollection.Find(query2).Distinct()) { lst.Add(item); } } return(lst.Distinct().ToList()); }
public async Task <IResultList <User> > QueryAsync(string appId, UserQuery query, CancellationToken ct) { var filters = new List <FilterDefinition <MongoDbUser> > { Filter.Eq(x => x.Doc.AppId, appId) }; if (!string.IsNullOrWhiteSpace(query.Query)) { var regex = new BsonRegularExpression(query.Query, "i"); filters.Add( Filter.Or( Filter.Regex(x => x.Doc.Id, regex), Filter.Regex(x => x.Doc.FullName, regex), Filter.Regex(x => x.Doc.EmailAddress, regex))); } var filter = Filter.And(filters); var taskForItems = Collection.Find(filter).ToListAsync(query, ct); var taskForCount = Collection.Find(filter).CountDocumentsAsync(ct); await Task.WhenAll( taskForItems, taskForCount); return(ResultList.Create(taskForCount.Result, taskForItems.Result.Select(x => x.ToUser()))); }
public async Task <List <Order> > GetOrdersByZone(string zone, int orderStatus, string serviceIdString) { try { var builder = Builders <Order> .Filter; var filter = builder.Eq(order => order.Zone, zone) & builder.Eq(order => order.Status, orderStatus); if (!string.IsNullOrWhiteSpace(serviceIdString)) { var regexFilter = ".*" + serviceIdString + ".*"; var bsonRegex = new BsonRegularExpression(regexFilter, "i"); filter = builder.Eq(order => order.Zone, zone) & builder.Eq(order => order.Status, orderStatus) & builder.Regex(x => x.ServiceId, bsonRegex); } var projection = Builders <Order> .Projection.Exclude("_id") .Include(u => u.ServiceId) .Include(u => u.Address) .Include(u => u.OrderBy) .Include(u => u.Status) .Include(u => u.Lat) .Include(u => u.Lon); var result = await Collection.Find(filter).Project <Order>(projection).ToListAsync(); return(result); } catch (Exception ex) { throw new Exception("Error getting orders" + ex); } }
/// <summary> /// Adds a regular expression test to the query. /// </summary> /// <param name="name">The name of the element to test.</param> /// <param name="regex">The regular expression to match against.</param> /// <returns>A query.</returns> public static QueryComplete Matches( string name, BsonRegularExpression regex ) { return(new QueryComplete(new BsonDocument(name, regex))); }
public async Task <IResultList <Topic> > QueryAsync(string appId, TopicQuery query, CancellationToken ct) { var filters = new List <FilterDefinition <MongoDbTopic> > { Filter.Eq(x => x.Doc.AppId, appId) }; if (!string.IsNullOrWhiteSpace(query.Query)) { var regex = new BsonRegularExpression(query.Query, "i"); filters.Add(Filter.Regex(x => x.Doc.Path, regex)); } var filter = Filter.And(filters); var taskForItems = Collection.Find(filter).SortByDescending(x => x.Doc.LastUpdate).ToListAsync(query, ct); var taskForCount = Collection.Find(filter).CountDocumentsAsync(ct); await Task.WhenAll( taskForItems, taskForCount); return(ResultList.Create(taskForCount.Result, taskForItems.Result.Select(x => x.Doc))); }
public static Domain.PhysicianCollection GetPhysiciansByName(string firstName, string lastName) { YellowstonePathology.Business.Domain.PhysicianCollection result = new YellowstonePathology.Business.Domain.PhysicianCollection(); YellowstonePathology.Business.Mongo.Server server = new Business.Mongo.TestServer(YellowstonePathology.Business.Mongo.MongoTestServer.LISDatabaseName); MongoCollection collection = server.Database.GetCollection <BsonDocument>("Physician"); MongoCursor cursor = null; if (string.IsNullOrEmpty(firstName) == false) { cursor = collection.FindAs <BsonDocument>(Query.And(Query.Matches("LastName", BsonRegularExpression.Create("^" + lastName + ".*", "i")), Query.Matches("FirstName", BsonRegularExpression.Create("^" + firstName + ".*", "i")))).SetSortOrder(SortBy.Ascending("LastName", "FirstName")); } else { cursor = collection.FindAs <BsonDocument>(Query.Matches("LastName", BsonRegularExpression.Create("^" + lastName + ".*", "i"))).SetSortOrder(SortBy.Ascending("LastName", "FirstName")); } foreach (BsonDocument bsonDocument in cursor) { YellowstonePathology.Business.Domain.Physician physician = new YellowstonePathology.Business.Domain.Physician(); YellowstonePathology.Business.Mongo.BSONPropertyWriter.Write(bsonDocument, physician); result.Add(physician); } return(result); }
private FilterDefinition <Campaign> GetFilter(string term) { return(string.IsNullOrWhiteSpace(term) ? Builders <Campaign> .Filter.Empty : Builders <Campaign> .Filter.Regex("Name", BsonRegularExpression.Create(new Regex(term, RegexOptions.IgnoreCase)))); }
/////////////////////////////////////////////////////////////// // SELECT All DATA ////////////////////////////////////////////////////////////// public static List <User> SearchUserbyLocation(string Location) { List <User> lst = new List <User>(); MongoCollection <BasicInfo> objCollection = db.GetCollection <BasicInfo>("c_BasicInfo"); var query = Query.Matches("CurrentCity", BsonRegularExpression.Create(new System.Text.RegularExpressions.Regex("^(?i)" + Location + ""))); foreach (BasicInfo item in objCollection.Find(query)) { MongoCollection <User> objUserCollection = db.GetCollection <User>("c_User"); UserBO objClass = new UserBO(); foreach (User Useritem in objUserCollection.Find(Query.EQ("_id", item.UserId))) { lst.Add(Useritem); break; } } return(lst.ToList()); }
/// <summary> /// finds all files /// </summary> /// <param name="startsWithPath"></param> /// <param name="includeTempFiles"></param> /// <param name="skip"></param> /// <param name="limit"></param> /// <returns></returns> public List<IStorageFile> FindAll(string startsWithPath = null, bool includeTempFiles = false, int? skip = null, int? limit = null) { //all filepaths are lowercase and all starts with folder separator if (!string.IsNullOrWhiteSpace(startsWithPath)) { startsWithPath = startsWithPath.ToLowerInvariant(); if (!startsWithPath.StartsWith(FOLDER_SEPARATOR)) startsWithPath = FOLDER_SEPARATOR + startsWithPath; } List<IMongoQuery> queries = new List<IMongoQuery>(); if (!includeTempFiles) { IMongoQuery tmpFolderQuery = Query.Matches("filename", new BsonRegularExpression("^(/" + TMP_FOLDER_NAME + "/)", "i")); IMongoQuery tmpFolderExclideQuery = Query.Not(tmpFolderQuery); queries.Add(tmpFolderExclideQuery); } if (!string.IsNullOrWhiteSpace(startsWithPath)) { //TODO change to starts with - now is contains var regex = new BsonRegularExpression(string.Format(".*{0}.*", startsWithPath), "i"); queries.Add(Query.Matches("filename", regex)); } IMongoQuery finalQuery = queries.Count > 0 ? Query.And(queries) : Query.Null; var cursor = gfs.Find(finalQuery); if (skip.HasValue) cursor.SetSkip(skip.Value); if (limit.HasValue) cursor.SetLimit(limit.Value); IEnumerable<MongoGridFSFileInfo> files = cursor.ToList(); return cursor.AsQueryable().Select(f => (IStorageFile)(new MongoStorageFile(f))).ToList(); }
/// <summary> /// Display all the files /// </summary> public ActionResult Files(string search) { var mongo = MongoServer.Create(MongoConnectionString); var db = mongo.GetDatabase(MongoDatabase); var gfs = db.GridFS; var files = new List<MongoGridFSFileInfo>(); if (! string.IsNullOrEmpty(search)) { var regex = new BsonRegularExpression(string.Format(".*{0}.*", search), "i"); files = gfs.Find( Query.Or( Query.Matches("metadata.title", regex), Query.Matches("filename", regex))) .ToList(); } else { files = gfs.FindAll().ToList(); } mongo.Disconnect(); return View(files); }
public void TestAsBsonRegularExpression() { BsonValue v = new BsonRegularExpression("pattern", "options"); BsonValue s = ""; var r = v.AsBsonRegularExpression; Assert.AreEqual("pattern", r.Pattern); Assert.AreEqual("options", r.Options); Assert.Throws<InvalidCastException>(() => { var x = s.AsBsonRegularExpression; }); }
public void WriteRegularExpression(string pattern, string options) { var regex = new BsonRegularExpression(pattern, options); WriteRegularExpression(regex); }
public void WriteRegularExpression_should_have_expected_result() { var subject = CreateSubject(); var value = new BsonRegularExpression("abc", "i"); WriteNested(subject, () => subject.WriteRegularExpression(value)); AssertBsonEquals(subject, "{ x : /abc/i }"); }
public void TestBsonRegularExpressionConstructors() { var regex = new BsonRegularExpression("pattern"); Assert.IsInstanceOf<BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("", regex.Options); regex = new BsonRegularExpression("/pattern/i"); Assert.IsInstanceOf<BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("i", regex.Options); regex = new BsonRegularExpression(@"/pattern\/withslash/i"); Assert.IsInstanceOf<BsonRegularExpression>(regex); Assert.AreEqual("pattern/withslash", regex.Pattern); Assert.AreEqual("i", regex.Options); regex = new BsonRegularExpression("pattern", "i"); Assert.IsInstanceOf<BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("i", regex.Options); regex = new BsonRegularExpression(new Regex("pattern")); Assert.IsInstanceOf<BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("", regex.Options); regex = new BsonRegularExpression(new Regex("pattern", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline)); Assert.IsInstanceOf<BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("imxs", regex.Options); regex = new BsonRegularExpression(new Regex("pattern", RegexOptions.IgnoreCase)); Assert.IsInstanceOf<BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("i", regex.Options); regex = new BsonRegularExpression(new Regex("pattern", RegexOptions.Multiline)); Assert.IsInstanceOf<BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("m", regex.Options); regex = new BsonRegularExpression(new Regex("pattern", RegexOptions.IgnorePatternWhitespace)); Assert.IsInstanceOf<BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("x", regex.Options); regex = new BsonRegularExpression(new Regex("pattern", RegexOptions.Singleline)); Assert.IsInstanceOf<BsonRegularExpression>(regex); Assert.AreEqual("pattern", regex.Pattern); Assert.AreEqual("s", regex.Options); }
private IMongoQuery BuildStringQuery(MethodCallExpression methodCallExpression) { if (methodCallExpression.Method.DeclaringType == typeof(string)) { switch (methodCallExpression.Method.Name) { case "Contains": case "EndsWith": case "StartsWith": var arguments = methodCallExpression.Arguments.ToArray(); if (arguments.Length == 1) { var serializationInfo = GetSerializationInfo(methodCallExpression.Object); var valueExpression = arguments[0] as ConstantExpression; if (serializationInfo != null && valueExpression != null) { var s = (string)valueExpression.Value; BsonRegularExpression regex; switch (methodCallExpression.Method.Name) { case "Contains": regex = new BsonRegularExpression(s); break; case "EndsWith": regex = new BsonRegularExpression(s + "$"); break; case "StartsWith": regex = new BsonRegularExpression("^" + s); break; default: throw new InvalidOperationException("Unreachable code"); } return Query.Matches(serializationInfo.ElementName, regex); } } break; } } return null; }
// constructors /// <summary> /// Initializes a new instance of the RegularExpressionJsonToken class. /// </summary> /// <param name="lexeme">The lexeme.</param> /// <param name="value">The BsonRegularExpression value.</param> public RegularExpressionJsonToken(string lexeme, BsonRegularExpression value) : base(JsonTokenType.RegularExpression, lexeme) { this.value = value; }
internal static kUser GetUserByName(string name) { var regex = new BsonRegularExpression(new Regex("^" + name + "$", RegexOptions.IgnoreCase)); var query = Query<kUser>.Matches(u => u.Name, regex); return Db.GetCollection<kUser>("users").FindOne(query); }
/// <summary> /// Writes a BSON regular expression to the writer. /// </summary> /// <param name="regex">A BsonRegularExpression.</param> public override void WriteRegularExpression(BsonRegularExpression regex) { if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); } if (State != BsonWriterState.Value) { ThrowInvalidState("WriteRegularExpression", BsonWriterState.Value); } _buffer.WriteByte((byte)BsonType.RegularExpression); WriteNameHelper(); _buffer.WriteCString(_binaryWriterSettings.Encoding, regex.Pattern); _buffer.WriteCString(_binaryWriterSettings.Encoding, regex.Options); State = GetNextState(); }
private static JsonToken GetRegularExpressionToken(JsonBuffer buffer) { // opening slash has already been read var start = buffer.Position - 1; var state = RegularExpressionState.InPattern; while (true) { var c = buffer.Read(); switch (state) { case RegularExpressionState.InPattern: switch (c) { case '/': state = RegularExpressionState.InOptions; break; case '\\': state = RegularExpressionState.InEscapeSequence; break; default: state = RegularExpressionState.InPattern; break; } break; case RegularExpressionState.InEscapeSequence: state = RegularExpressionState.InPattern; break; case RegularExpressionState.InOptions: switch (c) { case 'i': case 'm': case 'x': case 's': state = RegularExpressionState.InOptions; break; case ',': case '}': case ']': case ')': case -1: state = RegularExpressionState.Done; break; default: if (char.IsWhiteSpace((char)c)) { state = RegularExpressionState.Done; } else { state = RegularExpressionState.Invalid; } break; } break; } switch (state) { case RegularExpressionState.Done: buffer.UnRead(c); var lexeme = buffer.Substring(start, buffer.Position - start); var regex = new BsonRegularExpression(lexeme); return new RegularExpressionJsonToken(lexeme, regex); case RegularExpressionState.Invalid: throw new FileFormatException(FormatMessage("Invalid JSON regular expression", buffer, start)); } } }
public void TestAsRegexOptionX() { BsonValue v = new BsonRegularExpression("xyz", "x"); BsonValue s = ""; var r = v.AsRegex; Assert.AreEqual(RegexOptions.IgnorePatternWhitespace, r.Options); Assert.Throws<InvalidCastException>(() => { var x = s.AsRegex; }); }
public TestClass( BsonRegularExpression value ) { this.B = value; this.V = value; }
private void GetSession(int sessionId) { // Get the database instance of mongo var AuctionVehicles = ConnectToMongo(); // Get mongo Collection of documents, return them as a type of pre-made object (auction vehicle) // param that is passed in is the string for the collection name (Vehicles) var collection = AuctionVehicles.GetCollection<AuctionVehicle>("vehicles"); /// /// This searches for the searchsession 181 /// var query = new QueryDocument("_searchSession", 181); /// /// This one gets all var cursor = collection.FindAllAs<AuctionVehicle>(); /// /// This one gets one from using the above query. /// // var cursor = collection.Find(query); // Set returned cursor's sort params (sort by search session id decending). cursor.SetSortOrder(SortBy.Descending("_searchSession")); // Set limit of returned documents. cursor.SetLimit(1); // Convert the cursort to a list so can enumerate. var list = cursor.ToList(); // Get the latest search session (first session in the list) int latestSession = list[0]._searchSession; // this one works for ANDS var biggerQuery = Query.And( Query.EQ("make", "TOYOTA"), Query.EQ("model", "HIACE VAN") ); // This one works for ORs var queryOr = Query.Or( Query.EQ("model", "SAFARI"), Query.EQ("model", "ASTRO"), Query.EQ("model", "CHEVYVAN") ); // Create regex for mongo wildcard search var regex = new BsonRegularExpression("/.*" + "USS Nagoya" + "*/"); // This one works for ands and regex // This is my favourite way to query. each one is an And and finally a regex to do wildcard text search - remember the bsonregularexpression. var biggerQueryDocumentStyle = new QueryDocument() { {"make", "TOYOTA"}, {"model", "HIACE VAN"}, {"htmlData.htmlRow", regex} }; var cursor3 = collection.Find(biggerQueryDocumentStyle); var cursor2 = collection.Find(biggerQuery); var cursor3list = cursor3.ToList(); var cursor2list = cursor2.ToList(); /* foreach (var item in cursor2list) { Console.WriteLine(item.make + " " + item.model + " " + "Session ID = " + item._searchSession); Console.ReadLine(); } foreach (var item in cursor3list) { Console.WriteLine(item.make + " " + item.model + " " + "Session ID = " + item._searchSession); Console.ReadLine(); } /* * foreach (var item in list) { Console.WriteLine(item.make + " " + item.model + " " + "Session ID = " + item._searchSession); Console.ReadLine(); } */ }
/// <summary> /// Tests that the value of the named element matches a regular expression (see $regex). /// </summary> /// <param name="regex">The regular expression to match against.</param> /// <returns>A query.</returns> public QueryComplete Matches(BsonRegularExpression regex) { return new QueryComplete(new BsonDocument(_name, new BsonDocument("$not", regex))); }
public void TestAsRegexOptionAll() { BsonValue v = new BsonRegularExpression("xyz", "imxs"); BsonValue s = ""; var r = v.AsRegex; Assert.AreEqual(RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline, r.Options); Assert.Throws<InvalidCastException>(() => { var x = s.AsRegex; }); }
/// <summary> /// Tests that the value of the named element matches a regular expression (see $regex). /// </summary> /// <param name="name">The name of the element to test.</param> /// <param name="regex">The regular expression to match against.</param> /// <returns>A query.</returns> public static QueryComplete Matches(string name, BsonRegularExpression regex) { return new QueryComplete(new BsonDocument(name, regex)); }
private IMongoQuery BuildStringCaseInsensitiveComparisonQuery(Expression variableExpression, ExpressionType operatorType, ConstantExpression constantExpression) { var methodExpression = variableExpression as MethodCallExpression; if (methodExpression == null) { return null; } var methodName = methodExpression.Method.Name; if ((methodName != "ToLower" && methodName != "ToUpper" && methodName != "ToLowerInvariant" && methodName != "ToUpperInvariant") || methodExpression.Object == null || methodExpression.Type != typeof(string) || methodExpression.Arguments.Count != 0) { return null; } if (operatorType != ExpressionType.Equal && operatorType != ExpressionType.NotEqual) { return null; } var serializationInfo = _serializationInfoHelper.GetSerializationInfo(methodExpression.Object); var serializedValue = _serializationInfoHelper.SerializeValue(serializationInfo, constantExpression.Value); if (serializedValue.IsString) { var stringValue = serializedValue.AsString; var stringValueCaseMatches = methodName == "ToLower" && stringValue == stringValue.ToLower(CultureInfo.InvariantCulture) || methodName == "ToLowerInvariant" && stringValue == stringValue.ToLower(CultureInfo.InvariantCulture) || methodName == "ToUpper" && stringValue == stringValue.ToUpper(CultureInfo.InvariantCulture) || methodName == "ToUpperInvariant" && stringValue == stringValue.ToUpper(CultureInfo.InvariantCulture); if (stringValueCaseMatches) { string pattern = "/^" + Regex.Escape(stringValue) + "$/i"; var regex = new BsonRegularExpression(pattern); if (operatorType == ExpressionType.Equal) { return Query.Matches(serializationInfo.ElementName, regex); } else { return Query.Not(Query.Matches(serializationInfo.ElementName, regex)); } } else { if (operatorType == ExpressionType.Equal) { // == "mismatched case" matches no documents return BuildBooleanQuery(false); } else { // != "mismatched case" matches all documents return BuildBooleanQuery(true); } } } else if (serializedValue.IsBsonNull) { if (operatorType == ExpressionType.Equal) { return Query.EQ(serializationInfo.ElementName, BsonNull.Value); } else { return Query.NE(serializationInfo.ElementName, BsonNull.Value); } } else { var message = string.Format("When using {0} in a LINQ string comparison the value being compared to must serialize as a string.", methodName); throw new ArgumentException(message); } }
public void TestBsonRegularExpressionEquals() { BsonRegularExpression lhs = new BsonRegularExpression("pattern", "options"); BsonRegularExpression rhs = new BsonRegularExpression("pattern", "options"); Assert.NotSame(lhs, rhs); Assert.Equal(lhs, rhs); Assert.Equal(lhs.GetHashCode(), rhs.GetHashCode()); }
public void TestBsonRegularExpression() { var value = new BsonRegularExpression("pattern", "imxs"); Assert.AreSame(value, ((IConvertible)value).ToType(typeof(object), null)); Assert.Throws<InvalidCastException>(() => Convert.ToBoolean(value)); Assert.Throws<InvalidCastException>(() => Convert.ToByte(value)); Assert.Throws<InvalidCastException>(() => Convert.ToChar(value)); Assert.Throws<InvalidCastException>(() => Convert.ToDateTime(value)); Assert.Throws<InvalidCastException>(() => Convert.ToDecimal(value)); Assert.Throws<InvalidCastException>(() => Convert.ToDouble(value)); Assert.Throws<InvalidCastException>(() => Convert.ToInt16(value)); Assert.Throws<InvalidCastException>(() => Convert.ToInt32(value)); Assert.Throws<InvalidCastException>(() => Convert.ToInt64(value)); Assert.Throws<InvalidCastException>(() => Convert.ToSByte(value)); Assert.Throws<InvalidCastException>(() => Convert.ToSingle(value)); Assert.Throws<InvalidCastException>(() => Convert.ToString(value)); Assert.Throws<InvalidCastException>(() => Convert.ToUInt16(value)); Assert.Throws<InvalidCastException>(() => Convert.ToUInt32(value)); Assert.Throws<InvalidCastException>(() => Convert.ToUInt64(value)); }
/// <summary> /// Writes a BSON regular expression to the writer. /// </summary> /// <param name="regex">A BsonRegularExpression.</param> public override void WriteRegularExpression(BsonRegularExpression regex) { if (Disposed) { throw new ObjectDisposedException("BsonDocumentWriter"); } if (State != BsonWriterState.Value) { ThrowInvalidState("WriteRegularExpression", BsonWriterState.Value); } WriteValue(regex); State = GetNextState(); }
/// <summary> /// Writes a BSON regular expression to the writer. /// </summary> /// <param name="regex">A BsonRegularExpression.</param> public abstract void WriteRegularExpression(BsonRegularExpression regex);
public void TestAsRegexOptionI() { BsonValue v = new BsonRegularExpression("xyz", "i"); BsonValue s = ""; var r = v.AsRegex; Assert.Equal(RegexOptions.IgnoreCase, r.Options); Assert.Throws<InvalidCastException>(() => { var x = s.AsRegex; }); }
/// <summary> /// Writes a BSON regular expression element to the writer. /// </summary> /// <param name="name">The name of the element.</param> /// <param name="regex">A BsonRegularExpression.</param> public void WriteRegularExpression(string name, BsonRegularExpression regex) { WriteName(name); WriteRegularExpression(regex); }
public void WriteRegularExpression(BsonRegularExpression value) { SetWriteState(Newtonsoft.Json.JsonToken.Undefined, null); _wrappedWriter.WriteRegularExpression(value); }
public void TestBsonRegularExpressionEquals() { var a = new BsonRegularExpression("pattern 1", "options 1"); var b = new BsonRegularExpression("pattern 1", "options 1"); var c = new BsonRegularExpression("pattern 2", "options 1"); var d = new BsonRegularExpression("pattern 2", "options 2"); var n = (BsonJavaScript)null; Assert.IsTrue(object.Equals(a, b)); Assert.IsFalse(object.Equals(a, c)); Assert.IsFalse(object.Equals(a, d)); Assert.IsFalse(object.Equals(c, d)); Assert.IsFalse(object.Equals(a, BsonNull.Value)); Assert.IsFalse(a.Equals(n)); Assert.IsFalse(a.Equals(null)); Assert.IsTrue(a == b); Assert.IsFalse(a == c); Assert.IsFalse(b == d); Assert.IsFalse(c == d); Assert.IsFalse(a == BsonNull.Value); Assert.IsFalse(a == null); Assert.IsFalse(null == a); Assert.IsTrue(n == null); Assert.IsTrue(null == n); Assert.IsFalse(a != b); Assert.IsTrue(a != c); Assert.IsTrue(b != d); Assert.IsTrue(c != d); Assert.IsTrue(a != BsonNull.Value); Assert.IsTrue(a != null); Assert.IsTrue(null != a); Assert.IsFalse(n != null); Assert.IsFalse(null != n); }
public void TestMapBsonRegularExpression() { var value = new BsonRegularExpression("pattern", "options"); var bsonValue = (BsonRegularExpression) BsonTypeMapper.MapToBsonValue(value); Assert.AreSame(value, bsonValue); var bsonRegularExpression = (BsonRegularExpression) BsonTypeMapper.MapToBsonValue(value, BsonType.RegularExpression); Assert.AreSame(value, bsonRegularExpression); }