public void ReplaceDemo()
        {
            #region radspreadprocessing-features-find-and-replace_1
            Workbook  workbook   = new Workbook();
            Worksheet worksheet1 = workbook.Worksheets.Add();
            Worksheet worksheet2 = workbook.Worksheets.Add();

            worksheet1.Cells[1, 1].SetValue("SUMMARY");
            worksheet1.Cells[1, 2].SetValue("=SUM(5, 6)");

            worksheet2.Cells[2, 2].SetValue("=SUM(4, 4)");
            worksheet2.Cells[2, 3].SetValue("SUM");

            ReplaceOptions options = new ReplaceOptions()
            {
                StartCell   = new WorksheetCellIndex(worksheet1, 0, 0),
                FindBy      = FindBy.Rows,
                FindIn      = FindInContentType.Formulas,
                FindWhat    = "SUM",
                ReplaceWith = "Test",
                FindWithin  = FindWithin.Workbook,
            };

            var findResult = workbook.Find(options);

            options.StartCell = findResult.FoundCell;

            if (workbook.Replace(options))
            {
                RadWindow.Alert("Replace was successful!");
            }

            workbook.ReplaceAll(options);
            #endregion
        }
Beispiel #2
0
 public async Task UpsertAsync(Player playerIn)
 {
     var options = new ReplaceOptions {
         IsUpsert = true
     };
     await _players.ReplaceOneAsync(player => player.Id == playerIn.Id, playerIn, options);
 }
        public async Task UpsertCollection(IEnumerable <PoliceEvent> policeEvents)
        {
            try
            {
                var collection = GetCollection <PoliceEventEntity>();
                var count      = 0;
                foreach (var pe in policeEvents)
                {
                    var entity = new PoliceEventEntity(pe);
                    var filter = Builders <PoliceEventEntity> .Filter.Eq("_id", pe.Id);

                    var replaceOptions = new ReplaceOptions
                    {
                        IsUpsert = true
                    };
                    await collection.ReplaceOneAsync(filter, entity, replaceOptions);

                    count++;
                }
                _logger.LogInformation($"Upserted {count} police events to the MongoDB database");
            }
            catch (Exception e)
            {
                _logger.LogError(e.ToString());
                throw;
            }
        }
Beispiel #4
0
        public static async Task <ReplaceOneResult> ReplaceDocument <T>(
            this IMongoCollection <T> collection,
            T document,
            Action <ReplaceOptions>?configure,
            CancellationToken cancellationToken = default
            ) where T : Document
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document), "Document cannot be null.");
            }

            var options = new ReplaceOptions {
                IsUpsert = true
            };

            configure?.Invoke(options);

            return(await collection.ReplaceOneAsync(
                       x => x.Id == document.Id,
                       document,
                       options,
                       cancellationToken
                       ).Ignore());
        }
Beispiel #5
0
        /// <summary>Create or update a record in the database</summary>
        /// <remarks>
        /// The destination collection is chosen based on the record's type
        /// </remarks>
        public async Task <bool> Save <T>(T obj, Session?session = null) where T : Record
        {
            if (obj.Created == default)
            {
                var now = DateTime.UtcNow;
                obj.Created = now;
                obj.Updated = now;
            }
            else
            {
                obj.Updated = DateTime.UtcNow;
            }

            if (CollectionByType[typeof(T)] is IMongoCollection <T> collection)
            {
                var options = new ReplaceOptions();
                options.IsUpsert = true;
                if (session != null)
                {
                    return((await collection.ReplaceOneAsync(session.Handle, record => record.Id == obj.Id, obj,
                                                             options)).IsAcknowledged);
                }

                return((await collection.ReplaceOneAsync(record => record.Id == obj.Id, obj, options)).IsAcknowledged);
            }

            return(false);
        }
Beispiel #6
0
        /// <summary>
        /// ReplaceOne with optimistic lock async
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="queryById"></param>
        /// <param name="document"></param>
        /// <typeparam name="TDocument"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <returns></returns>
        /// <exception cref="MongoConcurrencyUpdatedException"></exception>
        public static ReplaceOneResult ReplaceOneOptimistic <TDocument, TKey>(this IMongoCollection <TDocument> collection, FilterDefinition <TDocument> queryById, TDocument document)
            where TDocument : IDocument <TKey>
            where TKey : IEquatable <TKey>
        {
            var replaceOptions = new ReplaceOptions()
            {
                IsUpsert = true
            };
            var queryWithIdAndVersion = Builders <TDocument> .Filter.And(queryById, Builders <TDocument> .Filter.Eq(ChangeCounter, document.ChangeCounter));

            try
            {
                document.UpdateChangeCounter();
                return(collection.ReplaceOne(queryWithIdAndVersion, document, replaceOptions));
            }
            catch (MongoWriteException e)
            {
                // if upsert is enabled and the versions do not match, an attempt will be made to insert the new entity
                // but as the ids of the entities are equal, this will throw this exception, which is equal to affected rows = 0
                if (e.WriteError.Category == ServerErrorCategory.DuplicateKey && replaceOptions.IsUpsert)
                {
                    var existingObject = collection.Find(queryById).Single();
                    throw new MongoConcurrencyUpdatedException(document.Id.ToString(), document.ChangeCounter, existingObject.ChangeCounter);
                }

                throw;
            }
        }
