private void CheckTimeout() { var watch = Stopwatch.StartNew(); var timeout = Configuration.ProcessTimeout; // timeout can't be less than PollTime if (timeout < PollTime) timeout = PollTime; var timeoutDate = DateTime.UtcNow.Subtract(timeout); // all message that are processing and update before timeout date Expression<Func<Message, bool>> filter = m => m.State == MessageState.Processing && m.Updated < timeoutDate; var timeoutState = (Configuration.TimeoutPolicy == TimeoutPolicy.Retry) ? MessageState.Queued : MessageState.Timeout; // update all messages that are timed out var updateDefinition = Builders<Message>.Update .Set(m => m.State, timeoutState) .Set(p => p.Updated, DateTime.UtcNow) .Inc(p => p.ErrorCount, 1); var updateOptions = new UpdateOptions { IsUpsert = false }; var t = Repository.Collection.UpdateManyAsync( filter, updateDefinition, updateOptions); // wait for result var result = t.Result; watch.Stop(); // log as Warn if there are results Logger.Warn() .Message("Completed '{0}' timeout check in: {1} ms. Timeout Message Count: {2}", Name, watch.ElapsedMilliseconds, result.ModifiedCount) .WriteIf(result.ModifiedCount > 0); }
public Task SaveLinks(int nodeId, IEnumerable<NodeLink> links) { var nodeLinks = new NodeLinks(nodeId, links); var updateOptions = new UpdateOptions { IsUpsert = true }; return _collection.ReplaceOneAsync(x => x.Id == nodeId, nodeLinks, updateOptions); }
public void AllocateBootstrapServer(int organisationID, BootstrapServer bootstrapServer) { IMongoDatabase database = GetDatabase(DATABASE_NAME, true); IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("OrganisationBootstrapServer"); FilterDefinition<BsonDocument> query = Builders<BsonDocument>.Filter.Eq("_id", organisationID); BsonDocument doc = new BsonDocument(); BsonHelper.SetValue(doc, "_id", organisationID); BsonHelper.SetValue(doc, "Url", bootstrapServer.Url); UpdateOptions options = new UpdateOptions(); options.IsUpsert = true; collection.ReplaceOne(query, doc, options); }
/// <summary> /// อัพเดทข้อมูล Class room /// </summary> /// <param name="data">ข้อมูลที่จะทำการอัพเดท</param> public void UpsertClassRoom(ClassRoom data) { var update = Builders<ClassRoom>.Update .Set(it => it.Name, data.Name) .Set(it => it.CourseCatalogId, data.CourseCatalogId) .Set(it => it.DeletedDate, data.DeletedDate) .Set(it => it.Message, data.Message) .Set(it => it.Lessons, data.Lessons) .Set(it => it.LastUpdatedMessageDate, data.LastUpdatedMessageDate); var updateOption = new UpdateOptions { IsUpsert = true }; MongoAccess.MongoUtil.Instance.GetCollection<ClassRoom>(TableName) .UpdateOne(it => it.id == data.id, update, updateOption); }
/// <summary> /// อัพเดทหรือเพิ่มข้อมูล Student key /// </summary> /// <param name="data">ข้อมูลที่ต้องการดำเนินการ</param> public void UpsertStudentKey(StudentKey data) { var update = Builders<StudentKey>.Update .Set(it => it.Code, data.Code) .Set(it => it.Grade, data.Grade) .Set(it => it.CourseCatalogId, data.CourseCatalogId) .Set(it => it.ClassRoomId, data.ClassRoomId) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.DeletedDate, data.DeletedDate); var updateOption = new UpdateOptions { IsUpsert = true }; MongoAccess.MongoUtil.Instance.GetCollection<StudentKey>(TableName) .UpdateOne(it => it.id == data.id, update, updateOption); }
/// <summary> /// อัพเดทหรือเพิ่มข้อมูลการขอเป็นเพื่อน /// </summary> /// <param name="data">ข้อมูลที่ต้องการดำเนินการ</param> public void UpsertFriendRequest(FriendRequest data) { var update = Builders<FriendRequest>.Update .Set(it => it.FromUserProfileId, data.FromUserProfileId) .Set(it => it.ToUserProfileId, data.ToUserProfileId) .Set(it => it.Status, data.Status) .Set(it => it.AcceptedDate, data.AcceptedDate) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.DeletedDate, data.DeletedDate); var updateOption = new UpdateOptions { IsUpsert = true }; MongoAccess.MongoUtil.Instance.GetCollection<FriendRequest>(TableName) .UpdateOne(it => it.id == data.id, update, updateOption); }
public MongoDbUpdateOperation(CommandActivator activator, IMongoDatabase database, string collectionName, Func <Row, MongoDB.Driver.FilterDefinition <T> > filter, Func <Row, MongoDB.Driver.UpdateDefinition <T> > update, MongoDB.Driver.UpdateOptions options = null) { _activator = activator; this.database = database; this.collectionName = collectionName; this.filter = filter; this.update = update; this.options = options; }
/// <summary> /// แก้ไขหรือเพิ่มข้อมูล Like lesson /// </summary> /// <param name="data">ข้อมูลที่จะทำการอัพเดทหรือเพิ่ม</param> public void UpsertLikeLesson(LikeLesson data) { var update = Builders<LikeLesson>.Update .Set(it => it.ClassRoomId, data.ClassRoomId) .Set(it => it.LessonId, data.LessonId) .Set(it => it.LikedByUserProfileId, data.LikedByUserProfileId) .Set(it => it.LastNotifyRequest, data.LastNotifyRequest) .Set(it => it.LastNotifyComplete, data.LastNotifyComplete) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.DeletedDate, data.DeletedDate); var updateOption = new UpdateOptions { IsUpsert = true }; MongoAccess.MongoUtil.Instance.GetCollection<LikeLesson>(TableName) .UpdateOne(it => it.id == data.id, update, updateOption); }
public async Task Get(string id) { var options = new UpdateOptions { IsUpsert = true }; for (;;) { var biscInput = BiscParser.Parse(id); var iscInput = IscParser.Parse(id); var biscFilter = Builders<Month>.Filter.Eq(m => m.YearMonth, biscInput.YearMonth); var iscFilter = Builders<Month>.Filter.Eq(m => m.YearMonth, iscInput.YearMonth); if ((biscInput.Percent == "до грудня \r\n\t\tпопереднього року") || (iscInput.Percent == " ")) break; await collectionIsc.ReplaceOneAsync(iscFilter, iscInput, options); await сollectionBisc.ReplaceOneAsync(biscFilter, biscInput, options); //insert and update date in DB } IscParser.parseLineNumber = 2; BiscParser.parseLineNumber = 3; }
public void UpdateMany <T>(IMongoCollection <T> collection, string filter, string update) { try { MongoDB.Driver.UpdateOptions updateOptions; updateOptions = new MongoDB.Driver.UpdateOptions(); updateOptions.IsUpsert = false; collection.UpdateMany(filter, update, updateOptions); } catch (Exception ex) { throw ex; } }
/// <summary> /// อัพเดทข้อมูล Class room /// </summary> /// <param name="data">ข้อมูลที่จะทำการอัพเดท</param> public async Task UpsertClassRoom(ClassRoom data) { var update = Builders<ClassRoom>.Update .Set(it => it.Name, data.Name) .Set(it => it.CourseCatalogId, data.CourseCatalogId) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.DeletedDate, data.DeletedDate) .Set(it => it.Message, data.Message) .Set(it => it.IsPublic, data.IsPublic) .Set(it => it.Lessons, data.Lessons) .Set(it => it.LastUpdatedMessageDate, data.LastUpdatedMessageDate); var updateOption = new UpdateOptions { IsUpsert = true }; await MongoAccess.MongoUtil.Instance.GetCollection<ClassRoom>(AppConfigOptions.ClassRoomTableName) .UpdateOneAsync(it => it.id == data.id, update, updateOption); }
/// <summary> /// อัพเดทหรือเพิ่มข้อมูลกิจกรรม /// </summary> /// <param name="data">ข้อมูลกิจกรรมที่ต้องการดำเนินการ</param> public void UpsertUserActivity(UserActivity data) { var update = Builders<UserActivity>.Update .Set(it => it.IsTeacher, data.IsTeacher) .Set(it => it.IsPrivateAccount, data.IsPrivateAccount) .Set(it => it.UserProfileName, data.UserProfileName) .Set(it => it.UserProfileImageUrl, data.UserProfileImageUrl) .Set(it => it.HideClassRoomMessageDate, data.HideClassRoomMessageDate) .Set(it => it.UserProfileId, data.UserProfileId) .Set(it => it.ClassRoomId, data.ClassRoomId) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.DeletedDate, data.DeletedDate) .Set(it => it.LessonActivities, data.LessonActivities); var updateOption = new UpdateOptions { IsUpsert = true }; _mongoUtil.GetCollection<UserActivity>(TableName) .UpdateOne(it => it.id == data.id, update, updateOption); }
public async Task UpsertTestedResult(LessonTestResult data) { var isNewRecord = string.IsNullOrEmpty(data.id); if (isNewRecord) { data.id = Guid.NewGuid().ToString(); data.CreatedDate = DateTime.Now; await _mongoUtil.GetCollection<LessonTestResult>(TableName).InsertOneAsync(data); } else { var update = Builders<LessonTestResult>.Update .Set(it => it.Answers, data.Answers); var updateOption = new UpdateOptions { IsUpsert = true }; _mongoUtil.GetCollection<LessonTestResult>(TableName) .UpdateOne(it => it.id == data.id, update, updateOption); } }
/// <summary> /// อัพเดทหรือเพิ่มข้อมูล notification /// </summary> /// <param name="data">ข้อมูลที่ต้องการดำเนินการ</param> public void Upsert(Notification data) { var update = Builders<Notification>.Update .Set(it => it.LastReadedDate, data.LastReadedDate) .Set(it => it.LastUpdateDate, data.LastUpdateDate) .Set(it => it.ToUserProfileId, data.ToUserProfileId) .Set(it => it.ClassRoomId, data.ClassRoomId) .Set(it => it.LessonId, data.LessonId) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.HideDate, data.HideDate) .Set(it => it.Message, data.Message) .Set(it => it.ByUserProfileId, data.ByUserProfileId) .Set(it => it.TotalLikes, data.TotalLikes) .Set(it => it.Tag, data.Tag); var updateOption = new UpdateOptions { IsUpsert = true }; _mongoUtil.GetCollection<Notification>(TableName) .UpdateOne(it => it.id == data.id, update, updateOption); }
public void UpdateMany <T>(string collectionName, string filter, string update) { try { MongoDB.Driver.UpdateOptions updateOptions; updateOptions = new MongoDB.Driver.UpdateOptions(); updateOptions.IsUpsert = false; var database = MongoUtils.CreateMongoDB(_mongoDBConnectionStr, _dataBaseName); var collection = database.GetCollection <T>(collectionName); collection.UpdateMany(filter, update, updateOptions); } catch (Exception ex) { throw ex; } }
/// <summary> /// อัพเดทหรือเพิ่มข้อมูล Class calendar /// </summary> /// <param name="data">ข้อมูลที่ต้องการดำเนินการ</param> public void UpsertClassCalendar(ClassCalendar data) { var update = Builders<ClassCalendar>.Update .Set(it => it.BeginDate, data.BeginDate) .Set(it => it.IsWeekendHoliday, data.IsWeekendHoliday) .Set(it => it.ExpiredDate, data.ExpiredDate) .Set(it => it.CloseDate, data.CloseDate) .Set(it => it.ClassRoomId, data.ClassRoomId) .Set(it => it.LastCalculateHolidayRequest, data.LastCalculateHolidayRequest) .Set(it => it.LastCalculateHolidayComplete, data.LastCalculateHolidayComplete) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.DeletedDate, data.DeletedDate) .Set(it => it.LessonCalendars, data.LessonCalendars) .Set(it => it.Holidays, data.Holidays) .Set(it => it.ShiftDays, data.ShiftDays); var updateOption = new UpdateOptions { IsUpsert = true }; MongoAccess.MongoUtil.Instance.GetCollection<ClassCalendar>(TableName) .UpdateOne(it => it.id == data.id, update, updateOption); }
/// <summary> /// เพิ่มหรืออัพเดทข้อมูล comment /// </summary> /// <param name="data">ข้อมูล comment ที่จะดำเนินการ</param> public void UpsertComment(Comment data) { var update = Builders<Comment>.Update .Set(it => it.Description, data.Description) .Set(it => it.TotalLikes, data.TotalLikes) .Set(it => it.CreatorImageUrl, data.CreatorImageUrl) .Set(it => it.CreatorDisplayName, data.CreatorDisplayName) .Set(it => it.ClassRoomId, data.ClassRoomId) .Set(it => it.LessonId, data.LessonId) .Set(it => it.CreatedByUserProfileId, data.CreatedByUserProfileId) .Set(it => it.LastNotifyRequest, data.LastNotifyRequest) .Set(it => it.LastNotifyComplete, data.LastNotifyComplete) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.DeletedDate, data.DeletedDate) .Set(it => it.Discussions, data.Discussions); var updateOption = new UpdateOptions { IsUpsert = true }; MongoAccess.MongoUtil.Instance.GetCollection<Comment>(TableName) .UpdateOne(it => it.id == data.id, update, updateOption); }
/// <summary> /// อัพเดทหรือเพิ่มข้อมูล lesson catalog /// </summary> /// <param name="lessonCatalogId">ข้อมูลที่ต้องการดำเนินการ</param> public async Task UpsertLessonCatalog(LessonCatalog data) { var update = Builders<LessonCatalog>.Update .Set(it => it.Order, data.Order) .Set(it => it.Title, data.Title) .Set(it => it.UnitNo, data.UnitNo) .Set(it => it.SemesterName, data.SemesterName) .Set(it => it.CourseCatalogId, data.CourseCatalogId) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.DeletedDate, data.DeletedDate) .Set(it => it.Advertisments, data.Advertisments) .Set(it => it.TopicOfTheDays, data.TopicOfTheDays) .Set(it => it.TeacherItems, data.TeacherItems) .Set(it => it.StudentItems, data.StudentItems) .Set(it => it.PreAssessments, data.PreAssessments) .Set(it => it.PostAssessments, data.PostAssessments); var updateOption = new UpdateOptions { IsUpsert = true }; await MongoAccess.MongoUtil.Instance .GetCollection<LessonCatalog>(AppConfigOptions.LessonCatalogTableName) .UpdateOneAsync(it => it.id == data.id, update, updateOption); }
/// <summary> /// อัพเดทหรือเพิ่มข้อมูล course catalog /// </summary> /// <param name="data">ข้อมูลที่ต้องการดำเนินการ</param> public async Task UpsertCourseCatalog(CourseCatalog data) { var update = Builders<CourseCatalog>.Update .Set(it => it.GroupName, data.GroupName) .Set(it => it.Advertisements, data.Advertisements) .Set(it => it.Grade, data.Grade) .Set(it => it.SideName, data.SideName) .Set(it => it.PriceUSD, data.PriceUSD) .Set(it => it.Series, data.Series) .Set(it => it.Title, data.Title) .Set(it => it.FullDescription, data.FullDescription) .Set(it => it.DescriptionImageUrl, data.DescriptionImageUrl) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.DeletedDate, data.DeletedDate) .Set(it => it.Semesters, data.Semesters) .Set(it => it.IsFree, data.IsFree) .Set(it => it.TotalWeeks, data.TotalWeeks); var updateOption = new UpdateOptions { IsUpsert = true }; await MongoAccess.MongoUtil.Instance .GetCollection<CourseCatalog>(AppConfigOptions.CourseCatalogTableName) .UpdateOneAsync(it => it.id == data.id, update, updateOption); }
/// <summary> /// อัพเดทหรือเพิ่มข้อมูล contract /// </summary> /// <param name="data">ข้อมูลที่ต้องการดำเนินการ</param> public async Task UpsertContract(Contract data) { var update = Builders<Contract>.Update .Set(it => it.SchoolName, data.SchoolName) .Set(it => it.City, data.City) .Set(it => it.State, data.State) .Set(it => it.ZipCode, data.ZipCode) .Set(it => it.PrimaryContractName, data.PrimaryContractName) .Set(it => it.PrimaryPhoneNumber, data.PrimaryPhoneNumber) .Set(it => it.PrimaryEmail, data.PrimaryEmail) .Set(it => it.SecondaryContractName, data.SecondaryContractName) .Set(it => it.SecondaryPhoneNumber, data.SecondaryPhoneNumber) .Set(it => it.SecondaryEmail, data.SecondaryEmail) .Set(it => it.StartDate, data.StartDate) .Set(it => it.ExpiredDate, data.ExpiredDate) .Set(it => it.TimeZone, data.TimeZone) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.DeletedDate, data.DeletedDate) .Set(it => it.Licenses, data.Licenses); var updateOption = new UpdateOptions { IsUpsert = true }; await MongoAccess.MongoUtil.Instance.GetCollection<Contract>(AppConfigOptions.ContractTableName) .UpdateOneAsync(it => it.id == data.id, update, updateOption); }
/// <summary> /// Replaces a single document. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> /// <param name="collection">The collection.</param> /// <param name="filter">The filter.</param> /// <param name="replacement">The replacement.</param> /// <param name="options">The options.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The result of the replacement. /// </returns> public static Task <ReplaceOneResult> ReplaceOneAsync <TDocument>(this IMongoCollection <TDocument> collection, Expression <Func <TDocument, bool> > filter, TDocument replacement, UpdateOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(collection, "collection"); Ensure.IsNotNull(filter, "filter"); return(collection.ReplaceOneAsync(new ExpressionFilterDefinition <TDocument>(filter), replacement, options, cancellationToken)); }
/// <summary> /// Renew the expiration of a lock with the specified <paramref name="name" /> and <paramref name="expiration" />. /// </summary> /// <param name="name">The name of the lock.</param> /// <param name="expiration">The amount of time before the lock will expire and be free to be acquired again.</param> /// <returns></returns> public virtual void Renew(string name, TimeSpan expiration) { if (name == null) throw new ArgumentNullException(nameof(name)); var builder = Builders<LockData>.Filter; var filter = builder.Eq(m => m.Id, name); var update = Builders<LockData>.Update .Set(p => p.Updated, DateTime.UtcNow) .Set(p => p.Expire, DateTime.UtcNow.Add(expiration)); var options = new UpdateOptions { IsUpsert = false }; Collection.UpdateOneAsync(filter, update, options).Wait(); }
/// <inheritdoc /> public virtual UpdateResult UpdateOne(FilterDefinition <TDocument> filter, UpdateDefinition <TDocument> update, UpdateOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(UpdateOne(filter, update, options, (requests, bulkWriteOptions) => BulkWrite(requests, bulkWriteOptions, cancellationToken))); }
public void SaveAccessKey(AccessKey accessKey, TObjectState state) { IMongoDatabase database = GetDatabase(DATABASE_NAME, true); IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("AccessKey"); FilterDefinition<BsonDocument> query = Builders<BsonDocument>.Filter.Eq("_id", accessKey.Key); if ((state == TObjectState.Add) || (state == TObjectState.Update)) { BsonDocument doc = new BsonDocument(); BsonHelper.SetValue(doc, "_id", accessKey.Key); BsonHelper.SetValue(doc, "OrganisationID", accessKey.OrganisationID); BsonHelper.SetValue(doc, "Name", accessKey.Name); BsonHelper.SetValue(doc, "Secret", accessKey.Secret); UpdateOptions options = new UpdateOptions(); options.IsUpsert = true; collection.ReplaceOne(query, doc, options); } else if (state == TObjectState.Delete) { collection.DeleteOne(query); } BroadcastTableChange("AccessKey", accessKey.Key); }
private static void Upsert(IMongoCollection<BsonDocument> collection, BsonDocument newDoc, FilterDefinition<BsonDocument> filter) { var options = new UpdateOptions(); options.IsUpsert = true; collection.ReplaceOneAsync(filter, newDoc, options).Wait(); }
/// <inheritdoc /> public virtual ReplaceOneResult ReplaceOne(FilterDefinition <TDocument> filter, TDocument replacement, UpdateOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filter, nameof(filter)); Ensure.IsNotNull((object)replacement, "replacement"); options = options ?? new UpdateOptions(); var model = new ReplaceOneModel <TDocument>(filter, replacement) { IsUpsert = options.IsUpsert }; try { var bulkWriteOptions = new BulkWriteOptions { BypassDocumentValidation = options.BypassDocumentValidation }; var result = BulkWrite(new[] { model }, bulkWriteOptions, cancellationToken); return(ReplaceOneResult.FromCore(result)); } catch (MongoBulkWriteException <TDocument> ex) { throw MongoWriteException.FromBulkWriteException(ex); } }
/// <inheritdoc /> public virtual async Task <ReplaceOneResult> ReplaceOneAsync(FilterDefinition <TDocument> filter, TDocument replacement, UpdateOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filter, "filter"); Ensure.IsNotNull((object)replacement, "replacement"); options = options ?? new UpdateOptions(); var model = new ReplaceOneModel <TDocument>(filter, replacement) { IsUpsert = options.IsUpsert }; try { var result = await BulkWriteAsync(new[] { model }, null, cancellationToken).ConfigureAwait(false); return(ReplaceOneResult.FromCore(result)); } catch (MongoBulkWriteException <TDocument> ex) { throw MongoWriteException.FromBulkWriteException(ex); } }
public virtual ReplaceOneResult ReplaceOne(FilterDefinition <TDocument> filter, TDocument replacement, UpdateOptions options, CancellationToken cancellationToken = default(CancellationToken)) { return(ReplaceOne(filter, replacement, ReplaceOptions.From(options), (requests, bulkWriteOptions) => BulkWrite(requests, bulkWriteOptions, cancellationToken))); }
/// <summary> /// Save the specified <paramref name="message" /> as an asynchronous operation. /// </summary> /// <param name="message">The message to save.</param> /// <returns> /// The <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="message"/> is <see langword="null" />.</exception> public Task<Message> Save(Message message) { if (message == null) throw new ArgumentNullException("message"); // generate id if null, upsert requires id if (string.IsNullOrEmpty(message.Id)) { message.Id = ObjectId.GenerateNewId().ToString(); message.Created = DateTime.UtcNow; } message.Updated = DateTime.UtcNow; var updateOptions = new UpdateOptions { IsUpsert = true }; return _collection .ReplaceOneAsync(m => m.Id == message.Id, message, updateOptions) .ContinueWith(t => message); }
private UpdateResult UpdateMany(FilterDefinition <TDocument> filter, UpdateDefinition <TDocument> update, UpdateOptions options, Func <IEnumerable <WriteModel <TDocument> >, BulkWriteOptions, BulkWriteResult <TDocument> > bulkWrite) { Ensure.IsNotNull(filter, nameof(filter)); Ensure.IsNotNull(update, nameof(update)); options = options ?? new UpdateOptions(); var model = new UpdateManyModel <TDocument>(filter, update) { ArrayFilters = options.ArrayFilters, Collation = options.Collation, IsUpsert = options.IsUpsert }; try { var bulkWriteOptions = new BulkWriteOptions { BypassDocumentValidation = options.BypassDocumentValidation }; var result = bulkWrite(new[] { model }, bulkWriteOptions); return(UpdateResult.FromCore(result)); } catch (MongoBulkWriteException <TDocument> ex) { throw MongoWriteException.FromBulkWriteException(ex); } }
/// <summary> /// อัพเดทหรือเพิ่มข้อมูล Class calendar /// </summary> /// <param name="data">ข้อมูลที่ต้องการดำเนินการ</param> public void UpsertClassCalendar(ClassCalendar data) { var update = Builders<ClassCalendar>.Update .Set(it => it.BeginDate, data.BeginDate) .Set(it => it.ExpiredDate, data.ExpiredDate) .Set(it => it.CloseDate, data.CloseDate) .Set(it => it.ClassRoomId, data.ClassRoomId) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.DeletedDate, data.DeletedDate) .Set(it => it.LessonCalendars, data.LessonCalendars) .Set(it => it.Holidays, data.Holidays) .Set(it => it.ShiftDays, data.ShiftDays); var updateOption = new UpdateOptions { IsUpsert = true }; _mongoUtil.GetCollection<ClassCalendar>(TableName) .UpdateOne(it => it.id == data.id, update, updateOption); }
public void SaveObjectDefinitions(List<ObjectDefinition> items, TObjectState state) { IMongoDatabase database = GetDatabase(DATABASE_NAME, true); IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("ObjectDefinition"); foreach (ObjectDefinition item in items) { if (item.ObjectDefinitionID == Guid.Empty) item.ObjectDefinitionID = Guid.NewGuid(); FilterDefinition<BsonDocument> query = Builders<BsonDocument>.Filter.Eq("_id", item.ObjectDefinitionID.ToByteArray()); if ((state == TObjectState.Add) || (state == TObjectState.Update)) { BsonDocument doc = new BsonDocument(); BsonHelper.SetValue(doc, "_id", item.ObjectDefinitionID); BsonHelper.SetValue(doc, "ObjectID", item.ObjectID); if (item.OrganisationID.HasValue && (item.OrganisationID.Value == 0)) item.OrganisationID = null; BsonHelper.SetValue(doc, "OrganisationID", item.OrganisationID); BsonHelper.SetValue(doc, "Name", item.Name); BsonHelper.SetValue(doc, "MIMEType", item.MIMEType); BsonHelper.SetValue(doc, "SerialisationName", item.SerialisationName); BsonHelper.SetValue(doc, "Description", item.Description); BsonHelper.SetValue(doc, "Singleton", item.Singleton); if ((item.Properties != null) && item.Properties.Count > 0) { BsonArray array = new BsonArray(); foreach (PropertyDefinition property in item.Properties) { if (property.PropertyDefinitionID == Guid.Empty) property.PropertyDefinitionID = Guid.NewGuid(); BsonDocument propertyDoc = new BsonDocument(); BsonHelper.SetValue(propertyDoc, "_id", property.PropertyDefinitionID); BsonHelper.SetValue(propertyDoc, "PropertyID", property.PropertyID); BsonHelper.SetValue(propertyDoc, "Name", property.Name); BsonHelper.SetValue(propertyDoc, "Description", property.Description); BsonHelper.SetValue(propertyDoc, "DataType", (int)property.DataType); BsonHelper.SetValue(propertyDoc, "DataTypeLength", property.DataTypeLength); BsonHelper.SetValue(propertyDoc, "MIMEType", property.MIMEType); BsonHelper.SetValue(propertyDoc, "MinValue", property.MinValue); BsonHelper.SetValue(propertyDoc, "MaxValue", property.MaxValue); BsonHelper.SetValue(propertyDoc, "Units", property.Units); BsonHelper.SetValue(propertyDoc, "IsCollection", property.IsCollection); BsonHelper.SetValue(propertyDoc, "IsMandatory", property.IsMandatory); BsonHelper.SetValue(propertyDoc, "Access", (int)property.Access); BsonHelper.SetValue(propertyDoc, "SortOrder", property.SortOrder); BsonHelper.SetValue(propertyDoc, "SerialisationName", property.SerialisationName); BsonHelper.SetValue(propertyDoc, "CollectionItemSerialisationName", property.CollectionItemSerialisationName); array.Add(propertyDoc); } doc.Add("Properties", array); } UpdateOptions options = new UpdateOptions(); options.IsUpsert = true; collection.ReplaceOne(query, doc, options); } else if (state == TObjectState.Delete) { collection.DeleteOne(query); } } BroadcastTableChange("ObjectDefinition", string.Empty); }
private async Task <UpdateResult> UpdateOneAsync(FilterDefinition <TDocument> filter, UpdateDefinition <TDocument> update, UpdateOptions options, Func <IEnumerable <WriteModel <TDocument> >, BulkWriteOptions, Task <BulkWriteResult <TDocument> > > bulkWriteAsync) { Ensure.IsNotNull(filter, nameof(filter)); Ensure.IsNotNull(update, nameof(update)); options = options ?? new UpdateOptions(); var model = new UpdateOneModel <TDocument>(filter, update) { ArrayFilters = options.ArrayFilters, Collation = options.Collation, Hint = options.Hint, IsUpsert = options.IsUpsert }; try { var bulkWriteOptions = new BulkWriteOptions { BypassDocumentValidation = options.BypassDocumentValidation }; var result = await bulkWriteAsync(new[] { model }, bulkWriteOptions).ConfigureAwait(false); return(UpdateResult.FromCore(result)); } catch (MongoBulkWriteException <TDocument> ex) { throw MongoWriteException.FromBulkWriteException(ex); } }
/// <inheritdoc /> public virtual Task <UpdateResult> UpdateOneAsync(IClientSessionHandle session, FilterDefinition <TDocument> filter, UpdateDefinition <TDocument> update, UpdateOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(UpdateOneAsync(filter, update, options, (requests, bulkWriteOptions) => BulkWriteAsync(session, requests, bulkWriteOptions, cancellationToken))); }
/// <inheritdoc /> public virtual async Task <UpdateResult> UpdateOneAsync(FilterDefinition <TDocument> filter, UpdateDefinition <TDocument> update, UpdateOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filter, nameof(filter)); Ensure.IsNotNull(update, nameof(update)); options = options ?? new UpdateOptions(); var model = new UpdateOneModel <TDocument>(filter, update) { IsUpsert = options.IsUpsert }; try { var bulkWriteOptions = new BulkWriteOptions { BypassDocumentValidation = options.BypassDocumentValidation }; var result = await BulkWriteAsync(new[] { model }, bulkWriteOptions, cancellationToken).ConfigureAwait(false); return(UpdateResult.FromCore(result)); } catch (MongoBulkWriteException <TDocument> ex) { throw MongoWriteException.FromBulkWriteException(ex); } }
private async Task <ReplaceOneResult> ReplaceOneAsync(FilterDefinition <TDocument> filter, TDocument replacement, UpdateOptions options, Func <IEnumerable <WriteModel <TDocument> >, BulkWriteOptions, Task <BulkWriteResult <TDocument> > > bulkWriteAsync) { Ensure.IsNotNull(filter, nameof(filter)); Ensure.IsNotNull((object)replacement, "replacement"); if (options?.ArrayFilters != null) { throw new ArgumentException("ArrayFilters cannot be used with ReplaceOne.", nameof(options)); } options = options ?? new UpdateOptions(); var model = new ReplaceOneModel <TDocument>(filter, replacement) { Collation = options.Collation, IsUpsert = options.IsUpsert }; try { var bulkWriteOptions = new BulkWriteOptions { BypassDocumentValidation = options.BypassDocumentValidation }; var result = await bulkWriteAsync(new[] { model }, bulkWriteOptions).ConfigureAwait(false); return(ReplaceOneResult.FromCore(result)); } catch (MongoBulkWriteException <TDocument> ex) { throw MongoWriteException.FromBulkWriteException(ex); } }
/// <summary> /// Release a lock with the specified <paramref name="name"/>. Note, release is typically not used on a throttle lock. /// </summary> /// <param name="name">The name of the lock.</param> public override void Release(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); var builder = Builders<LockData>.Filter; var filter = builder.Eq(m => m.Id, name); var update = Builders<LockData>.Update .Set(p => p.IsLocked, false) .Set(p => p.Updated, DateTime.UtcNow) .Unset(p => p.Expire); var options = new UpdateOptions { IsUpsert = false }; Collection.UpdateOneAsync(filter, update, options).Wait(); }
public void SaveBootstrapServer(BootstrapServer bootstrapServer, TObjectState state) { IMongoDatabase database = GetDatabase(DATABASE_NAME, true); IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("BootstrapServer"); FilterDefinition<BsonDocument> query = Builders<BsonDocument>.Filter.Eq("_id", bootstrapServer.Url); if ((state == TObjectState.Add) || (state == TObjectState.Update)) { BsonDocument doc = new BsonDocument(); BsonHelper.SetValue(doc, "_id", bootstrapServer.Url); if (bootstrapServer.ServerIdentities != null && bootstrapServer.ServerIdentities.Count > 0) { BsonArray array = new BsonArray(); foreach (PSKIdentity pskIdentity in bootstrapServer.ServerIdentities) { BsonDocument pskIdentityDoc = new BsonDocument(); BsonHelper.SetValue(pskIdentityDoc, "_id", pskIdentity.Identity); BsonHelper.SetValue(pskIdentityDoc, "Secret", pskIdentity.Secret); array.Add(pskIdentityDoc); } doc.Add("ServerIdentities", array); } if (bootstrapServer.ServerCertificate != null) { BsonDocument serverCertificateDoc = new BsonDocument(); BsonHelper.SetValue(serverCertificateDoc, "_id", (int)bootstrapServer.ServerCertificate.CertificateFormat); BsonHelper.SetValue(serverCertificateDoc, "RawCertificate", bootstrapServer.ServerCertificate.RawCertificate); doc.Add("ServerCertificate", serverCertificateDoc); } UpdateOptions options = new UpdateOptions(); options.IsUpsert = true; collection.ReplaceOne(query, doc, options); } else if (state == TObjectState.Delete) { collection.DeleteOne(query); } BroadcastTableChange("BootstrapServer", string.Empty); }
public void SaveSubscription(Subscription subscription, TObjectState state) { IMongoDatabase database = GetDatabase(DATABASE_NAME, true); IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(COLLECTION_NAME); EnsureIndexExists<BsonDocument>(collection, "OrganisationID"); EnsureIndexExists<BsonDocument>(collection, "ClientID"); FilterDefinition<BsonDocument> query = Builders<BsonDocument>.Filter.Eq("_id", subscription.SubscriptionID.ToByteArray()); if ((state == TObjectState.Add) || (state == TObjectState.Update)) { BsonDocument doc = new BsonDocument(); BsonHelper.SetValue(doc, "_id", subscription.SubscriptionID); BsonHelper.SetValue(doc, "OrganisationID", subscription.OrganisationID); BsonHelper.SetValue(doc, "ClientID", subscription.ClientID); BsonHelper.SetValue(doc, "DefinitionID", subscription.ObjectDefinitionID); BsonHelper.SetValue(doc, "ObjectID", subscription.ObjectID); BsonHelper.SetValue(doc, "SubscriptionType", (int)subscription.SubscriptionType); BsonHelper.SetValue(doc, "PropertyDefinitionID", subscription.PropertyDefinitionID); BsonHelper.SetValue(doc, "Url", subscription.Url); BsonHelper.SetValue(doc, "AcceptContentType", subscription.AcceptContentType); if (subscription.NotificationParameters != null) { MemoryStream stream = new MemoryStream(); subscription.NotificationParameters.Serialise(stream); BsonHelper.SetValue(doc, "NotificationParameters", StringUtils.Encode(stream.ToArray())); } UpdateOptions options = new UpdateOptions(); options.IsUpsert = true; collection.ReplaceOne(query, doc, options); } else if (state == TObjectState.Delete) { collection.DeleteOne(query); } BroadcastTableChange(COLLECTION_NAME, StringUtils.GuidEncode(subscription.SubscriptionID)); }
/// <inheritdoc /> public virtual Task <ReplaceOneResult> ReplaceOneAsync(FilterDefinition <TDocument> filter, TDocument replacement, UpdateOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(ReplaceOneAsync(filter, replacement, options, (requests, bulkWriteOptions) => BulkWriteAsync(requests, bulkWriteOptions, cancellationToken))); }
private void CheckSchedule() { var watch = Stopwatch.StartNew(); var currentDate = DateTime.UtcNow; // all message that are scheduled and schedule date before now Expression<Func<Message, bool>> filter = m => m.State == MessageState.Scheduled && m.Scheduled < currentDate; // update all messages to queued var updateDefinition = Builders<Message>.Update .Set(m => m.State, MessageState.Queued) .Set(p => p.Updated, DateTime.UtcNow); var updateOptions = new UpdateOptions { IsUpsert = false }; var t = Repository.Collection.UpdateManyAsync( filter, updateDefinition, updateOptions); // wait for result var result = t.Result; watch.Stop(); // log as Info if there are results Logger.Info() .Message("Completed '{0}' schedule check in: {1} ms. Schedule Message Count: {2}", Name, watch.ElapsedMilliseconds, result.ModifiedCount) .WriteIf(result.ModifiedCount > 0); }
/// <summary> /// Updates a single document. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> /// <param name="collection">The collection.</param> /// <param name="filter">The filter.</param> /// <param name="update">The update.</param> /// <param name="options">The options.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The result of the update operation. /// </returns> public static Task <UpdateResult> UpdateOneAsync <TDocument>(this IMongoCollection <TDocument> collection, Expression <Func <TDocument, bool> > filter, object update, UpdateOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(collection, "collection"); Ensure.IsNotNull(filter, "filter"); return(collection.UpdateOneAsync(filter, update, options, cancellationToken)); }
/// <inheritdoc /> public virtual UpdateResult UpdateOne(FilterDefinition <TDocument> filter, UpdateDefinition <TDocument> update, UpdateOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filter, nameof(filter)); Ensure.IsNotNull(update, nameof(update)); options = options ?? new UpdateOptions(); var model = new UpdateOneModel <TDocument>(filter, update) { ArrayFilters = options.ArrayFilters, Collation = options.Collation, IsUpsert = options.IsUpsert }; try { var bulkWriteOptions = new BulkWriteOptions { BypassDocumentValidation = options.BypassDocumentValidation }; var result = BulkWrite(new[] { model }, bulkWriteOptions, cancellationToken); return(UpdateResult.FromCore(result)); } catch (MongoBulkWriteException <TDocument> ex) { throw MongoWriteException.FromBulkWriteException(ex); } }
/// <summary> /// Updates a single document. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> /// <param name="collection">The collection.</param> /// <param name="filter">The filter.</param> /// <param name="update">The update.</param> /// <param name="options">The options.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The result of the update operation. /// </returns> public static Task <UpdateResult> UpdateOneAsync <TDocument>(this IMongoCollection <TDocument> collection, Expression <Func <TDocument, bool> > filter, Func <UpdateBuilder <TDocument>, UpdateBuilder <TDocument> > update, UpdateOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(collection, "collection"); Ensure.IsNotNull(filter, "filter"); Ensure.IsNotNull(update, "update"); var updateBuilder = new UpdateBuilder <TDocument>(); var updateObj = update(updateBuilder); return(collection.UpdateOneAsync(filter, updateObj, options, cancellationToken)); }
/// <summary> /// Verifies the lock record exists. /// </summary> /// <param name="name">The name of the lock.</param> protected virtual void VerifyLock(string name) { var builder = Builders<LockData>.Filter; var filter = builder.Eq(m => m.Id, name); // only set on insert var update = Builders<LockData>.Update .SetOnInsert(p => p.Id, name) .SetOnInsert(p => p.IsLocked, false) .SetOnInsert(p => p.Created, DateTime.UtcNow) .SetOnInsert(p => p.Updated, DateTime.UtcNow); var options = new UpdateOptions { IsUpsert = true }; Collection.UpdateOneAsync(filter, update, options).Wait(); }
/// <inheritdoc /> public virtual ReplaceOneResult ReplaceOne(IClientSessionHandle session, FilterDefinition <TDocument> filter, TDocument replacement, UpdateOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(ReplaceOne(filter, replacement, options, (requests, bulkWriteOptions) => BulkWrite(session, requests, bulkWriteOptions, cancellationToken))); }
private void SaveMetric(MetricBase metric, TObjectState state, BsonValue id, string collectionName, Dictionary<string, BsonValue> values) { IMongoDatabase database = GetDatabase(DATABASE_NAME, true); IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(collectionName); if (state == TObjectState.Add) { BsonDocument newItem = new BsonDocument(); BsonHelper.SetValue(newItem, "Name", metric.Name); BsonHelper.SetValue(newItem, "Value", metric.Value); foreach (KeyValuePair<string, BsonValue> pair in values) { newItem[pair.Key] = pair.Value; } FilterDefinition<BsonDocument> filter = Builders<BsonDocument>.Filter.Eq("_id", id); UpdateDefinition<BsonDocument> update = Builders<BsonDocument>.Update.AddToSet("Metrics", newItem); UpdateOptions options = new UpdateOptions(); options.IsUpsert = true; collection.UpdateOne(filter, update, options); } else if (state == TObjectState.Update) { FilterDefinition<BsonDocument> clientOrOrganisationIDFilter = Builders<BsonDocument>.Filter.Eq("_id", id); FilterDefinition<BsonDocument> metricNameFilter = Builders<BsonDocument>.Filter.Eq("Metrics.Name", metric.Name); FilterDefinition<BsonDocument> filter = Builders<BsonDocument>.Filter.And(clientOrOrganisationIDFilter, metricNameFilter); UpdateDefinition<BsonDocument> update = Builders<BsonDocument>.Update.Set("Metrics.$.Value", metric.Value); collection.UpdateOne(filter, update); } else if (state == TObjectState.Delete) { FilterDefinition<BsonDocument> filter = Builders<BsonDocument>.Filter.Eq("_id", id); UpdateDefinition<BsonDocument> update = Builders<BsonDocument>.Update.PullFilter("Metrics", Builders<BsonDocument>.Filter.Eq("Name", metric.Name)); collection.UpdateOne(filter, update); } }
public virtual Task <ReplaceOneResult> ReplaceOneAsync(IClientSessionHandle session, FilterDefinition <TDocument> filter, TDocument replacement, UpdateOptions options, CancellationToken cancellationToken = default(CancellationToken)) { return(ReplaceOneAsync(filter, replacement, ReplaceOptions.From(options), (requests, bulkWriteOptions) => BulkWriteAsync(session, requests, bulkWriteOptions, cancellationToken))); }
/// <summary> /// อัพเดทหรือเพิ่มข้อมูลผู้ใช้ /// </summary> /// <param name="data">ข้อมูลที่ต้องการดำเนินการ</param> public void UpsertUserProfile(UserProfile data) { var update = Builders<UserProfile>.Update .Set(it => it.Name, data.Name) .Set(it => it.SchoolName, data.SchoolName) .Set(it => it.ImageProfileUrl, data.ImageProfileUrl) .Set(it => it.IsPrivateAccount, data.IsPrivateAccount) .Set(it => it.IsEnableNotification, data.IsEnableNotification) .Set(it => it.CourseReminder, data.CourseReminder) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.DeletedDate, data.DeletedDate) .Set(it => it.Subscriptions, data.Subscriptions); var updateOption = new UpdateOptions { IsUpsert = true }; _mongoUtil.GetCollection<UserProfile>(TableName) .UpdateOne(it => it.id == data.id, update, updateOption); }
public async Task <UpdateResult> UpdateOneAsync(object filter, object update, UpdateOptions options, CancellationToken cancellationToken) { Ensure.IsNotNull(filter, "filter"); Ensure.IsNotNull(update, "update"); options = options ?? new UpdateOptions(); var model = new UpdateOneModel <TDocument>(filter, update) { IsUpsert = options.IsUpsert }; try { var result = await BulkWriteAsync(new[] { model }, null, cancellationToken).ConfigureAwait(false); return(UpdateResult.FromCore(result)); } catch (MongoBulkWriteException <TDocument> ex) { throw MongoWriteException.FromBulkWriteException(ex); } }