public async Task InsertAccess(IEnumerable<Access> toAdd) { if (toAdd != null) { var filter = new BsonDocument(); var projection = Builders<Access>.Projection.Include("level"); var findOptions = new FindOptions<Access>() { Projection = projection }; var allLevels = this.Database.GetCollection<Access>("accesses") .FindAsync(filter, findOptions) .Result.ToListAsync().Result; //removing all the elements from toAdd that have a level already from the datavase toAdd = toAdd.Where(x => allLevels.Where(y => y.level == x.level) .Count() == 0) .Select(x => x).ToList(); if (toAdd.Count() > 0) { //only if there are enough records to be sent to the database var insertTask = this.Database.GetCollection<Access>("accesses").InsertManyAsync(toAdd); //this is where you can go ahead and do all the slave thread work await insertTask; //end of database task return; } else { return; } } else { return; } }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); string filePath = dataDir+ "TestBook.xlsx"; Workbook workbook = new Workbook(filePath); Worksheet worksheet = workbook.Worksheets[0]; //Access the style of cell A1 Style style = worksheet.Cells["A1"].GetStyle(); //Specify the style for searching FindOptions options = new FindOptions(); options.Style = style; Cell nextCell = null; do { //Find the cell that has a style of cell A1 nextCell = worksheet.Cells.Find(null, nextCell, options); if (nextCell == null) break; //Change the text of the cell nextCell.PutValue("Found"); } while (true); workbook.Save(dataDir+ "output.xlsx"); }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); string filePath = dataDir+ "TestBook.xlsx"; Workbook workbook = new Workbook(filePath); Worksheet worksheet = workbook.Worksheets[0]; //Access the style of cell A1 Style style = worksheet.Cells["A1"].GetStyle(); //Specify the style for searching FindOptions options = new FindOptions(); options.Style = style; Cell nextCell = null; do { //Find the cell that has a style of cell A1 nextCell = worksheet.Cells.Find(null, nextCell, options); if (nextCell == null) break; //Change the text of the cell nextCell.PutValue("Found"); } while (true); workbook.Save(dataDir+ "output.out.xlsx"); }
private static void findNow(Worksheet objSheet, string textToFind) { //Get Cells collection Cells cells = objSheet.Cells; //Instantiate FindOptions Object FindOptions findOptions = new FindOptions(); //Create a Cells Area CellArea ca = new CellArea(); ca.StartRow = 8; ca.StartColumn = 2; ca.EndRow = 17; ca.EndColumn = 13; //Set cells area for find options findOptions.SetRange(ca); //Set searching properties findOptions.SearchNext = true; findOptions.SeachOrderByRows = true; findOptions.LookInType = LookInType.Values; //Find the cell with 0 value Cell cell = cells.Find(textToFind, null, findOptions); Console.WriteLine(cell.StringValue); }
private void BTN_Replace_Click(object sender, EventArgs e) { if (TXBX_Find.Text != "" && TXBX_Replace.Text!="") { workbook = new Workbook(FOD_OpenFile.FileName); FindOptions Opts = new FindOptions(); Opts.LookInType = LookInType.Values; Opts.LookAtType = LookAtType.Contains; string found = ""; Cell cell = null; foreach (Worksheet sheet in workbook.Worksheets) { do { cell = sheet.Cells.Find(TXBX_Find.Text, cell, Opts); if (cell != null) { string celltext = cell.Value.ToString(); celltext = celltext.Replace(TXBX_Find.Text, TXBX_Replace.Text); cell.PutValue(celltext); } } while (cell != null); } LBL_FindResults.Text = "Replaced All Existing Values, Save the file now"; } }
public ContentResult Count(FindOptions findOptions) { int count = Finder.QueryCount(new CountOptions(findOptions.QueryName) { FilterOptions = findOptions.FilterOptions }); return this.Content(count.ToString()); }
public static MvcHtmlString SearchControl(this HtmlHelper helper, UserQueryEntity userQuery, FindOptions findOptions, Context context, Action<SearchControl> searchControl = null) { if (findOptions == null) throw new ArgumentNullException("findOptions"); findOptions.ApplyUserQuery(userQuery); return helper.SearchControl(findOptions, context, searchControl); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Instantiate the workbook object Workbook workbook = new Workbook(dataDir + "book1.xls"); // Get Cells collection Cells cells = workbook.Worksheets[0].Cells; FindOptions opts = new FindOptions(); opts.LookInType = LookInType.Values; opts.LookAtType = LookAtType.EntireContent; // Find the cell with the input integer or double Cell cell1 = cells.Find(205, null, opts); if (cell1 != null) { Console.WriteLine("Name of the cell containing the value: " + cell1.Name); } else { Console.WriteLine("Record not found "); } // Find the cell with the input string Aspose.Cells.Cell cell2 = cells.Find("Items A", null, opts); if (cell2 != null) { Console.WriteLine("Name of the cell containing the value: " + cell2.Name); } else { Console.WriteLine("Record not found "); } // Find the cell containing with the input string opts.LookAtType = LookAtType.Contains; Cell cell3 = cells.Find("Data", null, opts); if (cell3 != null) { Console.WriteLine("Name of the cell containing the value: " + cell3.Name); } else { Console.WriteLine("Record not found "); } // ExEnd:1 }
private IFindFluent<Person, Person> CreateSubject() { var settings = new MongoCollectionSettings(); _collection = Substitute.For<IMongoCollection<Person>>(); _collection.DocumentSerializer.Returns(BsonSerializer.SerializerRegistry.GetSerializer<Person>()); _collection.Settings.Returns(settings); var options = new FindOptions<Person, Person>(); var subject = new FindFluent<Person, Person>(_collection, new BsonDocument(), options); return subject; }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Instantiate the workbook object Workbook workbook = new Workbook(dataDir + "book1.xls"); //Get Cells collection Cells cells = workbook.Worksheets[0].Cells; FindOptions opts = new FindOptions(); opts.LookInType = LookInType.Values; opts.LookAtType = LookAtType.EntireContent; //Find the cell with the input integer or double Cell cell1 = cells.Find(205, null, opts); if (cell1 != null) { Console.WriteLine("Name of the cell containing the value: " + cell1.Name); } else { Console.WriteLine("Record not found "); } //Find the cell with the input string Aspose.Cells.Cell cell2 = cells.Find("Items A", null, opts); if (cell2 != null) { Console.WriteLine("Name of the cell containing the value: " + cell2.Name); } else { Console.WriteLine("Record not found "); } //Find the cell containing with the input string opts.LookAtType = LookAtType.Contains; Cell cell3 = cells.Find("Data", null, opts); if (cell3 != null) { Console.WriteLine("Name of the cell containing the value: " + cell3.Name); } else { Console.WriteLine("Record not found "); } }
public static Widget CreateWidget(WidgetContext ctx) { var ident = (Entity)ctx.Entity; var findOptions = new FindOptions { QueryName = typeof(NoteEntity), Create = false, SearchOnLoad = true, ShowFilters = false, ShowFilterButton = false, FilterOptions = { new FilterOption("Target", ident.ToLite()) }, ColumnOptions = { new ColumnOption("Target") }, ColumnOptionsMode = ColumnOptionsMode.Remove, }.ToJS(ctx.Prefix, "New"); var url = RouteHelper.New().Action((NoteController ac) => ac.NotesCount()); List<IMenuItem> items = new List<IMenuItem>() { new MenuItem(ctx.Prefix, "sfNoteView") { CssClass = "sf-note-view", OnClick = NoteClient.Module["explore"](ctx.Prefix, findOptions, url), Text = NoteMessage.ViewNotes.NiceToString(), }, new MenuItem(ctx.Prefix, "sfNoteCreate") { CssClass = "sf-note-create", OnClick = NoteClient.Module["createNote"](JsFunction.Event, ctx.Prefix, NoteOperation.CreateNoteFromEntity.Symbol.Key, url), Text = NoteMessage.CreateNote.NiceToString() }, }; int count = CountNotes(ident.ToLite()); return new Widget { Id = TypeContextUtilities.Compose(ctx.Prefix, "notesWidget"), Title = NoteMessage.Notes.NiceToString(), IconClass = "glyphicon glyphicon-comment", Active = count > 0, Class = "sf-notes-toggler", Html = new HtmlTag("span").Class("sf-widget-count").SetInnerText(count.ToString()), Items = items }; }
public CachedRegex(string pattern, FindOptions findOptions) { this.pattern = pattern; this.findOptions = findOptions & FindOptionsMask; culture = CultureInfo.CurrentCulture; var options = RegexOptions.None; if ((findOptions & FindOptions.MatchCase) == 0) options |= RegexOptions.IgnoreCase; if ((findOptions & FindOptions.SearchReverse) != 0) options |= RegexOptions.RightToLeft; if ((findOptions & FindOptions.Multiline) != 0) options |= RegexOptions.Multiline; if ((findOptions & FindOptions.SingleLine) != 0) options |= RegexOptions.Singleline; Regex = new Regex(pattern, options); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Instantiate the workbook object Workbook workbook = new Workbook(dataDir + "book1.xls"); // Get Cells collection Cells cells = workbook.Worksheets[0].Cells; // Instantiate FindOptions Object FindOptions findOptions = new FindOptions(); // Create a Cells Area CellArea ca = new CellArea(); ca.StartRow = 8; ca.StartColumn = 2; ca.EndRow = 17; ca.EndColumn = 13; // Set cells area for find options findOptions.SetRange(ca); // Set searching properties findOptions.SearchNext = true; findOptions.SeachOrderByRows = true; // Set the lookintype, you may specify, values, formulas, comments etc. findOptions.LookInType = LookInType.Values; // Set the lookattype, you may specify Match entire content, endswith, starwith etc. findOptions.LookAtType = LookAtType.EntireContent; // Find the cell with value Cell cell = cells.Find(205, null, findOptions); if (cell != null) { Console.WriteLine("Name of the cell containing the value: " + cell.Name); } else { Console.WriteLine("Record not found "); } // ExEnd:1 }
public ActionResult View(Lite<UserQueryEntity> lite, FindOptions findOptions, Lite<Entity> currentEntity) { UserQueryPermission.ViewUserQuery.AssertAuthorized(); UserQueryEntity uq = UserQueryLogic.RetrieveUserQuery(lite); using (uq.EntityType == null ? null : CurrentEntityConverter.SetCurrentEntity(currentEntity.Retrieve())) { if (findOptions == null) findOptions = uq.ToFindOptions(); else findOptions.ApplyUserQuery(uq); } return Finder.SearchPage(this, findOptions); }
public static void Run() { // ExStart:SearchDataUsingOriginalValues // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create workbook object Workbook workbook = new Workbook(); // Access first worksheet Worksheet worksheet = workbook.Worksheets[0]; // Add 10 in cell A1 and A2 worksheet.Cells["A1"].PutValue(10); worksheet.Cells["A2"].PutValue(10); // Add Sum formula in cell D4 but customize it as --- Cell cell = worksheet.Cells["D4"]; Style style = cell.GetStyle(); style.Custom = "---"; cell.SetStyle(style); // The result of formula will be 20 but 20 will not be visible because the cell is formated as --- cell.Formula = "=Sum(A1:A2)"; // Calculate the workbook workbook.CalculateFormula(); // Create find options, we will search 20 using original values otherwise 20 will never be found because it is formatted as --- FindOptions options = new FindOptions(); options.LookInType = LookInType.OriginalValues; options.LookAtType = LookAtType.EntireContent; Cell foundCell = null; object obj = 20; // Find 20 which is Sum(A1:A2) and formatted as --- foundCell = worksheet.Cells.Find(obj, foundCell, options); // Print the found cell Console.WriteLine(foundCell); // Save the workbook workbook.Save(dataDir + "output_out.xlsx"); // ExEnd:SearchDataUsingOriginalValues }
public void Count_should_call_collection_Count( [Values(false, true)] bool async) { var findOptions = new FindOptions<Person, Person> { Collation = new Collation("en_US"), Limit = 1, MaxTime = TimeSpan.FromSeconds(1), Modifiers = new BsonDocument("$hint", "hint"), Skip = 2 }; var subject = CreateSubject(findOptions); Predicate<CountOptions> countOptionsPredicate = countOptions => { return countOptions.Collation == findOptions.Collation && countOptions.Hint == findOptions.Modifiers["$hint"].AsString && countOptions.Limit == findOptions.Limit && countOptions.MaxTime == findOptions.MaxTime && countOptions.Skip == findOptions.Skip; }; if (async) { subject.CountAsync().GetAwaiter().GetResult(); _mockCollection.Verify( c => c.CountAsync( subject.Filter, It.Is<CountOptions>(o => countOptionsPredicate(o)), It.IsAny<CancellationToken>()), Times.Once); } else { subject.Count(); _mockCollection.Verify( c => c.Count( subject.Filter, It.Is<CountOptions>(o => countOptionsPredicate(o)), It.IsAny<CancellationToken>()), Times.Once); } }
public static void SetScintillaSearchFlags(Scintilla scintilla, FindOptions findOptions, FindMode findMode) { if (scintilla == null) { return; } // 検索オプション scintilla.SearchFlags = 0; scintilla.SearchFlags |= findOptions.HasFlag(FindOptions.MatchWholeWordOnly) ? SearchFlags.WholeWord : SearchFlags.None; scintilla.SearchFlags |= findOptions.HasFlag(FindOptions.MatchCase) ? SearchFlags.MatchCase : SearchFlags.None; // 検索モード scintilla.SearchFlags |= findMode == FindMode.RegularExpression ? SearchFlags.Regex : SearchFlags.None; }
public ActionResult Index(FindOptions findOptions) { ChartPermission.ViewCharting.AssertAuthorized(); if (!Finder.IsFindable(findOptions.QueryName)) throw new UnauthorizedAccessException(ChartMessage.Chart_Query0IsNotAllowed.NiceToString().FormatWith(findOptions.QueryName)); QueryDescription queryDescription = DynamicQueryManager.Current.QueryDescription(findOptions.QueryName); FilterOption.SetFilterTokens(findOptions.FilterOptions, queryDescription, false); var request = new ChartRequest(findOptions.QueryName) { ChartScript = ChartScriptLogic.Scripts.Value.Values.FirstEx(() => "No ChartScript loaded in the database"), Filters = findOptions.FilterOptions.Select(fo => fo.ToFilter()).ToList() }; return OpenChartRequest(request, null); }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); string filePath = dataDir+ "input.xlsx"; Workbook workbook = new Workbook(filePath); Worksheet worksheet = workbook.Worksheets[0]; //Specify the range where you want to search //Here the range is E3:H6 CellArea area = CellArea.CreateCellArea("E9", "H15"); //Specify Find options FindOptions opts = new FindOptions(); opts.LookInType = LookInType.Values; opts.LookAtType = LookAtType.EntireContent; opts.SetRange(area); Cell cell = null; do { //Search the cell with value search within range cell = worksheet.Cells.Find("search", cell, opts); //If no such cell found, then break the loop if (cell == null) break; //Replace the cell with value replace cell.PutValue("replace"); } while (true); //Save the workbook workbook.Save(dataDir+ "output.xlsx"); }
static void Main(string[] args) { //Instantiating a Workbook object Workbook workbook = new Workbook("../../data/test.xlsx"); //Accessing the first worksheet in the Excel file Worksheet worksheet = workbook.Worksheets[0]; //Finding the cell containing the specified formula Cells cells = worksheet.Cells; //Instantiate FindOptions FindOptions findOptions = new FindOptions(); //Finding the cell containing a string value that starts with "Or" findOptions.LookAtType = LookAtType.StartWith; Cell cell = cells.Find("SH", null, findOptions); //Printing the name of the cell found after searching worksheet Console.WriteLine("Name of the cell containing String: " + cell.Name); }
/// <summary> /// /// </summary> /// <param name="asm"></param> /// <param name="findOptions"> Опции указывающие какие типы и члены собирать</param> /// <param name="unboundTypes">Массив типов из XML документации, которые не смогли привязаться к данным из Reflection</param> /// <param name="unboundMembers">Массив members из XML документации, которые не смогли привязаться к данным из Reflection</param> public void MergeWithReflection(Assembly asm, FindOptions findOptions, out TypeDoc[] unboundTypes, out MemberDoc[] unboundMembers) { var docTypes=Types.ToDictionary(_ => _.FullName); foreach (var type in asm.GetTypes()) { if(!type.IsVisible && !findOptions.InternalClasses) continue; string name = type.FullName.Replace('+', '.'); //Для nested классов type.FullName дает Class1+Class2, а по XML Class1.Class2 - невозможно отличить nested класс от namespace TypeDoc docT; if (docTypes.TryGetValue(name, out docT)) { if(docT.ReflectionType!=null) throw new Exception("multiple types on single node"); docT.ReflectionType = type; } else if (findOptions.UndocumentedClasses) { docT = new TypeDoc { FullName = name , ReflectionType = type}; if (!docT.FullName.Contains("XamlGeneratedNamespace")) docTypes.Add(docT.FullName, docT); } } if (findOptions.UndocumentedClasses) Types = docTypes.Select(_ => _.Value).ToArray(); unboundTypes = Types.Where(_ => _.ReflectionType == null).ToArray(); if (unboundTypes.Length > 0) Types = Types.Where(_ => _.ReflectionType != null).ToArray(); var unbound = new List<MemberDoc>(); foreach (var type in Types) unbound.AddRange(type.MergeMembersWithReflection(!findOptions.UndocumentedMembers, findOptions.PrivateMembers)); unboundMembers = unbound.ToArray(); }
private void BTN_Find_Click(object sender, EventArgs e) { if (TXBX_Find.Text != "") { workbook = new Workbook(FOD_OpenFile.FileName); FindOptions Opts = new FindOptions(); Opts.LookInType = LookInType.Values; Opts.LookAtType = LookAtType.Contains; string found = ""; Cell cell = null; foreach (Worksheet sheet in workbook.Worksheets) { found += Environment.NewLine + "Sheet: " + sheet.Name + ":"; do { cell = sheet.Cells.Find(TXBX_Find.Text, cell, Opts); if (cell != null) found += cell.Name + ","; } while (cell != null); } LBL_FindResults.Text = found; } }
void FindNextCore(FindOptions options, SnapshotPoint? startingPosition) { if (startingPosition == null) return; var res = FindNextResultCore(options, startingPosition.Value); if (res == null) return; ShowSearchResult(res.Value); }
IEnumerable <FindResult> FindAllCore(SnapshotSpan searchRange, SnapshotPoint startingPosition, string searchPattern, FindOptions options, string?replacePattern) { if (!(searchRange.Start <= startingPosition && startingPosition <= searchRange.End)) { return(Array.Empty <FindResult>()); } if ((options & FindOptions.Multiline) != 0) { return(FindAllCoreMultiline(searchRange, startingPosition, searchPattern, options, replacePattern)); } return(FindAllCoreSingleLine(searchRange, startingPosition, searchPattern, options, replacePattern)); }
SnapshotPoint? GetStartingPosition(SearchKind searchKind, FindOptions options, bool restart) { Debug.Assert(searchKind != SearchKind.None); switch (searchKind) { case SearchKind.Find: case SearchKind.Replace: return GetStartingPosition(options, restart); case SearchKind.IncrementalSearchBackward: case SearchKind.IncrementalSearchForward: return incrementalStartPosition; default: throw new ArgumentOutOfRangeException(nameof(searchKind)); } }
IEnumerable <FindResult> FindAllCoreMultiline(SnapshotSpan searchRange, SnapshotPoint startingPosition, string searchPattern, FindOptions options, string?replacePattern) { Debug.Assert((options & FindOptions.Multiline) == FindOptions.Multiline); var stringComparison = GetStringComparison(options); if ((options & FindOptions.SearchReverse) != 0) { // reverse search var searchText = searchRange.GetText(); var range1 = new SnapshotSpan(searchRange.Start, startingPosition); if (range1.Length > 0) { foreach (var res in FindAllCoreMultilineReverse(searchText, searchRange.Start, startingPosition, searchPattern, options, stringComparison, replacePattern)) { yield return(res); } } if ((options & FindOptions.Wrap) != 0) { var range2 = new SnapshotSpan(startingPosition, searchRange.End); if (range2.Length > 0) { foreach (var res in FindAllCoreMultilineReverse(searchText, searchRange.Start, searchRange.End, searchPattern, options, stringComparison, replacePattern)) { if (res.Position + res.Length <= startingPosition.Position) { break; } yield return(res); } } } } else { // forward search var searchText = searchRange.GetText(); var range1 = new SnapshotSpan(startingPosition, searchRange.End); if (range1.Length > 0) { foreach (var res in FindAllCoreMultilineForward(searchText, searchRange.Start, startingPosition, searchPattern, options, stringComparison, replacePattern)) { yield return(res); } } if ((options & FindOptions.Wrap) != 0) { var range2 = new SnapshotSpan(searchRange.Start, startingPosition); if (range2.Length > 0) { foreach (var res in FindAllCoreMultilineForward(searchText, searchRange.Start, searchRange.Start, searchPattern, options, stringComparison, replacePattern)) { if (res.Position >= startingPosition.Position) { break; } yield return(res); } } } } }
private void frmFind_FindText(object sender, EventArgs e) { findOptions = sender as FindOptions; resetColors(); //currentCell_Row = 0; //currentCell_Col = 0; setStartCell(); findText(findOptions); }
public extern Iterator Find(FindOptions options = FindOptions.None);
IEnumerable <FindResult> FindAllCoreMultilineReverse(string searchText, SnapshotPoint searchTextPosition, SnapshotPoint startingPosition, string searchPattern, FindOptions options, StringComparison stringComparison, string?replacePattern) { Debug.Assert((options & FindOptions.SearchReverse) != 0); bool onlyWords = (options & FindOptions.WholeWord) != 0; int index = startingPosition - searchTextPosition; if ((options & FindOptions.UseRegularExpressions) != 0) { var regex = GetRegex(searchPattern, options); foreach (var res in GetRegexResults(regex, searchTextPosition, searchText, index, searchPattern, options, replacePattern)) { yield return(res); } } else { while (index > 0) { index = searchText.LastIndexOf(searchPattern, index - 1, index, stringComparison); if (index < 0) { break; } if (!onlyWords || IsWord(searchTextPosition.Snapshot, searchTextPosition.Position + index, searchPattern.Length)) { yield return(new FindResult(searchTextPosition.Position + index, searchPattern.Length, replacePattern)); } index += searchPattern.Length - 1; } } }
public void ToCursor_with_an_expression_should_call_collection_FindAsync_with_correct_options( [Values(false, true)] bool async) { var mockSubject = CreateMockSubject(); var subject = mockSubject.Object; var filter = BsonDocument.Parse("{Age:1}"); var projection = BsonDocument.Parse("{y:1}"); var sort = BsonDocument.Parse("{a:1}"); var options = new FindOptions { AllowPartialResults = true, BatchSize = 20, Collation = new Collation("en_US"), Comment = "funny", CursorType = CursorType.TailableAwait, MaxAwaitTime = TimeSpan.FromSeconds(4), MaxTime = TimeSpan.FromSeconds(3), Modifiers = BsonDocument.Parse("{$snapshot: true}"), NoCursorTimeout = true, OplogReplay = true }; var fluent = subject.Find(x => x.Age == 1, options) .Project(projection) .Sort(sort) .Limit(30) .Skip(40); FilterDefinition <Person> actualFilter = null; FindOptions <Person, BsonDocument> actualOptions = null; if (async) { mockSubject .Setup(s => s.FindAsync(It.IsAny <FilterDefinition <Person> >(), It.IsAny <FindOptions <Person, BsonDocument> >(), It.IsAny <CancellationToken>())) .Callback((FilterDefinition <Person> filterArg, FindOptions <Person, BsonDocument> optionsArg, CancellationToken cancellationToken) => { actualFilter = filterArg; actualOptions = optionsArg; }) .Returns(Task.FromResult(new Mock <IAsyncCursor <BsonDocument> >().Object)); fluent.ToCursorAsync(CancellationToken.None).GetAwaiter().GetResult(); } else { mockSubject .Setup(s => s.FindSync(It.IsAny <FilterDefinition <Person> >(), It.IsAny <FindOptions <Person, BsonDocument> >(), It.IsAny <CancellationToken>())) .Callback((FilterDefinition <Person> filterArg, FindOptions <Person, BsonDocument> optionsArg, CancellationToken cancellationToken) => { actualFilter = filterArg; actualOptions = optionsArg; }) .Returns(new Mock <IAsyncCursor <BsonDocument> >().Object); fluent.ToCursor(CancellationToken.None); } actualFilter.Should().BeOfType <ExpressionFilterDefinition <Person> >(); actualFilter.Render(subject.DocumentSerializer, subject.Settings.SerializerRegistry).Should().Be(filter); actualOptions.AllowPartialResults.Should().Be(fluent.Options.AllowPartialResults); actualOptions.BatchSize.Should().Be(fluent.Options.BatchSize); actualOptions.Collation.Should().BeSameAs(fluent.Options.Collation); actualOptions.Comment.Should().Be(fluent.Options.Comment); actualOptions.CursorType.Should().Be(fluent.Options.CursorType); actualOptions.Limit.Should().Be(fluent.Options.Limit); actualOptions.MaxAwaitTime.Should().Be(fluent.Options.MaxAwaitTime); actualOptions.MaxTime.Should().Be(fluent.Options.MaxTime); actualOptions.Modifiers.Should().Be(fluent.Options.Modifiers); actualOptions.NoCursorTimeout.Should().Be(fluent.Options.NoCursorTimeout); actualOptions.OplogReplay.Should().Be(fluent.Options.OplogReplay); actualOptions.Projection.Should().Be(fluent.Options.Projection); actualOptions.Skip.Should().Be(fluent.Options.Skip); actualOptions.Sort.Should().Be(fluent.Options.Sort); }
public async Task <IAsyncCursor <TReadModel> > FindAsync(Expression <Func <TReadModel, bool> > filter, FindOptions <TReadModel, TReadModel> options = null, CancellationToken cancellationToken = new CancellationToken()) { var readModelDescription = _readModelDescriptionProvider.GetReadModelDescription <TReadModel>(); var collection = _mongoDatabase.GetCollection <TReadModel>(readModelDescription.RootCollectionName.Value); _log.Verbose(() => $"Finding read model '{typeof(TReadModel).PrettyPrint()}' with expression '{filter}' from collection '{readModelDescription.RootCollectionName}'"); return(await collection.FindAsync(filter, options, cancellationToken)); }
/// <summary> /// Get all notification endpoints. /// </summary> /// <param name="orgId">only show notification endpoints belonging to specified organization</param> /// <param name="findOptions">the find options</param> /// <returns></returns> public async Task <NotificationEndpoints> FindNotificationEndpointsAsync(string orgId, FindOptions findOptions) { Arguments.CheckNonEmptyString(orgId, nameof(orgId)); Arguments.CheckNotNull(findOptions, nameof(findOptions)); return(await _service.GetNotificationEndpointsAsync(orgId, offset : findOptions.Offset, limit : findOptions.Limit)); }
private IFindFluent <Person, Person> CreateSubject(IClientSessionHandle session = null, FilterDefinition <Person> filter = null, FindOptions <Person, Person> options = null) { var settings = new MongoCollectionSettings(); _mockCollection = new Mock <IMongoCollection <Person> >(); _mockCollection.SetupGet(c => c.DocumentSerializer).Returns(BsonSerializer.SerializerRegistry.GetSerializer <Person>()); _mockCollection.SetupGet(c => c.Settings).Returns(settings); filter = filter ?? new BsonDocument(); options = options ?? new FindOptions <Person, Person>(); var subject = new FindFluent <Person, Person>(session: session, collection: _mockCollection.Object, filter: filter, options: options); return(subject); }
public static extern Iterator Find(StorageContext context, byte[] prefix, FindOptions options = FindOptions.None);
public extern Iterator Find(byte[] prefix, FindOptions options = FindOptions.None);
public extern Iterator Find(ByteString prefix, FindOptions options = FindOptions.None);
IEnumerable <Tuple <SnapshotSpan, string?> > FindAllForReplace(SnapshotSpan searchRange, SnapshotPoint startingPosition, string searchPattern, string replacePattern, FindOptions options) { var snapshot = searchRange.Snapshot; foreach (var res in FindAllCore(searchRange, startingPosition, searchPattern, options, replacePattern)) { yield return(Tuple.Create(new SnapshotSpan(snapshot, res.Position, res.Length), res.ExpandedReplacePattern)); } }
public static async Task <List <Movie> > GetMovie(GetMovieInput Parameters) { var List = new List <Movie>(); var projection = Builders <Movie> .Projection; var project = projection.Exclude("_id"); var filter = FilterDefinition <Movie> .Empty; BsonValue val; if (Parameters.ColumnType == "int") { val = Convert.ToInt64(Parameters.Value); } else if (Parameters.ColumnType == "bool") { val = Convert.ToBoolean(Parameters.Value); } else { val = Convert.ToString(Parameters.Value); } if (Parameters.Statement == "=") { filter = Builders <Movie> .Filter.Eq(Parameters.Column, val); } else if (Parameters.Statement == "<") { filter = Builders <Movie> .Filter.Lt(Parameters.Column, val); } else if (Parameters.Statement == ">") { filter = Builders <Movie> .Filter.Gt(Parameters.Column, val); } var option = new FindOptions <Movie, BsonDocument> { Projection = project }; using (var cursor = await db.GetCollection <Movie>("Movie").FindAsync(filter, option)) { while (await cursor.MoveNextAsync()) { var batch = cursor.Current; foreach (BsonDocument s in batch) { var movie = new Movie(); if (s.Contains("MovieID")) { movie.MovieID = s["MovieID"].AsString; } if (s.Contains("MovieName")) { movie.MovieName = s["MovieName"].AsString; } if (s.Contains("Actors")) { movie.Actors = s["Actors"].AsString; } if (s.Contains("PublishedDate")) { movie.PublishedDate = s["PublishedDate"].AsString; } if (s.Contains("Country")) { movie.Country = s["Country"].AsString; } if (s.Contains("Company")) { movie.Company = s["Company"].AsString; } if (s.Contains("Scenario")) { movie.Scenario = s["Scenario"].AsString; } if (s.Contains("MovieType")) { movie.MovieType = s["MovieType"].AsString; } if (s.Contains("Time")) { movie.Time = s["Time"].AsDouble; } if (s.Contains("IMDB")) { movie.IMDB = s["IMDB"].AsDouble; } List.Add(movie); } } } return(List); }
public IEnumerable <Tuple <SnapshotSpan, string?> > FindAllForReplace(SnapshotSpan searchRange, string searchPattern, string replacePattern, FindOptions options) { if (searchRange.Snapshot is null) { throw new ArgumentException(); } if (searchPattern is null) { throw new ArgumentNullException(nameof(searchPattern)); } if (searchPattern.Length == 0) { throw new ArgumentOutOfRangeException(nameof(searchPattern)); } if (replacePattern is null) { throw new ArgumentNullException(nameof(replacePattern)); } return(FindAllForReplace(searchRange, searchRange.Start, searchPattern, replacePattern, options)); }
private IFindFluent <Person, Person> CreateSubject(IClientSessionHandle session = null, FilterDefinition <Person> filter = null, FindOptions <Person, Person> options = null) { var clientSettings = new MongoClientSettings { LinqProvider = LinqProvider.V2 }; var mockClient = new Mock <IMongoClient>(); mockClient.SetupGet(c => c.Settings).Returns(clientSettings); var mockDatabase = new Mock <IMongoDatabase>(); mockDatabase.SetupGet(d => d.Client).Returns(mockClient.Object); var collectionSettings = new MongoCollectionSettings(); _mockCollection = new Mock <IMongoCollection <Person> >(); _mockCollection.SetupGet(c => c.Database).Returns(mockDatabase.Object); _mockCollection.SetupGet(c => c.DocumentSerializer).Returns(BsonSerializer.SerializerRegistry.GetSerializer <Person>()); _mockCollection.SetupGet(c => c.Settings).Returns(collectionSettings); filter = filter ?? new BsonDocument(); options = options ?? new FindOptions <Person, Person>(); var subject = new FindFluent <Person, Person>(session: session, collection: _mockCollection.Object, filter: filter, options: options); return(subject); }
public bool Equals(string pattern, FindOptions findOptions) => StringComparer.Ordinal.Equals(pattern, this.pattern) && (findOptions & FindOptionsMask) == this.findOptions && CultureInfo.CurrentCulture == culture;
public void Count_should_call_collection_Count( [Values(false, true)] bool usingSession, [Values(false, true)] bool async) { var session = CreateSession(usingSession); var filter = new BsonDocumentFilterDefinition <Person>(new BsonDocument("filter", 1)); var hint = new BsonDocument("hint", 1); var findOptions = new FindOptions <Person> { Collation = new Collation("en-us"), Limit = 1, MaxTime = TimeSpan.FromSeconds(2), #pragma warning disable 618 Modifiers = new BsonDocument("$hint", hint), #pragma warning restore 618 Skip = 3 }; var subject = CreateSubject(session: session, filter: filter, options: findOptions); var cancellationToken = new CancellationTokenSource().Token; Predicate <CountOptions> matchesExpectedOptions = countOptions => countOptions.Collation.Equals(findOptions.Collation) && countOptions.Hint.Equals(hint) && countOptions.Limit.Equals((long?)findOptions.Limit) && countOptions.MaxTime.Equals(findOptions.MaxTime) && countOptions.Skip.Equals((long?)findOptions.Skip); if (async) { if (usingSession) { #pragma warning disable 618 subject.CountAsync(cancellationToken).GetAwaiter().GetResult(); _mockCollection.Verify( m => m.CountAsync( session, filter, It.Is <CountOptions>(o => matchesExpectedOptions(o)), cancellationToken), Times.Once); #pragma warning restore } else { #pragma warning disable 618 subject.CountAsync(cancellationToken).GetAwaiter().GetResult(); _mockCollection.Verify( m => m.CountAsync( filter, It.Is <CountOptions>(o => matchesExpectedOptions(o)), cancellationToken), Times.Once); } #pragma warning restore } else { if (usingSession) { #pragma warning disable 618 subject.Count(cancellationToken); _mockCollection.Verify( m => m.Count( session, filter, It.Is <CountOptions>(o => matchesExpectedOptions(o)), cancellationToken), Times.Once); #pragma warning restore } else { #pragma warning disable 618 subject.Count(cancellationToken); _mockCollection.Verify( m => m.Count( filter, It.Is <CountOptions>(o => matchesExpectedOptions(o)), cancellationToken), Times.Once); #pragma warning restore } } }
IEnumerable <FindResult> GetRegexResults(Regex regex, SnapshotPoint searchTextPosition, string searchText, int index, string searchPattern, FindOptions options, string?replacePattern) { bool onlyWords = (options & FindOptions.WholeWord) != 0; foreach (Match?match in regex.Matches(searchText, index)) { Debug2.Assert(match is not null); int position = searchTextPosition.Position + match.Index; if (!onlyWords || IsWord(searchTextPosition.Snapshot, position, searchPattern.Length)) { yield return(new FindResult(position, match.Length, replacePattern is null ? null : match.Result(replacePattern))); } } }
public MyMongoDataContext(string connectionString, string dbName, FindOptions findOptions) : base( connectionString, dbName, findOptions) { }
IEnumerable <FindResult> FindAllSingleLineReverse(ITextSnapshotLine startLine, ITextSnapshotLine endLine, SnapshotSpan searchRange, string searchPattern, FindOptions options, StringComparison stringComparison, string?replacePattern) { Debug.Assert((options & FindOptions.SearchReverse) != 0); int startLineNumber = startLine.LineNumber; var snapshot = searchRange.Snapshot; bool onlyWords = (options & FindOptions.WholeWord) != 0; var regex = (options & FindOptions.UseRegularExpressions) != 0 ? GetRegex(searchPattern, options) : null; for (int lineNumber = endLine.LineNumber; lineNumber >= startLineNumber; lineNumber--) { var line = snapshot.GetLineFromLineNumber(lineNumber); var range = searchRange.Intersection(line.ExtentIncludingLineBreak); if (range is null || range.Value.Length == 0) { continue; } var text = range.Value.GetText(); int index = text.Length; if (regex is not null) { foreach (var res in GetRegexResults(regex, range.Value.Start, text, index, searchPattern, options, replacePattern)) { yield return(res); } } else { while (index > 0) { index = text.LastIndexOf(searchPattern, index - 1, index, stringComparison); if (index < 0) { break; } if (!onlyWords || UnicodeUtilities.IsWord(line, range.Value.Start.Position - line.Start.Position + index, searchPattern.Length)) { yield return(new FindResult(range.Value.Start.Position + index, searchPattern.Length, replacePattern)); } index += searchPattern.Length - 1; } } } }
/// <summary> /// Find next match of the input string. /// </summary> /// <param name="input">The string to search for a match.</param> /// <param name="findOptions">the search options</param> /// <returns>The <see cref="TextRange"/> instance representing the input string.</returns> /// <remarks> /// This method will advance the <see cref="CurrentPosition"/> to next context position. /// </remarks> public TextRange FindNext(String input, FindOptions findOptions) { TextRange textRange = GetTextRangeFromPosition(ref currentPosition, input, findOptions, LogicalDirection.Forward); return(textRange); }
IEnumerable <FindResult> FindAllCoreSingleLine(SnapshotSpan searchRange, SnapshotPoint startingPosition, string searchPattern, FindOptions options, string?replacePattern) { Debug.Assert((options & FindOptions.Multiline) == 0); var firstLine = searchRange.Start.GetContainingLine(); var lastLine = searchRange.End.GetContainingLine(); var startLine = startingPosition.GetContainingLine(); var stringComparison = GetStringComparison(options); if ((options & FindOptions.SearchReverse) != 0) { // reverse search var range1 = new SnapshotSpan(searchRange.Start, startingPosition); if (range1.Length > 0) { foreach (var res in FindAllSingleLineReverse(firstLine, startLine, range1, searchPattern, options, stringComparison, replacePattern)) { yield return(res); } } if ((options & FindOptions.Wrap) != 0) { var range2 = new SnapshotSpan(startLine.Start, searchRange.End); if (range2.Length > 0) { foreach (var res in FindAllSingleLineReverse(startLine, lastLine, range2, searchPattern, options, stringComparison, replacePattern)) { if (res.Position + res.Length <= startingPosition.Position) { break; } yield return(res); } } } } else { // forward search var range1 = new SnapshotSpan(startingPosition, searchRange.End); if (range1.Length > 0) { foreach (var res in FindAllSingleLineForward(startLine, lastLine, range1, searchPattern, options, stringComparison, replacePattern)) { yield return(res); } } if ((options & FindOptions.Wrap) != 0) { var range2 = new SnapshotSpan(searchRange.Start, startLine.EndIncludingLineBreak); if (range2.Length > 0) { foreach (var res in FindAllSingleLineForward(firstLine, startLine, range2, searchPattern, options, stringComparison, replacePattern)) { if (res.Position >= startingPosition.Position) { break; } yield return(res); } } } } }
/// <inheritdoc/> public Task <IAsyncCursor <TProjection> > FindAsync <TProjection>(FilterDefinition <T> filter, FindOptions <T, TProjection> options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(_actualCollection.FindAsync(filter, options, cancellationToken)); }
static string Unescape(string s, FindOptions options) { if ((options & FindOptions.UseRegularExpressions) == 0) return s; if (s.IndexOf('\\') < 0) return s; var sb = new StringBuilder(s.Length); for (int i = 0; i < s.Length; i++) { var c = s[i]; if (c == '\\' && i + 1 < s.Length) { i++; c = s[i]; switch (c) { case 't': sb.Append('\t'); break; case 'n': sb.Append('\n'); break; case 'r': sb.Append('\r'); break; default: sb.Append('\\'); sb.Append(c); break; } } else sb.Append(c); } return sb.ToString(); }
/// <inheritdoc/> public IAsyncCursor <TProjection> FindSync <TProjection>(IClientSessionHandle session, FilterDefinition <T> filter, FindOptions <T, TProjection> options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(_actualCollection.FindSync(filter, options, cancellationToken)); }
SnapshotPoint? GetStartingPosition(FindOptions options, bool restart) { if (wpfTextView.Selection.IsEmpty) return wpfTextView.Caret.Position.BufferPosition; if (restart) { if ((options & FindOptions.SearchReverse) == 0) return wpfTextView.Selection.Start.Position; return wpfTextView.Selection.End.Position; } if ((options & FindOptions.SearchReverse) != 0) { if (wpfTextView.Selection.End.Position.Position > 0) return wpfTextView.Selection.End.Position - 1; if ((options & FindOptions.Wrap) != 0) return new SnapshotPoint(wpfTextView.TextSnapshot, wpfTextView.TextSnapshot.Length); return null; } if (wpfTextView.Selection.Start.Position.Position != wpfTextView.Selection.Start.Position.Snapshot.Length) return wpfTextView.Selection.Start.Position + 1; if ((options & FindOptions.Wrap) != 0) return new SnapshotPoint(wpfTextView.TextSnapshot, 0); return null; }
protected Task <List <T> > GetModelsAsync <T>(Expression <Func <T, bool> > filter, MongoCollectionSettings settings = null, FindOptions options = null) { var collection = Collection <T>(ModelName <T>(), settings); return(collection.Find(filter, options).ToListAsync()); }
SnapshotSpan? FindNextResultCore(FindOptions options, SnapshotPoint startingPosition) { if (SearchString.Length == 0) return null; var snapshot = wpfTextView.TextSnapshot; startingPosition = startingPosition.TranslateTo(snapshot, PointTrackingMode.Negative); var searchRange = new SnapshotSpan(snapshot, 0, snapshot.Length); try { return textSearchService2.Find(searchRange, startingPosition, SearchString, options); } catch (ArgumentException) when ((options & FindOptions.UseRegularExpressions) != 0) { // Invalid regex string return null; } }
/// <summary> /// Find the corresponding <see cref="TextRange"/> instance /// representing the input string given a specified text pointer position. /// </summary> /// <param name="position">the current text position</param> /// <param name="textToFind">input text</param> /// <param name="findOptions">the search option</param> /// <returns>An <see cref="TextRange"/> instance represeneting the matching string withing the text container.</returns> public TextRange GetTextRangeFromPosition(ref TextPointer position, String input, FindOptions findOptions) { Boolean matchCase = (findOptions & FindOptions.MatchCase) == FindOptions.MatchCase; Boolean matchWholeWord = (findOptions & FindOptions.MatchWholeWord) == FindOptions.MatchWholeWord; TextRange textRange = null; while (position != null) { if (position.CompareTo(inputDocument.ContentEnd) == 0) { break; } if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text) { String textRun = position.GetTextInRun(LogicalDirection.Forward); StringComparison stringComparison = matchCase ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase; Int32 indexInRun = textRun.IndexOf(input, stringComparison); if (indexInRun >= 0) { position = position.GetPositionAtOffset(indexInRun); TextPointer nextPointer = position.GetPositionAtOffset(input.Length); textRange = new TextRange(position, nextPointer); if (matchWholeWord) { if (IsWholeWord(textRange)) // Test if the "textRange" represents a word. { // If a WholeWord match is found, directly terminate the loop. break; } else { // If a WholeWord match is not found, go to next recursion to find it. position = position.GetPositionAtOffset(input.Length); return(GetTextRangeFromPosition(ref position, input, findOptions)); } } else { // If a none-WholeWord match is found, directly terminate the loop. position = position.GetPositionAtOffset(input.Length); break; } } else { // If a match is not found, go over to the next context position after the "textRun". position = position.GetPositionAtOffset(textRun.Length); } } else { //If the current position doesn't represent a text context position, go to the next context position. // This can effectively ignore the formatting or emebed element symbols. position = position.GetNextContextPosition(LogicalDirection.Forward); } } return(textRange); }
public void ToCursor_with_an_expression_should_call_collection_FindAsync_with_correct_options( [Values(false, true)] bool async) { var subject = CreateSubject(); var filter = BsonDocument.Parse("{Age:1}"); var projection = BsonDocument.Parse("{y:1}"); var sort = BsonDocument.Parse("{a:1}"); var options = new FindOptions { AllowPartialResults = true, BatchSize = 20, Comment = "funny", CursorType = CursorType.TailableAwait, MaxAwaitTime = TimeSpan.FromSeconds(4), MaxTime = TimeSpan.FromSeconds(3), Modifiers = BsonDocument.Parse("{$snapshot: true}"), NoCursorTimeout = true, OplogReplay = true }; var fluent = subject.Find(x => x.Age == 1, options) .Project(projection) .Sort(sort) .Limit(30) .Skip(40); FilterDefinition<Person> actualFilter = null; FindOptions<Person, BsonDocument> actualOptions = null; if (async) { subject.FindAsync( Arg.Do<FilterDefinition<Person>>(x => actualFilter = x), Arg.Do<FindOptions<Person, BsonDocument>>(x => actualOptions = x), Arg.Any<CancellationToken>()); fluent.ToCursorAsync(CancellationToken.None).GetAwaiter().GetResult(); } else { subject.FindSync( Arg.Do<FilterDefinition<Person>>(x => actualFilter = x), Arg.Do<FindOptions<Person, BsonDocument>>(x => actualOptions = x), Arg.Any<CancellationToken>()); fluent.ToCursor(CancellationToken.None); } actualFilter.Should().BeOfType<ExpressionFilterDefinition<Person>>(); actualFilter.Render(subject.DocumentSerializer, subject.Settings.SerializerRegistry).Should().Be(filter); actualOptions.AllowPartialResults.Should().Be(fluent.Options.AllowPartialResults); actualOptions.BatchSize.Should().Be(fluent.Options.BatchSize); actualOptions.Comment.Should().Be(fluent.Options.Comment); actualOptions.CursorType.Should().Be(fluent.Options.CursorType); actualOptions.Limit.Should().Be(fluent.Options.Limit); actualOptions.MaxAwaitTime.Should().Be(fluent.Options.MaxAwaitTime); actualOptions.MaxTime.Should().Be(fluent.Options.MaxTime); actualOptions.Modifiers.Should().Be(fluent.Options.Modifiers); actualOptions.NoCursorTimeout.Should().Be(fluent.Options.NoCursorTimeout); actualOptions.OplogReplay.Should().Be(fluent.Options.OplogReplay); actualOptions.Projection.Should().Be(fluent.Options.Projection); actualOptions.Skip.Should().Be(fluent.Options.Skip); actualOptions.Sort.Should().Be(fluent.Options.Sort); }
public static async Task <List <Scenario> > GetScenario(GetScenarioInput Parameters) { var List = new List <Scenario>(); var projection = Builders <Scenario> .Projection; var project = projection.Exclude("_id"); var filter = FilterDefinition <Scenario> .Empty; BsonValue val; if (Parameters.ColumnType == "int") { val = Convert.ToInt64(Parameters.Value); } else if (Parameters.ColumnType == "bool") { val = Convert.ToBoolean(Parameters.Value); } else { val = Convert.ToString(Parameters.Value); } if (Parameters.Statement == "=") { filter = Builders <Scenario> .Filter.Eq(Parameters.Column, val); } else if (Parameters.Statement == "<") { filter = Builders <Scenario> .Filter.Lt(Parameters.Column, val); } else if (Parameters.Statement == ">") { filter = Builders <Scenario> .Filter.Gt(Parameters.Column, val); } var option = new FindOptions <Scenario, BsonDocument> { Projection = project }; using (var cursor = await db.GetCollection <Scenario>("Scenario").FindAsync(filter, option)) { while (await cursor.MoveNextAsync()) { var batch = cursor.Current; foreach (BsonDocument s in batch) { var Scenario = new Scenario(); if (s.Contains("ScenarioID")) { Scenario.ScenarioID = s["ScenarioID"].AsString; } if (s.Contains("ScenarioName")) { Scenario.ScenarioName = s["ScenarioName"].AsString; } if (s.Contains("Scenarioİmage")) { Scenario.Scenarioİmage = s["Scenarioİmage"].AsString; } List.Add(Scenario); } } } return(List); }
public async Task FindUserLogsPaging() { var user = await _usersApi.CreateUserAsync(GenerateName("John Ryzen")); foreach (var i in Enumerable.Range(0, 19)) { user.Name = $"{i}_{user.Name}"; await _usersApi.UpdateUserAsync(user); } var logs = await _usersApi.FindUserLogsAsync(user); Assert.AreEqual(20, logs.Count); Assert.AreEqual("User Created", logs[0].Description); Assert.AreEqual("User Updated", logs[19].Description); var findOptions = new FindOptions { Limit = 5, Offset = 0 }; var entries = await _usersApi.FindUserLogsAsync(user, findOptions); Assert.AreEqual(5, entries.Logs.Count); Assert.AreEqual("User Created", entries.Logs[0].Description); Assert.AreEqual("User Updated", entries.Logs[1].Description); Assert.AreEqual("User Updated", entries.Logs[2].Description); Assert.AreEqual("User Updated", entries.Logs[3].Description); Assert.AreEqual("User Updated", entries.Logs[4].Description); findOptions.Offset += 5; entries = await _usersApi.FindUserLogsAsync(user, findOptions); Assert.AreEqual(5, entries.Logs.Count); Assert.AreEqual("User Updated", entries.Logs[0].Description); Assert.AreEqual("User Updated", entries.Logs[1].Description); Assert.AreEqual("User Updated", entries.Logs[2].Description); Assert.AreEqual("User Updated", entries.Logs[3].Description); Assert.AreEqual("User Updated", entries.Logs[4].Description); findOptions.Offset += 5; entries = await _usersApi.FindUserLogsAsync(user, findOptions); Assert.AreEqual(5, entries.Logs.Count); Assert.AreEqual("User Updated", entries.Logs[0].Description); Assert.AreEqual("User Updated", entries.Logs[1].Description); Assert.AreEqual("User Updated", entries.Logs[2].Description); Assert.AreEqual("User Updated", entries.Logs[3].Description); Assert.AreEqual("User Updated", entries.Logs[4].Description); findOptions.Offset += 5; entries = await _usersApi.FindUserLogsAsync(user, findOptions); Assert.AreEqual(5, entries.Logs.Count); Assert.AreEqual("User Updated", entries.Logs[0].Description); Assert.AreEqual("User Updated", entries.Logs[1].Description); Assert.AreEqual("User Updated", entries.Logs[2].Description); Assert.AreEqual("User Updated", entries.Logs[3].Description); Assert.AreEqual("User Updated", entries.Logs[4].Description); findOptions.Offset += 5; entries = await _usersApi.FindUserLogsAsync(user, findOptions); Assert.AreEqual(0, entries.Logs.Count); // // Order // findOptions = new FindOptions { Descending = false }; entries = await _usersApi.FindUserLogsAsync(user, findOptions); Assert.AreEqual(20, entries.Logs.Count); Assert.AreEqual("User Updated", entries.Logs[19].Description); Assert.AreEqual("User Created", entries.Logs[0].Description); }
/// <summary> /// Finds all entities according to the specified filter definition. /// </summary> /// <param name="filter">The filter.</param> /// <param name="options">The options.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> protected async Task <ICollection <TEntity> > FindAsync(FilterDefinition <TEntity> filter, FindOptions <TEntity> options = null, CancellationToken cancellationToken = default) { var collection = await GetCollectionAsync(cancellationToken); var cursor = await collection.FindAsync(filter, options, cancellationToken); return(await cursor.ToListAsync(cancellationToken)); }
private void AssertFindNext( SearchData data, string searchText, FindOptions options) { var isWrap = SearchKindUtil.IsWrap(data.Kind); var snapshot = MockObjectFactory.CreateTextSnapshot(10); var nav = _factory.Create<ITextStructureNavigator>(); var findData = new FindData(searchText, snapshot.Object, options, nav.Object); _textSearch .Setup(x => x.FindNext(2, isWrap, findData)) .Returns<SnapshotSpan?>(null) .Verifiable(); _search.FindNext(data, new SnapshotPoint(snapshot.Object, 2), nav.Object); _factory.Verify(); }
public async Task <IAsyncCursor <TDocument> > FindAsync(Expression <Func <TDocument, bool> > predicate, FindOptions <TDocument, TDocument> options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(await _collection.FindAsync(predicate, options, cancellationToken)); }