public void GetSteps(String userId) { var filterBuilder = new FilterDefinitionBuilder<AuthenticationToken>(); var filter = filterBuilder.Where(i => i.UserId.Equals(userId)); var user = _mongoRepository.Get<AuthenticationToken>(filter).FirstOrDefault(); if (user != null) { StepsModel steps = null; using (var client = new WebClient()) { client.Headers.Add("Authorization", "Bearer " + user.Token); client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; var url = $"https://api.fitbit.com/1/user/{user.ServiceUserId}/activities/date/{DateTime.Today.ToString("yyyy-MM-dd")}.json"; dynamic activity = Json.Decode(client.DownloadString(url)); steps = new StepsModel { Date = DateTime.Today, Count = activity.summary.steps, UserId = userId }; } _mongoRepository.Insert(steps); } }
public async Task <MongoExternalUser> AutoProvisionUser(string provider, string userId, List <Claim> claims) { var filter = Filters.Where(x => x.UsernameNormalized == userId.ToLowerInvariant().Normalize()); var numberOfUsersWithUsername = await collection.CountAsync(filter); if (numberOfUsersWithUsername > 0) { throw new UserExistsException(); } var nameClaim = ClaimsFinder.ResolveNameClaim(userId, claims); var emailClaim = claims.ResolveEmailClaim(); var user = new MongoExternalUser { ProviderId = userId, Username = nameClaim?.Value, Email = emailClaim.Value, ProviderKey = provider, Claims = claims.Select(x => new MongoClaim(x)).ToList() }; user.SetMongoInternals(); await collection.InsertOneAsync(user); return(user); }
private async Task <bool> SaveSystemMessages() { var ptBR = Messages["pt-br"]; var en = Messages["en"]; var es = Messages["es"]; var filter = new FilterDefinitionBuilder <SystemMessages>(); var msgCol = IlevusDatabase.GetCollection <SystemMessages>(IlevusTableNames.SystemMessagesTable); var result = await msgCol.ReplaceOneAsync(filter.Where((msg) => msg.Id == ptBR.Id), ptBR); if (result.MatchedCount == 0) { return(false); } result = await msgCol.ReplaceOneAsync(filter.Where((msg) => msg.Id == en.Id), en); if (result.MatchedCount == 0) { return(false); } result = await msgCol.ReplaceOneAsync(filter.Where((msg) => msg.Id == es.Id), es); if (result.MatchedCount == 0) { return(false); } return(true); }
protected override async Task <TEntity> OnUpdateAsync(TEntity entity, Expression <Func <TEntity, bool> > filter) { var filterDefinition = _filterDefinitionBuilder.Where(filter); await _collection.ReplaceOneAsync(filterDefinition, entity); return(entity); }
/// <summary> /// Get By Id. /// </summary> /// <param name="id"></param> public async Task <ShelveDTO> GetShelveById(string id) { var applyFilter = _builderFilter.Where(book => book.Id == id); var result = await _context.ShelveCollection.Find(applyFilter).FirstOrDefaultAsync(); if (result is null) { throw new NotFoundException("the shelve id '" + id + "' can't be found"); } return(_mapper.Map <ShelveDTO>(result)); }
public List <BsonDocument> GetRoleWithFilter(string searchKey) { var filter = Builder.Or( Builder.Where(x => x.RoleCode.ToLower().Contains(searchKey)), Builder.Where(x => x.RoleName.ToLower().Contains(searchKey)) ); var data = _Role.Aggregate() .Match(filter) .Lookup("Permission", "PermissionId", "_id", "Permission") .ToList(); return(data); }
public User GetUserByName(string username) { var filter = filterBuilder.Where(x => x.Name == username); var result = dbService.Query(filter).Result; if (result.Count > 0) { return(result[0]); } else { return(new User()); } }
/// <summary> /// Audits the item based on the sent id and collection /// </summary> /// <remarks>Error codes follow the format DAL-DMB-4XX</remarks> /// <typeparam name="T">The type of the object to audit</typeparam> /// <param name="items">An IEnumerable list of items to audit</param> /// <param name="auditCollectionName">The collection name for the audit</param> /// <param name="auditSettingsKey">Optional audit setting key to reference the AuditSettings dictionary</param> /// <param name="auditUser">Optional string for the audit user</param> /// <param name="auditCapSize">Optional int to set the audit cap size</param> public async Task AuditItems(string[] ids, string collectionName, string auditCollectionName, string auditSettingsKey = null, string auditUser = null, int auditCapSize = 100) { //set audit by default value item has not yet been created bool auditItem = AuditByDefault; if (auditItem) { //check the audit settings allow try { auditItem = (!String.IsNullOrEmpty(auditSettingsKey) && AuditSettings != null && AuditSettings.ContainsKey(auditSettingsKey)) ? bool.Parse(AuditSettings[auditSettingsKey]) : auditItem; } catch { } } //audit item if set if (auditItem) { try { auditCapSize = (!String.IsNullOrEmpty(auditCollectionName + ".Size") && AuditSettings != null && AuditSettings.ContainsKey(auditCollectionName + ".Size")) ? int.Parse(AuditSettings[auditCollectionName + ".Size"]) : auditCapSize; } catch { } FilterDefinitionBuilder <BaseIdWithQuickSearchModel> filterBuilder = Builders <BaseIdWithQuickSearchModel> .Filter; var filter = filterBuilder.Empty; filter = filter & filterBuilder.Where(w => ids.Contains(w.Id)); var collection = Repository.Database.GetCollection <BaseIdWithQuickSearchModel>(collectionName); var items = await collection.Find(filter).ToListAsync <BaseIdWithQuickSearchModel>(); foreach (var item in items) { await AuditManager.AuditItem <BaseIdWithQuickSearchModel>(Repository.Database, item, false, auditCollectionName, auditUser, auditCapSize); } } }
/// <summary> /// Find /// </summary> /// <param name="requestFilter"></param> /// <returns></returns> public async Task <IEnumerable <ArticleContent> > Find(ConditionFilter requestFilter) { var skip = 0; var take = 10; var filterDefinition = new FilterDefinitionBuilder <ArticleContent>(); var filter = filterDefinition.Eq(x => x.ContentType, requestFilter.ContentType); if (!requestFilter.Brand.IsNullOrEmpty()) { filter = filter & filterDefinition.Where(x => x.Brand.Contains(requestFilter.Brand)); } if (!requestFilter.Category.IsNullOrEmpty()) { filter = filter & filterDefinition.Eq(x => x.Category.Parent, requestFilter.Category); } if (!requestFilter.Language.IsNullOrEmpty()) { filter = filter & filterDefinition.Eq(x => x.Market, requestFilter.Language); } skip = take * (requestFilter.Page - 1); return(await _repository.FindAsync <ArticleContent>(filter, orderBy : x => x.GetOrderFor(requestFilter.Ordering), skip : skip, take : take)); }
/// <summary> /// Update Error status to the Krawler DB /// </summary> /// <param name="projectId"></param> /// <param name="error"></param> public static void UpdateCrawlErrorMessage(string projectId, KrawlError error) { try { if (_server == null) { InitiateConnection(); } var urlCollection = _kitsuneDB.GetCollection <KitsuneKrawlerStats>(EnvironmentConstants.ApplicationConfiguration.MongoDBCollections.KitsuneKrawlStatsCollection); //Filter Defination var fdb = new FilterDefinitionBuilder <KitsuneKrawlerStats>(); var filter = fdb.Where(x => x.ProjectId == projectId); //Update Defination var udb = new UpdateDefinitionBuilder <KitsuneKrawlerStats>(); var update = udb.Set(x => x.Stage, KitsuneKrawlerStatusCompletion.Error) .Set(x => x.IsLocked, false) .Set(x => x.Error, error); //Process var result = urlCollection.UpdateOne(filter, update); APIHelper.UpdateKitsuneProjectsStatus(projectId, ProjectStatus.ERROR); } catch (Exception ex) { //TODO:Log } }
/// <summary> /// Update Stage in DB /// and lock the project /// </summary> /// <param name="crawlId"></param> /// <param name="resources"></param> /// <returns></returns> public static bool UpdateCrawlStatsStage(string crawlId, KitsuneKrawlerStatusCompletion stage) { try { if (_server == null) { InitiateConnection(); } var urlCollection = _kitsuneDB.GetCollection <KitsuneKrawlerStats>(EnvironmentConstants.ApplicationConfiguration.MongoDBCollections.KitsuneKrawlStatsCollection); //Filter Defination var fdb = new FilterDefinitionBuilder <KitsuneKrawlerStats>(); var filter = fdb.Where(x => x.ProjectId == crawlId); //Update Defination var udb = new UpdateDefinitionBuilder <KitsuneKrawlerStats>(); var update = udb.Set(x => x.Stage, stage) .Set(x => x.IsLocked, false); //Process var result = urlCollection.UpdateOne(filter, update); return(true); } catch (Exception ex) { return(false); } }
/// <summary> /// Update the Styles,Scripts and Assets Details to KitsuneProjects DB /// </summary> /// <param name="crawlId"></param> /// <param name="resources"></param> /// <returns></returns> public static bool UpdateTheDownloadStageDetailsInDB(string crawlId, DownloadResourceContext resources) { try { if (_server == null) { InitiateConnection(); } var urlCollection = _kitsuneDB.GetCollection <KitsuneKrawlerStats>(EnvironmentConstants.ApplicationConfiguration.MongoDBCollections.KitsuneKrawlStatsCollection); //Filter Defination var fdb = new FilterDefinitionBuilder <KitsuneKrawlerStats>(); var filter = fdb.Where(x => x.ProjectId == crawlId); //Update Defination var udb = new UpdateDefinitionBuilder <KitsuneKrawlerStats>(); var update = udb.Set(x => x.Scripts, resources.Scripts.ToList()) .Set(x => x.Styles, resources.Styles.ToList()) .Set(x => x.Assets, resources.Assets.ToList()); //Process var result = urlCollection.UpdateOne(filter, update, new UpdateOptions { IsUpsert = true }); return(true); } catch (Exception ex) { throw ex; } }
public static async Task UpdateDBForPlaceHolderReplacer(string projectId) { try { if (_server == null) { InitiateConnection(); } var urlCollection = _kitsuneDB.GetCollection <KitsuneKrawlerStats>(EnvironmentConstants.ApplicationConfiguration.MongoDBCollections.KitsuneKrawlStatsCollection); //Filter Defination var fdb = new FilterDefinitionBuilder <KitsuneKrawlerStats>(); var filter = fdb.Where(x => x.ProjectId == projectId); //Update Defination var udb = new UpdateDefinitionBuilder <KitsuneKrawlerStats>(); UpdateDefinition <KitsuneKrawlerStats> update = udb.Inc(x => x.LinksReplaced, 1); //Process var result = await urlCollection.UpdateOneAsync(filter, update); } catch (Exception ex) { Log.Error(ex, $"ProjectId:{projectId}, Message:Error updating the Link processed"); } }
public Cliente Update(Cliente cliente) { FilterDefinitionBuilder <Cliente> filtro = new FilterDefinitionBuilder <Cliente>(); _db.Collection.ReplaceOne(filtro.Where(c => c.id == cliente.id), cliente); return(cliente); }
//幂等操作 private void RollbackOperations(TransactionDocumentP t, string source, string destination) { //1 将事务文档状态由pending更新为canceling. ReUpdateTransactionState(t, "pending", "canceling", new TimeSpan(0, 0, 100)); //2 账户余额回滚. FilterDefinitionBuilder <AccountP> filterBuilderS = Builders <AccountP> .Filter; FilterDefinition <AccountP> filterS1 = filterBuilderS.Eq(doc => doc._id, t.Source);//source FilterDefinition <AccountP> filterS2 = filterBuilderS.Where(doc => doc.PendingTransactions.Contains(t._id)); FilterDefinition <AccountP> filterS = filterBuilderS.And(new FilterDefinition <AccountP>[] { filterS1, filterS2 }); var updateS = Builders <AccountP> .Update.Inc(m => m.Balance, t.Value).Pull(m => m.PendingTransactions, t._id); bool isSuccess = mongoDBService.UpdateOne(AccountsCollectionName, filterS, updateS); if (isSuccess) { FilterDefinitionBuilder <AccountP> filterBuilderD = Builders <AccountP> .Filter; FilterDefinition <AccountP> filterD1 = filterBuilderD.Eq(doc => doc._id, t.Destination);//source FilterDefinition <AccountP> filterD2 = filterBuilderD.Where(doc => doc.PendingTransactions.Contains(t._id)); FilterDefinition <AccountP> filterD = filterBuilderD.And(new FilterDefinition <AccountP>[] { filterD1, filterD2 }); var updateD = Builders <AccountP> .Update.Inc(m => m.Balance, -t.Value).Pull(m => m.PendingTransactions, t._id); isSuccess = mongoDBService.UpdateOne(AccountsCollectionName, filterD, updateD); } if (isSuccess) { //3 将事务文档状态由canceling更新为cancelled. UpdateTransactionState(t, "canceling", "cancelled"); } }
private async Task <bool> HaveUniqueName(CookDto cook, string displayName, CancellationToken token) { var filterBuilder = new FilterDefinitionBuilder <Cook>(); var filter = filterBuilder.Where(x => x.DisplayName.Equals(displayName) && !x.Id.Equals(cook.Id)); var displayNameExists = await _cookRepo.GetAll(filter); return(!displayNameExists.Any()); }
public AthleteAccount GetAthleteProfile(object guid) { var fdb = new FilterDefinitionBuilder <AthleteAccount>(); var fd = fdb.Where(ap => ap.Id == 1); var athleteProfile = _apCollection.Find(fd).SingleOrDefault(); return(athleteProfile ?? AthleteAccount.GetNew()); }
public async Task <bool> ReplaceAsync(T apiScopeData, Expression <Func <T, bool> > expression) { var filterDefinitionBuilder = new FilterDefinitionBuilder <T>(); var filter = filterDefinitionBuilder.Where(expression); var replaceResult = await Collection.ReplaceOneAsync(filter, apiScopeData); return(replaceResult.IsAcknowledged); }
public ActItem UpdateActItem(ActItem actItem) { var filter = filterBuilder.Where(x => x.ID == actItem.ID); actItem.CreateTime = dbService.Query(filter).Result[0].CreateTime; actItem.UpDateTime = DateTime.Now; var result = dbService.Update <ActItem>(filter, actItem).Result; if (result.IsModifiedCountAvailable && result.ModifiedCount == 1) { return(dbService.Query <ActItem>(filter).Result[0]); } else { return(new ActItem()); } }
public async Task <UserData> ReplaceAsync(UserData user) { var filterDefinitionBuilder = new FilterDefinitionBuilder <UserData>(); var filter = filterDefinitionBuilder.Where(data => data.Id == user.Id); var replaceResult = await Collection.ReplaceOneAsync(filter, user); return(replaceResult.IsAcknowledged ? user : default(UserData)); }
public static async Task <Room> GetRoomByBookingId(this IMongoQueryRepository <Room> queryRepository, Guid bookingId) { var filterBuilder = new FilterDefinitionBuilder <Room>(); var filterDefinition = filterBuilder.Where(c => c.RoomReservations.Any(r => r.Id == bookingId)); var car = (await queryRepository.GetCollection().FindAsync(filterDefinition)).First(); return(car); }
private async Task <bool> NameNotAlreadyExists(CookEntryDto cookEntryDto, string name, CancellationToken token) { var filterBuilder = new FilterDefinitionBuilder <CookEntry>(); var filter = filterBuilder.Where(x => !x.Id.Equals(cookEntryDto.Id) && x.CookId.Equals(cookEntryDto.CookId) && x.Name.Equals(cookEntryDto.Name)); var dishes = await _repo.GetAll(filter); return(!dishes.Any()); }
private async Task <EmailTemplate> GetTemplate(string key) { var filterBuilder = new FilterDefinitionBuilder <EmailTemplate>(); var filter = filterBuilder.Where(x => x.Key == key); var result = await _templateRepo.GetAll(filter); return(result.FirstOrDefault()); }
public async Task <User> GetByIdentityId(string identityProviderId) { var filterBuilder = new FilterDefinitionBuilder <User>(); var filter = filterBuilder.Where(x => x.IdentityProviderId.Equals(identityProviderId)); var existingUser = await GetAll(filter); return(existingUser.FirstOrDefault()); }
public async Task <User> GetByEmail(string email) { var filterBuilder = new FilterDefinitionBuilder <User>(); var filter = filterBuilder.Where(x => x.Email.Equals(email)); var existingUser = await GetAll(filter); return(existingUser.FirstOrDefault()); }
public List <RichlistTable> AddressBalances(IEnumerable <string> addresses) { FilterDefinitionBuilder <RichlistTable> filterBuilder = Builders <RichlistTable> .Filter; FilterDefinition <RichlistTable> filter = filterBuilder.Where(s => addresses.Contains(s.Address)); List <RichlistTable> document = mongoDb.RichlistTable.Find(filter).ToList(); return(document); }
public void Contains_should_render_correctly() { var values = (IEnumerable <E?>) new E?[] { null, E.A, E.B }; var filter = __subject.Where(x => values.Contains(x.P)); var result = filter.Render(__serializer, __registry); result.Should().Be("{ P : { $in : [ null, 'A', 'B' ] } }"); }
/// <inheritdoc /> /// <summary> /// Gets total records count in the MongoDB collection. /// </summary> /// <returns>Int representing the total number of records in the MongoDB collection.</returns> public async Task <int> GetTotalNumberOfFiles() { Log.Information("Getting file count from MongoDB."); var filterDef = new FilterDefinitionBuilder <FileMetaData>(); var filter = filterDef.Where(x => x.IsDeleted == false); return((int)await _collection.CountDocumentsAsync(filter)); }
public Activity UpdateActivity(Activity activity) { var filter = filterBuilder.Where(x => x.ID == activity.ID); activity.CreateTime = dbService.Query(filter).Result[0].CreateTime; activity.ID = dbService.Query(filter).Result[0].ID; activity.UpDateTime = DateTime.Now; var result = dbService.Update(filter, activity).Result; if (result.IsModifiedCountAvailable && result.ModifiedCount == 1) { return(dbService.Query(filter).Result[0]); } else { return(new Activity()); } }
/// <summary> /// Pick a country in collection by his ID (ALPHA 2 or 3 Code). /// </summary> /// <param name="id">The searched ID (Alpha2 or Alpha3)</param> /// <returns>The corrresponding HRCountry or null if not found. Can throw the following exception : /// </returns> public async Task <HRCountry> GetAsync(string id) { HRCountry retour = null; if (String.IsNullOrEmpty(id)) { return(null); } try { String idToSearch = id.ToUpper(); MondoDBConnexionParam conParam = MondoDBConnexionParamFactory.CreateMondoDBConnexionParam(_config); IMongoCollection <HRCountry> collection = MongoDBCollectionGetter <HRCountry> .GetCollection(conParam); if (collection != null) { FilterDefinitionBuilder <HRCountry> bld = new FilterDefinitionBuilder <HRCountry>(); Task <IAsyncCursor <HRCountry> > retourTask = null; try { retourTask = collection.FindAsync(bld.Where(country => ((!String.IsNullOrEmpty(country.Alpha2Code)) && (country.Alpha2Code == idToSearch)) || ((!String.IsNullOrEmpty(country.Alpha3Code)) && (country.Alpha3Code == idToSearch)))); //1.1.3- await retourTask; //Message IDE0067 Disposable object created by 'await retourTask' is never disposed whereas finally dispose exists ? if (retourTask.Result != null) { retour = retourTask.Result.FirstOrDefault(); } } finally { if (retourTask != null) { if (retourTask.Result != null) { retourTask.Result.Dispose(); } retourTask.Dispose(); } } } } catch (Exception ex) { if (_logger != null) { _logger.LogError(ex.Message); } throw; } //2- return(retour); }
public void DeleteUser(string id) { var db = client.GetDatabase("LightLinkProfiles"); var collection = db.GetCollection <User>("User"); var filter = new FilterDefinitionBuilder <User>(); collection.DeleteOne(filter.Where(u => u.UserName == id)); }
public void GetToken(String code, String userId) { AuthenticationToken token = null; var parameters = String.Format("client_id={0}&grant_type=authorization_code&redirect_uri={1}&code={2}", ClientId, RedirectUrl, code); using (var client = new WebClient()) { client.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(_basicAuthenticationHeader))); client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; dynamic credentials = Json.Decode(client.UploadString(TokenUrl, parameters)); var filterBuilder = new FilterDefinitionBuilder<AuthenticationToken>(); var filter = filterBuilder.Where(i => i.UserId.Equals(userId)); if (!_mongoRepository.Exists(filter)) { token = new AuthenticationToken { Expiration = credentials.expires_in, Token = credentials.access_token, RefreshToken = credentials.refresh_token, Type = credentials.token_type, UserId = userId, ExpirationDate = DateTime.Now.AddSeconds(credentials.expires_in), ServiceUserId = credentials.user_id }; _mongoRepository.Insert(token); } } }
public void RefreshToken(string userId) { var filterBuilder = new FilterDefinitionBuilder<AuthenticationToken>(); var filter = filterBuilder.Where(i => i.UserId.Equals(userId)); AuthenticationToken token = _mongoRepository.Get(filter).FirstOrDefault(); if (token != null) { var refresherToken = token.RefreshToken; var parameters = String.Format("grant_type=refresh_token&refresh_token={0}", refresherToken); using (var client = new WebClient()) { client.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(_basicAuthenticationHeader))); client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; dynamic credentials = Json.Decode(client.UploadString(TokenUrl, parameters)); token.Expiration = credentials.expires_in; token.Token = credentials.access_token; token.RefreshToken = credentials.refresh_token; token.Type = credentials.token_type; } _mongoRepository.Update(filter, token); } }