Beispiel #7
0
 /// <summary>
 /// Replace one document from the MongoDb collection.
 /// </summary>
 /// <param name="context">Mongodb collection context</param>
 /// <param name="document">The document to be replaced</param>
 /// <param name="options"><see cref="ReplaceOptions"/></param>
 /// <typeparam name="TDocument">Type of the document</typeparam>
 /// <returns><see cref="ReplaceOneResult"/></returns>
 public static async ValueTask <ReplaceOneResult> Replace <TDocument>(this ICallistoCollectionContext <TDocument> context, TDocument document,
                                                                      ReplaceOptions options = null)
     where TDocument : class, IDocumentRoot, ICallistoCollectionContext <TDocument>
 {
     ValidateOperationParameters(document, context, "replace-one");
     return(await context.Collection.ReplaceOneAsync(document.FilterById(), document, options));
 }
Beispiel #8
0
 public async Task UpsertAsync(ToDoItem item)
 {
     var opt = new ReplaceOptions {
         IsUpsert = true
     };
     await _collection.ReplaceOneAsync(t => t.Id.Equals(item.Id), item, opt);
 }
Beispiel #9
0
        public static int GetDividendDataAndInsertToMongoDb(List <string> symbols)
        {
            int recordsInsertedOrUpdated = 0;

            try
            {
                var db             = Client.GetDatabase("PseudoMarketsDB");
                var collection     = db.GetCollection <BsonDocument>("DividendData");
                var replaceOptions = new ReplaceOptions()
                {
                    IsUpsert = true
                };

                var dividends = AlphaVantageClient.GetDividendData(symbols, AlphaVantageKey).GetAwaiter().GetResult();
                foreach (DividendData dividend in dividends)
                {
                    if (dividend.dividendPerShare > 0)
                    {
                        var filter = Builders <BsonDocument> .Filter.Eq("symbol", dividend.symbol);

                        var dividendAsBson = dividend.ToBsonDocument();

                        collection.ReplaceOne(filter, dividendAsBson, replaceOptions);

                        recordsInsertedOrUpdated++;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Fatal(e, $"{nameof(GetDividendDataAndInsertToMongoDb)}");
            }

            return(recordsInsertedOrUpdated);
        }
Beispiel #10
0
        protected override void BeginProcessing()
        {
            if (MyInvocation.ExpectingInput)
            {
                if (_FilterSet)
                {
                    throw new PSArgumentException(Res.ParameterFilter2);
                }
            }
            else
            {
                if (_Filter == null)
                {
                    throw new PSArgumentException(Res.ParameterFilter1);
                }
            }

            if (Options == null)
            {
                Options = new ReplaceOptions();
            }
            if (Add)
            {
                Options.IsUpsert = true;
            }
        }
Beispiel #11
0
 public async Task UpsertAsync(ScheduledMatch matchIn)
 {
     var options = new ReplaceOptions {
         IsUpsert = true
     };
     await _collection.ReplaceOneAsync(
         match => match.Id == matchIn.Id, matchIn, options);
 }
Beispiel #12
0
        public string Replace(string text, IDictionary<string, object> data, ReplaceOptions options) {
            var tokenset = Parse(text);
            var tokens = tokenset.Item2;
            var replacements = Evaluate(options.Predicate == null ? tokens : tokens.Where(options.Predicate), data);

            return replacements.Aggregate(tokenset.Item1,
                (current, replacement) => current.Replace("{" + replacement.Key + "}", (options.Encoding ?? ReplaceOptions.NoEncode)(replacement.Key, replacement.Value)));
        }
Beispiel #13
0
        public virtual async Task UpsertAsync(FilterDefinition <TEntity> filter, TEntity entity)
        {
            var options = new ReplaceOptions {
                IsUpsert = true
            };

            await Collection.ReplaceOneAsync(filter, entity, options);
        }
Beispiel #14
0
 public async Task ReplaceOneAtomicallyAsync(Expression <Func <T, bool> > filter, T document, bool isUpsert = false, CancellationToken token = default)
 {
     var replaceOptions = new ReplaceOptions()
     {
         IsUpsert = isUpsert
     };
     await _collection.ReplaceOneAsync(filter, document, replaceOptions, token);
 }
Beispiel #15
0
 public async Task ProcessAsync(IClientSessionHandle session, CancellationToken token)
 {
     var replaceOptions = new ReplaceOptions()
     {
         IsUpsert = _isUpsert
     };
     await _mongoCollection.ReplaceOneAsync(session, _filter, _object, replaceOptions, token);
 }
Beispiel #16
0
        public Task SaveAsync <T>(T item) where T : IEntity
        {
            var opt = new ReplaceOptions {
                IsUpsert = true
            };

            return(GetCollection <T>().ReplaceOneAsync(s => s.Id == item.Id, item, opt));
        }
 public async Task UpsertAsync(Scorer scorerIn)
 {
     var options = new ReplaceOptions {
         IsUpsert = true
     };
     await _collection.ReplaceOneAsync(
         scorer => scorer.Id == scorerIn.Id, scorerIn, options);
 }
Beispiel #18
0
 public DefaultCallistoReplace(string operationName, T replacement, 
     FilterDefinition<T> filterDefinition, ReplaceOptions replaceOptions)
 {
     OperationName = operationName;
     Replacement = replacement;
     FilterDefinition = filterDefinition;
     ReplaceOptions = replaceOptions;
 }
Beispiel #19
0
 public Task <ReplaceOneResult> ReplaceOneAsync(
     Expression <Func <TDocument, bool> > filter,
     TDocument replacement,
     ReplaceOptions options = null,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     return(_collection.ReplaceOneAsync(filter, replacement, options, cancellationToken));
 }
Beispiel #20
0
        public virtual void Upsert(FilterDefinition <TEntity> filter, TEntity entity)
        {
            var options = new ReplaceOptions {
                IsUpsert = true
            };

            Collection.ReplaceOne(filter, entity, options);
        }
Beispiel #21
0
        public async Task Update(Account account, IFinanceStatement financeStatement)
        {
            Entities.FinanceStatement financeStatementEntity = new Entities.FinanceStatement
            {
                Id            = financeStatement.Id,
                Title         = financeStatement.Title,
                ReferenceDate = financeStatement.ReferenceDate,
                AccountId     = account.Id,
            };

            var replaceOptions = new ReplaceOptions {
                IsUpsert = true
            };
            var financeStatementFilter = Builders <Entities.FinanceStatement> .Filter.Eq(x => x.Id, financeStatement.Id);

            if (financeStatement is Income)
            {
                await _context.Incomes.ReplaceOneAsync(financeStatementFilter, financeStatementEntity, replaceOptions);
            }

            if (financeStatement is Expense)
            {
                await _context.Expenses.ReplaceOneAsync(financeStatementFilter, financeStatementEntity, replaceOptions);
            }

            if (financeStatement is Investment)
            {
                await _context.Investments.ReplaceOneAsync(financeStatementFilter, financeStatementEntity, replaceOptions);
            }

            await _context.AmountRecords
            .Find(x => x.FinanceStatementId == financeStatement.Id)
            .ForEachAsync(entity =>
            {
                if (!financeStatement.AmountRecords.Contains(entity.Id))
                {
                    _context.AmountRecords.DeleteOneAsync(x => x.Id == entity.Id && x.FinanceStatementId == financeStatement.Id);
                }
            });

            foreach (var amountRecord in financeStatement
                     .AmountRecords
                     .GetAmountRecords())
            {
                var amountRecordEntity = new Entities.AmountRecord
                {
                    Id                 = amountRecord.Id,
                    Amount             = amountRecord.Amount,
                    Description        = amountRecord.Description,
                    FinanceStatementId = financeStatement.Id
                };

                await _context.AmountRecords
                .ReplaceOneAsync(x => x.Id == amountRecord.Id && x.FinanceStatementId == financeStatement.Id,
                                 amountRecordEntity,
                                 replaceOptions);
            }
        }
        public virtual Task AddOrUpdateItemAsync <T>(T item, string collectionName) where T : IBaseModel
        {
            var collection = _mongoDatabase.GetCollection <T>(collectionName);
            var options    = new ReplaceOptions {
                IsUpsert = true
            };

            return(collection.ReplaceOneAsync(x => x.ExternalId == item.ExternalId, item, options));
        }
 /// <summary>
 /// 替换单条(自动更新UpdateTime字段)
 /// </summary>
 /// <typeparam name="T">文档类型</typeparam>
 /// <param name="filter">过滤器</param>
 /// <param name="document">文档对象</param>
 /// <param name="options">替换操作设置</param>
 /// <param name="cancellationToken">取消操作设置</param>
 /// <returns></returns>
 public ReplaceOneResult WhereReplaceOne <T>(
     FilterDefinition <T> filter,
     T document,
     ReplaceOptions options = null,
     CancellationToken cancellationToken = default) where T : BaseMongoEntity
 {
     document.UpdateTime = DateTime.Now;
     return(Database.GetCollection <T>(typeof(T).Name).ReplaceOne(filter, document, options, cancellationToken));
 }
Beispiel #24
0
        public Task ReplaceAndAddAsync(TEntity obj)
        {
            var options = new ReplaceOptions
            {
                IsUpsert = true
            };

            return(_dbCol.ReplaceOneAsync <TEntity>(e => e.Id == obj.Id, obj, options));
        }
Beispiel #25
0
 public async Task UpsertAsync(TablePosition tablePositionIn)
 {
     var options = new ReplaceOptions {
         IsUpsert = true
     };
     await _table.ReplaceOneAsync(
         tablePosition => tablePosition.Id == tablePositionIn.Id, tablePositionIn,
         options);
 }
Beispiel #26
0
        /// <summary>
        ///     Replaces document in DB, based on _id
        /// </summary>
        /// <param name="objectToSave"></param>
        public async Task <ReplaceOneResult> UpdateAsync(Tdb objectToSave)
        {
            FilterDefinition <Tdb> filter = new BsonDocumentFilterDefinition <Tdb>(new BsonDocument("_id", objectToSave.Id));
            var updateOptions             = new ReplaceOptions {
                IsUpsert = false
            };                                                           // update or insert / upsert

            return(await Collection.ReplaceOneAsync(filter, objectToSave, updateOptions));
        }
Beispiel #27
0
 /// <summary>
 /// 替换单条(自动更新UpdateTime字段)
 /// </summary>
 /// <typeparam name="T">文档类型</typeparam>
 /// <param name="filter">过滤器</param>
 /// <param name="document">文档对象</param>
 /// <param name="options">替换操作设置</param>
 /// <param name="cancellationToken">取消操作设置</param>
 /// <returns></returns>
 public Task <ReplaceOneResult> WhereReplaceOneAsnyc <T>(
     FilterDefinition <T> filter,
     T document,
     ReplaceOptions options = null,
     CancellationToken cancellationToken = default)
     where T : BaseMongoEntity
 {
     return(Task.Run(() => WhereReplaceOne(filter, document, options, cancellationToken)));
 }
Beispiel #28
0
        public virtual void Upsert(TEntity entity)
        {
            var options = new ReplaceOptions {
                IsUpsert = true
            };
            var filter = Builders <TEntity> .Filter.Eq(x => x.Id, entity.Id);

            Collection.ReplaceOne(filter, entity, options);
        }
Beispiel #29
0
        public string Replace(string text, IDictionary <string, object> data, ReplaceOptions options)
        {
            var tokenset     = Parse(text);
            var tokens       = tokenset.Item2;
            var replacements = Evaluate(options.Predicate == null ? tokens : tokens.Where(options.Predicate), data);

            return(replacements.Aggregate(tokenset.Item1,
                                          (current, replacement) => current.Replace("{" + replacement.Key + "}", (options.Encoding ?? ReplaceOptions.NoEncode)(replacement.Key, replacement.Value))));
        }
Beispiel #30
0
 /// <summary>
 /// 替换单条(自动更新UpdateTime字段)
 /// </summary>
 /// <typeparam name="T">文档类型</typeparam>
 /// <param name="id">文档默认ID</param>
 /// <param name="document">文档对象</param>
 /// <param name="options">替换操作设置</param>
 /// <param name="cancellationToken">取消操作设置</param>
 /// <returns></returns>
 public Task <ReplaceOneResult> WhereReplaceOneAsnyc <T>(
     string id,
     T document,
     ReplaceOptions options = null,
     CancellationToken cancellationToken = default)
     where T : BaseMongoEntity
 {
     return(Task.Run(() => WhereReplaceOne(id, document, options, cancellationToken)));
 }
Beispiel #31
0
        public virtual async Task UpsertAsync(TEntity entity)
        {
            var options = new ReplaceOptions {
                IsUpsert = true
            };
            var filter = Builders <TEntity> .Filter.Eq(x => x.Id, entity.Id);

            await Collection.ReplaceOneAsync(filter, entity, options);
        }
        public string Replace(string text, IDictionary<string, object> data, ReplaceOptions options) {
            if (String.IsNullOrEmpty(text)) {
                return String.Empty;
            }

            // do we have to replace tokens with hashes ?
            bool hashMode = text.Contains("#{");

            var tokenset = Parse(text, hashMode);
            var tokens = tokenset.Item2;
            var replacements = Evaluate(options.Predicate == null ? tokens : tokens.Where(options.Predicate), data);

            return replacements.Aggregate(tokenset.Item1,
                (current, replacement) => current.Replace((hashMode ? "#{" : "{") + replacement.Key + "}", (options.Encoding ?? ReplaceOptions.NoEncode)(replacement.Key, replacement.Value)));
        }
 public string Replace(string text, object data, ReplaceOptions options) {
     return Replace(text, new RouteValueDictionary(data), options);
 }