private static bool AtualizarRegistro(IMongoCollection<Cidade> cidades) { // Encontra o registro Cidade atualizaCidade = cidades.Find(c => c.Nome == "Charles Lomboni").ToList().First(); // Atualiza o valor do registro atualizaCidade.Estado = "RJ"; // Atualiza no mongo ReplaceOneResult estadoReplace = cidades.ReplaceOne(c => c._id == atualizaCidade._id, atualizaCidade); // Se tiver encontrado e atualizado será maior que zero return estadoReplace.ModifiedCount > 0; }
private static async Task FillData( dynamic profile, SqlConnection connection, IMongoCollection<BsonDocument> threadCollection, IMongoCollection<BsonDocument> threadProfiles) { var tags = connection.Query<string>(SqlQueryFactory.Instance.Get("get_thread_tags"), new { ThreadId = profile.Id }); var key = Builders<BsonDocument>.Filter.Eq("id", (profile.Id as string).Trim()); var match = await threadCollection.Find(key).Project("{url: 1, messages: 1, _id: 0}").SingleOrDefaultAsync(); var updateAction = Builders<BsonDocument>.Update .Set("create_on", (DateTime)profile.CreateOn) .Set("category", profile.Category as string) .Set("title", profile.Title as string) .Set("type", profile.Type as string); if (match != null) { var html = match.GetValue("messages") .AsBsonArray .FirstOrDefault() .AsBsonDocument .GetValue("body").AsString; var document = new HtmlAgilityPack.HtmlDocument(); document.LoadHtml(html); var text = document.DocumentNode.InnerText; var excerpt = text.Substring(0, Math.Min(256, text.Length)); updateAction = updateAction.Set("url", match.GetValue("url").AsString) .Set("excerpt", excerpt); } if (tags != null) { var tagArray = new BsonArray(tags.Select(m => m.ToLower()).ToList()); updateAction = updateAction.Set("tags", tagArray); } await threadProfiles.UpdateOneAsync("{'_id': '" + (profile.Id as string).Trim() + "'}", updateAction, new UpdateOptions { IsUpsert = true }); }
protected virtual IEnumerable<BsonDocument> GetDocuments(IMongoCollection<BsonDocument> collection) { var query = Filter(); var find = query != null ? collection.Find(query) : collection.Find(Builders<BsonDocument>.Filter.Empty); return find.ToList(); }
public void loadColors(IMongoCollection<board_item> coll, string boardName) { List<board_item> colors = coll.Find(brd => brd.Type == "Color" && brd.Board_Name == boardName) .ToListAsync() .Result; int i = 1; foreach (board_item color in colors) { if (i == 1) { colorPlace1.ImageUrl = color.Image_Link; i++; colorPlace2.ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Solid_white.svg/2000px-Solid_white.svg.png"; } else if (i == 2) { colorPlace2.ImageUrl = color.Image_Link; i++; colorPlace3.ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Solid_white.svg/2000px-Solid_white.svg.png"; } else if (i == 3) { colorPlace3.ImageUrl = color.Image_Link; } } }
private async void NewMethod(IMongoCollection<BsonDocument> collection) { var list = await collection.Find(_ => true).ToListAsync(); foreach (var item in list) { } }
protected virtual IEnumerable<BsonDocument> GetDocuments(IMongoCollection<BsonDocument> collection) { var query = Filter(); if (query != null) { return query.ToList(); } return collection.Find(Builders<BsonDocument>.Filter.Empty).ToList(); }
public async Task <OrderSummeryViewModel> GetOrderAsync(int orderId) { //var filter = new BsonDocument() {{"orderId", orderId}}; try { var documents = await collection?.Find(e => e.OrderId == orderId)?.FirstOrDefaultAsync(); if (documents != null) { return(ToOrderSummeryViewModel(documents)); } return(null); } catch (Exception ex) { logger.LogError("$Method:GetOrderAsync - Error while querying doc from Mongo " + ex.Message); throw new Exception(ex.Message); } }
async private Task <IEnumerable <BsonDocument> > Find(FilterDefinition <BsonDocument> filter) { var documents = default(IEnumerable <BsonDocument>); if (filter != null) { documents = await CollectionInformation?.Find(filter).ToListAsync(); } return(documents); }
static async Task FindCustomer(IMongoCollection<Customer> collection) { //creates a filter to find Bson Document var filter = Builders<Customer>.Filter.Eq(c => c.FirstName, "John"); //runs the query to find it var query = await collection.Find(filter).ToListAsync(); //gets the customer var customer = query.FirstOrDefault(); //displays the customer using C# 6.0 string formatter Console.WriteLine($"Customer {customer.FirstName} {customer.LastName} is found!"); }
/// <summary> /// Finds phones in database using a name. /// </summary> /// <returns>The phone.</returns> /// <param name="collection">Collection.</param> private static async Task FindPhone(IMongoCollection<PhoneBookRecord> collection) { Console.WriteLine("Enter a name"); string name = Console.ReadLine(); var filter = Builders<PhoneBookRecord>.Filter.Eq("Name", name); var names = await collection.Find(filter).ToListAsync(); foreach (var n in names) { Console.WriteLine(n.Phone); } }
private static async Task<List<int>> LoadUids(IMongoCollection<BsonDocument> collection, int uidKey) { var uid0 = uidKey * 0x1000000; var uid1 = uid0 + 0xFFFFFF; var uids = new List<int>(); await collection .Find(Builders<BsonDocument>.Filter.Gte("_id", uid0) & Builders<BsonDocument>.Filter.Lte("_id", uid1)) .Project(Builders<BsonDocument>.Projection.Include("_id")) .ForEachAsync(x => uids.Add((int)x["_id"])); return uids; }
private static void GetAllDrinks(IMongoCollection<EnergyDrink> collection) { Console.Clear(); var rest = collection.Find(_ => true); foreach (var item in rest.ToListAsync().Result) { Console.WriteLine("Name: {0} => Price: {1}", item.Name, item.Price); } Console.WriteLine("\nPress any key to continue.."); Console.ReadLine(); }
static async Task findDocuments(IMongoCollection<student> collection, FilterDefinition<student> searchFilter) { //Option 1: for iterting over many documents on the server. Console.WriteLine("--------------------------------------------------------------------"); ///using (var cursor = await collection.Find(searchFilter).Sort("{student_id:1, scores.type:1}").ToCursorAsync()) using (var cursor = await collection.Find(searchFilter).ToCursorAsync()) { using (StreamWriter w = File.AppendText("c:\\data\\hw31.txt")) { while (await cursor.MoveNextAsync()) //iterate over each batch { foreach (var doc in cursor.Current) { double minHWScore = 100.0; ///string text = i + " :=> sid: " + doc.student_id + ":" + doc.scores.ToString(); List<studentscore> thisStudentScores = doc.scores.ToList(); foreach (studentscore s in thisStudentScores) { if (s.type.Equals("homework")) { if (s.score < minHWScore) { minHWScore = s.score; } } } studentscore[] newScores = thisStudentScores.Where((x) => x.score != minHWScore).ToArray<studentscore>(); doc.scores = newScores.ToArray<studentscore>(); var filter = Builders<student>.Filter.Eq("Id", doc.Id); await collection.ReplaceOneAsync(filter, doc); Console.WriteLine(doc.ToString()); w.WriteLine(doc.ToString()); /** if (i % 4 == 0) { Console.WriteLine("lowest score for " + doc.student_id + " is " + doc.score); w.WriteLine("lowest score for " + doc.student_id + " is " + doc.score); await collection.DeleteOneAsync(a => a.Id == doc.Id); } i++; **/ } } } } }
public void updateUser(UserDTO user) { var dataUser = UsersDB?.Find((x => x.userID == user.userID))?.FirstOrDefault(); if (dataUser == null || user.userID != dataUser.userID) { // Create New User UsersDB.InsertOneAsync(user); } else { // Edit Existing Use UsersDB.ReplaceOneAsync(arg => arg.userID == user.userID, user); } }
private static void FindByName(IMongoCollection<Note> collection) { Console.Write("Введите имя для поиска: "); string name = Console.ReadLine(); var list = collection.Find(new BsonDocument()).ToList(); int count = 0; foreach (var node in list) if (node.Name == name) { ++count; Console.WriteLine($"Его номер ({count}): {node.Number}"); } if (count == 0) Console.WriteLine("Ничего не найдено"); }
private static void AddNewNote(IMongoCollection<Note> collection) { Console.Write("Введите номер: "); string newNumber = Console.ReadLine(); Console.Write("Введите имя: "); string newName = Console.ReadLine(); var list = collection.Find(new BsonDocument()).ToList(); foreach (var node in list) if (node.Number == newNumber) { Console.WriteLine("Такой номер уже записан под именем " + node.Name); return; } collection.InsertOne(new Note { Name = newName, Number = newNumber }); Console.WriteLine("Запись добавлена"); }
public override async void Start() { base.OnceTime = true; // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname String uri = "mongodb://[petahost2.ns.co.th:27017/travox-mbos"; var client = new MongoClient(uri); db = client.GetDatabase("travox-mbos"); oAuth = db.GetCollection<BsonDocument>("oAuth"); await oAuth.Find(filter).ForEachAsync(song => Console.WriteLine("In the {0}, {1} by {2} topped the charts for {3} straight weeks", song["Decade"], song["Title"], song["Artist"], song["WeeksAtOne"]) ); base.Start(); }
private static void FindAllAndPrint(IMongoCollection<Category> coll, string name) { var results = coll.Find(t => t.Name == name) .Limit(10) .ToListAsync().Result; Console.Write("List of categories\n**************************\n"); foreach (var result in results) { Console.WriteLine("Name : " + result.Name); Console.WriteLine("Description : " + result.Description); Console.WriteLine(); } foreach (var expensse in results.SelectMany(t => t.Expenses)) { Console.WriteLine("Amount : " + expensse.Amount); Console.WriteLine("Date : " + expensse.Date); Console.WriteLine("Transaction : " + expensse.Transaction); } }
static void Query(IMongoCollection<BsonDocument> col) { //查询,同步,异步 //Find the First Document in a Collection var doc = col.Find(new BsonDocument()).FirstOrDefault(); //var document = await collection.Find(new BsonDocument()).FirstOrDefaultAsync(); Console.WriteLine(doc); //Find All Documents in a Collection var documents = col.Find(new BsonDocument()).ToList(); foreach(var document in documents) { Console.WriteLine(document); } //var documents = await collection.Find(new BsonDocument()).ToListAsync(); //await collection.Find(new BsonDocument()).ForEachAsync(d => Console.WriteLine(d)); var cursor = col.Find(new BsonDocument()).ToCursor(); foreach(var document in cursor.ToEnumerable()) { Console.WriteLine(document); } //选择条件 var builder = Builders<BsonDocument>.Filter; var filter = builder.Gt("score", 50) & builder.Lte("score", 100); cursor = col.Find(filter).ToCursor(); //排序 var sortFilter = Builders<BsonDocument>.Sort.Descending("score").Ascending("type"); cursor = col.Find(filter).Sort(sortFilter).Skip(2).Limit(2).ToCursor(); //投影 var projectFilter = Builders<BsonDocument>.Projection.Exclude("_id").Include("type"); cursor = col.Find(filter).Project(projectFilter).ToCursor(); }
public void loadPatterns(IMongoCollection<board_item> coll, string boardName) { List<board_item> patterns = coll.Find(brd => brd.Type == "Pattern" && brd.Board_Name == boardName) .ToListAsync() .Result; int i = 1; foreach (board_item pattern in patterns) { if (i == 1) { patternPlace1.ImageUrl = pattern.Image_Link; i++; } else if (i == 2) { patternPlace2.ImageUrl = pattern.Image_Link; i++; } else if (i == 3) { patternPlace3.ImageUrl = pattern.Image_Link; } } }
public T ObtenerPorId(object id) { return(_collection.Find(f => f.Id == id).FirstOrDefault()); }
/// <summary> /// [MONGODB-DEMO] Find all the documents (SQL=row) in the collection (SQL=table) + sort\filtering\limitation. /// </summary> private static async Task FindAllAsync(IMongoCollection<BsonDocument> collection) { Console.WriteLine("\nFind all the documents (SQL=row) in the collection (SQL=table) :"); var filter = new BsonDocument(); // Empty filter -> Find ALL. //var list = await collection.Find("{ Name: 'Sergii' }").ToListAsync(); var list = await collection.Find(filter) .Sort( Builders<BsonDocument>.Sort.Ascending("_id").Descending("Name") ) .Limit(22) .ToListAsync(); foreach (var doc in list) { Console.WriteLine(" " + doc); } Console.WriteLine(); }
/// <summary> /// Returns a list of <see cref="MiniProfiler.Id"/>s that haven't been seen by <paramref name="user"/>. /// </summary> /// <param name="user">User identified by the current <see cref="MiniProfiler.User"/>.</param> public List <Guid> GetUnviewedIds(string user) => _collection.Find(p => p.User == user && !p.HasUserViewed).Project(p => p.Id).ToList();
public HighScore GetHighScore(string playerUserName) { return(_highScores?.Find(highScore => highScore.PlayerUserName == playerUserName).SingleOrDefault()); }
public IEnumerable <GreetingHistory> GetAll() { return(_collection.Find(_ => true).ToList()); }
public List <Product> Get() { return(_products.Find(product => true).ToList()); }
public List <Message> GetAll() { return(collection.Find(x => true).ToList()); }
public async Task <User> GetByIdAsync(string id) => await _context.Find <User>(user => user.Id == id).FirstOrDefaultAsync();
public List <ClientCompany> Get() => _client.Find(x => true).ToList();
public async Task <List <SkillEntity> > GetSkillsAsync(CancellationToken ct = default) => await _skillCollection .Find(new BsonDocument()) .ToListAsync(ct);
public List <PointAccount> Get() => _points.Find(point => true).ToList();
public ActionResult ObterInfectados() { var infectados = _infectadosCollection.Find(Builders <Infectado> .Filter.Empty).ToList(); return(Ok(infectados)); }
public List <Phrase> Get() => _phrases.Find <Phrase>(phrase => true).ToList();
public void loadRooms(IMongoCollection<board_item> coll, string boardName) { List<board_item> rooms = coll.Find(brd => brd.Type == "LivingRoom" && brd.Board_Name == boardName) .ToListAsync() .Result; int i = 1; foreach (board_item room in rooms) { if (i == 1) { roomPlace1.ImageUrl = room.Image_Link; i++; } else if (i == 2) { roomPlace2.ImageUrl = room.Image_Link; i++; } else if (i == 3) { roomPlace3.ImageUrl = room.Image_Link; } } }
public List <User> Get() => _user.Find(User => true).ToList();
public void loadRugs(IMongoCollection<board_item> coll, string boardName) { List<board_item> rugs = coll.Find(brd => brd.Type == "Rugs" && brd.Board_Name == boardName) .ToListAsync() .Result; int i = 1; foreach (board_item rug in rugs) { if (i == 1) { rugPlace1.ImageUrl = rug.Image_Link; i++; } else if (i == 2) { rugPlace2.ImageUrl = rug.Image_Link; i++; } else if (i == 3) { rugPlace3.ImageUrl = rug.Image_Link; } } }
public List <User> GetUsers() { return(_users.Find(user => true).ToList()); }
public void loadOttomans(IMongoCollection<board_item> coll, string boardName) { List<board_item> ottomans = coll.Find(brd => brd.Type == "Ottoman" && brd.Board_Name == boardName) .ToListAsync() .Result; int i = 1; foreach (board_item otm in ottomans) { if (i == 1) { ottomanPlace1.ImageUrl = otm.Image_Link; i++; } else if (i == 2) { ottomanPlace2.ImageUrl = otm.Image_Link; i++; } else if (i == 3) { ottomanPlace3.ImageUrl = otm.Image_Link; } } }
public Task <ApplicationProperty> GetAsync() { var filter = Builders <ApplicationProperty> .Filter.Empty; return(_collection.Find(filter).SingleOrDefaultAsync()); }
public List <AccessoryReceipt> Get() => _accessoryReceipt.Find(accessoryReceipt => true).ToList();
protected product_image findItemAddToBoard(string link, IMongoCollection<product_image> coll) { product_image p = new product_image(); List<product_image> items = coll.Find(itm => itm.Image_Link == link) .ToListAsync() .Result; foreach (product_image itm in items) { p = itm; } return p; }
public Task <bool> ExistsAsync(Expression <Func <TAggregateRoot, bool> > predicate, CancellationToken cancellationToken = default) { AssertPredicate(predicate); return(_collection.Find(predicate).AnyAsync(cancellationToken)); }
public List <UserProfile> Get() => _profile.Find(profile => true).ToList();
public List <Factura> Get() { return(_facturas.Find(factura => true).ToList <Factura>()); }
public async Task <Player> GetPlayer(Guid id) { var filter = Builders <Player> .Filter.Eq(player => player.Id, id); return(await _playerCollection.Find(filter).FirstAsync()); }
private Task<List<BsonDocument>> GetCollectionDocumentsAsync(IMongoCollection<BsonDocument> collection) { return collection.Find(new BsonDocument()).ToListAsync(); }
/// <summary> /// The conflicts workload writes to all regions concurrently until a certain number of conflicts have been examined. /// </summary> private static async Task ExecuteConflictsWorkloadAsync(IReadOnlyList <MongoClient> mongoClients, Guid runGuid) { int documentsRemaining = 1000; int conflictsRemaining = 3; int id = 0; Console.WriteLine($"Writing up to {documentsRemaining} documents to all regions to generate and examine up to {conflictsRemaining} conflicts..."); while (conflictsRemaining > 0 && documentsRemaining > 0) { documentsRemaining--; string currentId = $"{runGuid}:{id}"; Task <BsonDocument>[] writeTasks = mongoClients .Select(async mongoClient => { IMongoDatabase mongoDatabase = mongoClient.GetDatabase(ConfigurationManager.AppSettings["database"]); IMongoCollection <BsonDocument> mongoCollection = mongoDatabase.GetCollection <BsonDocument>(ConfigurationManager.AppSettings["collection"]); ServerDescription primaryServerDescription = mongoClient.Cluster.Description.Servers.First(x => x.Type == ServerType.ReplicaSetPrimary); string region = Helpers.TryGetRegionFromTags(primaryServerDescription.Tags) ?? string.Empty; BsonDocument toInsert = new BsonDocument( (IEnumerable <BsonElement>) new[] { new BsonElement("_id", new BsonString(currentId)), new BsonElement("writtenFrom", new BsonString(region)), }); await Task.Yield(); await mongoCollection.InsertOneAsync(toInsert); return(toInsert); }) .ToArray(); try { await Task.WhenAll(writeTasks); } catch (MongoWriteException) { // When a conflict does not occur, one write will fail with a duplicate _id error // This exception is expected, unless a conflict occurred. // In a conflict scenario, writes will succeed to multiple regions even with the // same _id, and the winning write will be chosen with conflict resolution. } Task <BsonDocument>[] completedSuccessfully = writeTasks.Where(x => x.Status == TaskStatus.RanToCompletion).ToArray(); if (completedSuccessfully.Length > 1) { await Task.Delay(1000); Console.WriteLine(); Console.WriteLine("Conflict happened! These documents all written successfully to different regions: "); foreach (Task <BsonDocument> success in completedSuccessfully) { #pragma warning disable AsyncFixer02 // Long running or blocking operations under an async method Console.WriteLine(" " + success.Result.ToString()); #pragma warning restore AsyncFixer02 // Long running or blocking operations under an async method } // Conflict resolution is based on the server-side timestamp of the write // In a conflict scenario, the document with the latest timestamp wins // The timestamp depends on the server-side clock in each region and as is not // currently exposed through the MongoDB API Console.WriteLine("Winner: "); IMongoDatabase mongoDatabase = mongoClients[0].GetDatabase(ConfigurationManager.AppSettings["database"]); IMongoCollection <BsonDocument> mongoCollection = mongoDatabase.GetCollection <BsonDocument>(ConfigurationManager.AppSettings["collection"]); BsonDocument winner = (await mongoCollection.Find(x => x["_id"] == currentId).ToListAsync())[0]; Console.WriteLine(" " + winner.ToString()); conflictsRemaining--; } id++; } Console.WriteLine("Complete."); }
public Task <TEntity> GetAsync(TKey id) => _collection.Find(d => d.Id.Equals(id)).SingleOrDefaultAsync();
public async Task <IEnumerable <TModel> > Find(Expression <Func <TModel, bool> > filter) { return(await _collection.Find(filter).ToListAsync()); }
public List <Product> Get() => _products.Find(product => true).ToList();
public List <User> GetUsers() => _users.Find(user => true).ToList();
static async Task findDocuments(IMongoCollection<Person> collection, FilterDefinition<Person> searchFilter) { //Option 1: for iterting over many documents on the server. Console.WriteLine("--------------------------------------------------------------------"); using (var cursor = await collection.Find(searchFilter).Skip(1).Limit(1).ToCursorAsync()) { while (await cursor.MoveNextAsync()) //iterate over each batch { foreach (var doc in cursor.Current) { Console.WriteLine("OPT 1:" + doc.ToBsonDocument().ToString()); } } } Console.WriteLine("--------------------------------------------------------------------"); //Option 2: for listing documents on the server. var list = await collection.Find(x => x.Name == "jones" && x.Age <= 31).ToListAsync(); foreach (var doc in list) { Console.WriteLine("OPT 2:" + doc.ToBsonDocument().ToString()); } Console.WriteLine("--------------------------------------------------------------------"); // Option 3: using the ForEachAsynch() with a lambda function, projection, sort, and expression trees. await collection.Find(searchFilter) .Sort("{Age:-1}") .Project(Builders<Person>.Projection.Include(x => x.Name).Include(x=>x.Age).Exclude("_id")) .ForEachAsync(doc => Console.WriteLine("OPT 3:" + doc.ToBsonDocument().ToString())); //Option 4: Option 3 with a anonymous function to do a general calc client side. await collection.Find(searchFilter) .Sort("{Age:-1}") .Project((x => new {x.Name, CalcAge = x.Age + 20})) .ForEachAsync(doc => Console.WriteLine("OPT 4:" + doc.ToBsonDocument().ToString())); }
public Entities.File GetById(object id) { return(_files.Find(file => file.Id == id.ToString()).FirstOrDefault()); }
/// <summary> /// Finds names in database using a phone. /// </summary> /// <returns>The name.</returns> /// <param name="collection">Collection.</param> private static async Task FindName(IMongoCollection<PhoneBookRecord> collection) { Console.WriteLine("Enter a phone"); string phone = Console.ReadLine(); var filter = Builders<PhoneBookRecord>.Filter.Eq("Phone", phone); var phones = await collection.Find(filter).ToListAsync(); foreach (var p in phones) { Console.WriteLine(p.Name); } }
public IEnumerable <Player> GetPlayers() { return(_players?.Find(new BsonDocument()).ToEnumerable()); }
private async Task DoWork(IMongoCollection<BsonDocument> collection) { var rand = new Random(); while (!_cancellationTokenSource.IsCancellationRequested) { var i = rand.Next(0, 10000); List<BsonDocument> docs; try { docs = await collection.Find(new BsonDocument("i", i)) .ToListAsync(_cancellationTokenSource.Token); } catch { Console.Write("+"); continue; } if (docs.Count == 0) { try { await collection.InsertOneAsync(new BsonDocument("i", i), _cancellationTokenSource.Token); } catch { Console.Write("*"); } } else { try { var filter = new QueryDocument("_id", docs[0]["_id"]); var update = new UpdateDocument("$set", new BsonDocument("i", i + 1)); await collection.UpdateOneAsync(filter, update, cancellationToken: _cancellationTokenSource.Token); //Console.Write("."); } catch (Exception) { Console.Write("*"); } } } }
public void CreatePdf(IQueryable<string> test, IMongoCollection<infoDept> collection, string dates, bool type, string path) { DateTime now = DateTime.Now; var oneweekAffter = now.AddDays(7); Document document = new Document(PageSize.A1, 5, 5, 155, 15); int Id = 0; string filepath = path + "\\" + "Asistance_Report_LNO-HN" + "_" + dates + ".pdf"; if ((!System.IO.File.Exists(filepath))) { using (FileStream output = new FileStream((filepath), FileMode.Create)) { using (PdfWriter writer = PdfWriter.GetInstance(document, output)) { document.Open(); foreach (var items in test) { var managers = collection .Find(a => a.Id_Dept == items) .ToListAsync() .Result; foreach (var i in managers) { List<Getreport> get = new List<Getreport>(i.GetReport); foreach (var sub in get) { Id = Convert.ToInt32(sub.deptID); PdfPTable table = new PdfPTable(24); table.TotalWidth = 5000f; if (oneweekAffter.Month != now.Month) { //document.Add(ArchiveSpin4(table, Id, sub.subdept, dates, type)); document.Add(archive(table, Id, sub.subdept, dates, type)); } else { document.Add(archive(table, Id, sub.subdept, dates, type)); } } } } document.Close(); output.Close(); } } } Id = 0; foreach (var items in test) { var managers = collection .Find(a => a.Id_Dept == items) .ToListAsync() .Result; foreach (var i in managers) { for (var y = 0; y < i.Name.Length; y++) { if (oneweekAffter.Month != now.Month) { Console.WriteLine("ultimo lunes ................................"); filepath = path + "\\Asistance_Report_All_" + i.Nombre_Dept + "_" + dates + ".pdf"; if ((!System.IO.File.Exists(filepath))) { using (FileStream output = new FileStream((filepath), FileMode.Create)) { Document Alldocument = new Document(PageSize.A1, 5, 5, 155, 15); using (PdfWriter writer = PdfWriter.GetInstance(Alldocument, output)) { Alldocument.Open(); List<Getreport> get = new List<Getreport>(i.GetReport); foreach (var sub in get) { Id = Convert.ToInt32(sub.deptID); PdfPTable table = new PdfPTable(24); table.TotalWidth = 5000f; // Alldocument.Add(ArchiveSpin4(table, Id, sub.subdept, dates, type)); Alldocument.Add(archive(table, Id, sub.subdept, dates, type)); } Alldocument.Close(); output.Close(); } } } } else { Console.WriteLine(" no es el ultimo lunes del mes................................"); filepath = path + "\\Asistance_Report_All" + i.Nombre_Dept + "_" + dates + ".pdf"; if ((!System.IO.File.Exists(filepath))) { using (FileStream output = new FileStream((filepath), FileMode.Create)) { Document Alldocument = new Document(PageSize.A1, 5, 5, 155, 15); using (PdfWriter writer = PdfWriter.GetInstance(Alldocument, output)) { Alldocument.Open(); List<Getreport> get = new List<Getreport>(i.GetReport); foreach (var sub in get) { Id = Convert.ToInt32(sub.deptID); PdfPTable table = new PdfPTable(24); table.TotalWidth = 5000f; //archive Alldocument.Add(archive(table, Id, sub.subdept, dates, type)); } Alldocument.Close(); output.Close(); } } } } /* filepath = path + "\\Asistance_Report_All" + i.Nombre_Dept + "_" + dates + ".pdf"; if ((!System.IO.File.Exists(filepath))) { using (FileStream output = new FileStream((filepath), FileMode.Create)) { Document Alldocument = new Document(PageSize.A1, 5, 5, 155, 15); using (PdfWriter writer = PdfWriter.GetInstance(Alldocument, output)) { Alldocument.Open(); List<Getreport> get = new List<Getreport>(i.GetReport); foreach (var sub in get) { Id = Convert.ToInt32(sub.deptID); PdfPTable table = new PdfPTable(24); table.TotalWidth = 5000f; Alldocument.Add(archive(table, Id, sub.subdept, dates, type)); } Alldocument.Close(); output.Close(); } } } */ } } } }
static async Task findDocuments(IMongoCollection<student> collection, FilterDefinition<student> searchFilter) { //Option 1: for iterting over many documents on the server. Console.WriteLine("--------------------------------------------------------------------"); using (var cursor = await collection.Find(searchFilter) .Sort("{student_id:1, score:-1}") .ToCursorAsync()) { int i = 1; using (StreamWriter w = File.AppendText("c:\\data\\test2.txt")) { while (await cursor.MoveNextAsync()) //iterate over each batch { foreach (var doc in cursor.Current) { string text = i + " :=> sid: " + doc.student_id + ":" + doc.score; Console.WriteLine(text); w.WriteLine(text); if (i % 4 == 0) { Console.WriteLine("lowest score for " + doc.student_id + " is " + doc.score); w.WriteLine("lowest score for " + doc.student_id + " is " + doc.score); await collection.DeleteOneAsync(a => a.Id == doc.Id); } i++; } } } } }
public void loadColors(IMongoCollection<board_item> coll, string boardName) { List<board_item> colors = coll.Find(brd => brd.Type == "Color" && brd.Board_Name == boardName) .ToListAsync() .Result; int i = 1; foreach (board_item color in colors) { if (i == 1) { colorPlace1.ImageUrl = color.Image_Link; i++; } else if (i == 2) { colorPlace2.ImageUrl = color.Image_Link; i++; } else if (i == 3) { colorPlace3.ImageUrl = color.Image_Link; } } }
private static void SearchByName(IMongoCollection<EnergyDrink> collection) { Console.Clear(); Console.Write("Enter the name:"); var inputName = Console.ReadLine(); var fileter = Builders<EnergyDrink>.Filter.Eq("Name", inputName); var result = collection.Find(fileter).ToListAsync().Result; if (result.Count == 0) { Console.WriteLine("\nThere are no drinks with name {0}", inputName); } else { foreach (var item in result) { Console.WriteLine("Name: {0} => Price: {1}", item.Name, item.Price); } } Console.WriteLine("\nPress any key to continue.."); Console.ReadLine(); }