public async Task SaveTradeAsync(Trade trade)
        {
            var          item       = Mapping.Mapper.Map <TradeAdapter>(trade);
            TradeAdapter checkExist = _ordersAdapter.Find(x => x.TradeId.Equals(item.TradeId)).FirstOrDefault();

            _ordersAdapter.Upsert(item);
        }
Example #2
0
        private void TrackPoint()
        {
            var nextId = statsPoints.GenNextIndex();

            var now = Tools.Now;

            CurrentStatsData.Time = now;
            CurrentStatsData.Id   = nextId;
            var trackTime = now - runtimeLastTrack;

            runtimeLastTrack              = now;
            CurrentStatsData.TotalUptime += trackTime;
            CurrentStatsData.RunningBots  = botManager.GetRunningBotCount();
            CurrentStatsData.BotsRuntime  = TimeSpan.FromTicks(trackTime.Ticks * CurrentStatsData.RunningBots);
            foreach (var factory in runningSongsPerFactory.Values)
            {
                CurrentStatsData.SongStats.GetOrNew(factory).Playtime += trackTime;
            }

            Log.Debug("Track: {@data}", CurrentStatsData);
            trackEntries.Upsert(CurrentStatsData);
            overallStats.Add(CurrentStatsData);
            trackEntries.Upsert(overallStats);
            CurrentStatsData.Reset();

            if (UploadEnabled && statsPoints.LastSend + SendInterval < now)
            {
                var sendData = GetStatsTill(statsPoints.LastSend);
                SendStats(sendData);
                statsPoints.LastSend = now;
            }

            UpdateMeta();
        }
        public async Task SaveTraderAsync(Trader trader)
        {
            var           item       = Mapping.Mapper.Map <TraderAdapter>(trader);
            TraderAdapter checkExist = _traderAdapter.Find(x => x.Identifier.Equals(item.Identifier)).FirstOrDefault();

            _traderAdapter.Upsert(item);
        }
Example #4
0
 public void SaveRelease(VpdbRelease release)
 {
     _games.Upsert(release.Game);
     if (release.Game.Backglass != null)
     {
         _files.Upsert(release.Game.Backglass);
     }
     if (release.Game.Logo != null)
     {
         _files.Upsert(release.Game.Logo);
     }
     release.Versions.ToList().ForEach(version => {
         version.Files.ToList().ForEach(file => {
             _files.Upsert(file.Reference);
             _files.Upsert(file.PlayfieldImage);
             if (file.PlayfieldVideo != null)
             {
                 _files.Upsert(file.PlayfieldVideo);
             }
             file.Compatibility.ToList().ForEach(build => _builds.Upsert(build));
         });
     });
     release.Authors.ToList().ForEach(author => {
         _users.Upsert(author.User);
     });
     _releases.Upsert(release);
 }
Example #5
0
        public void addEntities(List <CoreEntity> coreList)
        {
            List <PortalInfo> upportals = new List <PortalInfo>();

            foreach (CoreEntity ent in coreList)
            {
                if (ent is PortalEntity)
                {
                    PortalEntity pent = (PortalEntity)ent;
                    PortalInfo   p    = AllPortals.FindOne(x => x.Guid.Equals(ent.Guid));
                    if (p == null)
                    {
                        p           = new PortalInfo();
                        p.Enabled   = false;
                        p.Guid      = pent.Guid;
                        p.ShowLabel = false;

                        p.AddressName = "";
                        p.Country     = "";
                        p.County      = "";
                        p.Road        = "";
                        p.Suburb      = "";
                        p.Village     = "";
                    }
                    p.Lastrefresh = DateTime.UtcNow;
                    p.Pos         = pent.Pos;
                    p.Name        = pent.Name;

                    p.Team     = pent.Team;
                    p.Level    = pent.Level;
                    p.Health   = pent.Health;
                    p.ResCount = pent.ResCount;
                    p.Image    = pent.Image;
                    p.Mission  = pent.Mission;
                    p.MapTile  = pent.MapTile;

                    upportals.Add(p);
                }
                if (ent is LinkEntity)
                {
                    LinkEntity le = (LinkEntity)ent;
                    otherLinks.Upsert(le.parseToDataset());
                    PortalInfo p = AllPortals.FindById(le.OGuid);
                    if (p != null)
                    {
                        p.Team = le.Team;
                        AllPortals.Upsert(p);
                    }
                    p = AllPortals.FindById(le.DGuid);
                    if (p != null)
                    {
                        p.Team = le.Team;
                        AllPortals.Upsert(p);
                    }
                }
            }
            AllPortals.Upsert(upportals);
        }
        /// <summary>
        /// A private method to process transactions from API and store as ledgers in local data store.
        /// </summary>
        /// <param name="txs">Transactions from API</param>
        /// <returns>None.</returns>
        private async Task ProcessingLedger(ApiTransactionCollections txs)
        {
            if (txs.txs.Count() > 0)
            {
                foreach (var tx in txs.txs)
                {
                    tx.blockheight = await api.GetBlockHeight(tx.blockhash);

                    var record = tx.ToLedger(contract, contractService);
                    if (record != null && !ledger.Exists(Query.EQ("TxId", record.TxId)))
                    {
                        record.Status = ProcessStatus.NotProcessed;
                        ledger.Upsert(record);
                    }
                }
                ledger.EnsureIndex(l => l.TxId);
                ledger.EnsureIndex(l => l.Blockheight);
                ledger.EnsureIndex(l => l.Operation);
                ledger.EnsureIndex(l => l.TokenSenderHash);
                ledger.EnsureIndex(l => l.TokenReceiverHash);
                ledger.EnsureIndex(l => l.Time);
                contract.LastSyncedBlock = txs.txs.Max(t => t.blockheight);
                contractService.UpdateContract(contract);
            }
        }
Example #7
0
 private void PrepareData(LiteCollection <Item> collection)
 {
     collection.Upsert(new Item()
     {
         Id = "C", Value = "Value 1"
     });
     collection.Upsert(new Item()
     {
         Id = "A", Value = "Value 2"
     });
     collection.Upsert(new Item()
     {
         Id = "B", Value = "Value 1"
     });
 }
        public void AddFaceInfo(string imageFile, double[] doubleInfo, int left, int right, int top, int bottom)
        {
            string           imageFileLower   = imageFile.ToLower();
            FaceEncodingInfo faceEncodingInfo = GetFromDB(imageFileLower);

            //if (faceEncodingInfo != null)
            //    throw new Exception($"{imageFile} уже есть в базе!");

            if (faceEncodingInfo == null)
            {
                faceEncodingInfo = new FaceEncodingInfo(imageFileLower);
            }

            FingerAndLocation fingerAndLocation = new FingerAndLocation();

            fingerAndLocation.FingerPrint = doubleInfo;
            fingerAndLocation.Left        = left;
            fingerAndLocation.Right       = right;
            fingerAndLocation.Top         = top;
            fingerAndLocation.Bottom      = bottom;

            var fingerAndLocations = _fingerCollection.Find(f => f.Equals(fingerAndLocation));

            if (fingerAndLocations.Any())
            {
                fingerAndLocation.Id = fingerAndLocations.Single().Id;
            }
            else
            {
                _fingerCollection.Insert(fingerAndLocation);
            }

            //if (!faceEncodingInfo.FingerAndLocations.Any(fe => fe.Equals(fingerAndLocation)))
            if (!faceEncodingInfo.FingerAndLocations.Any(fe => fe.Bottom == fingerAndLocation.Bottom &&
                                                         fe.Left == fingerAndLocation.Left &&
                                                         fe.Right == fingerAndLocation.Right &&
                                                         fe.Top == fingerAndLocation.Top &&
                                                         fe.FingerPrint.SequenceEqual(fingerAndLocation.FingerPrint)))
            {
                faceEncodingInfo.FingerAndLocations.Add(fingerAndLocation);
            }

            _faceCollection.Upsert(faceEncodingInfo);

            //var info = _faceCollection.Include(x => x.FingerAndLocations).FindById(imageFile);
            //if (info.FingerAndLocations.First().Left != faceEncodingInfo.FingerAndLocations.First().Left)
            //    throw new Exception("Данные не сохранились!");
        }
Example #9
0
 internal static void Save(ChatCache cChat)
 {
     lock (chatCacheCol)
     {
         chatCacheCol.Upsert(cChat);
     }
 }
Example #10
0
        private bool Add(string key, string data, TimeSpan expireIn)
        {
            if (data == null)
            {
                return(false);
            }

            var success = false;

            try
            {
                var item = new CacheItem
                {
                    Id             = key,
                    ExpirationDate = GetExpiration(expireIn),
                    Contents       = data
                };

                _col.Upsert(item);

                success = true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }

            return(success);
        }
 public void SavePartial(PartialSession partial)
 {
     lock (_partialSessions)
     {
         _partialSessions.Upsert(partial.ToData());
     }
 }
 public void SaveSession(EnrichmentSession session)
 {
     lock (_sessions)
     {
         _sessions.Upsert(session.ToData());
     }
 }
        public Summary SaveSummary(Summary summary)
        {
            var dbModel = summary.ToDbModel();

            _summaries.Upsert(dbModel);
            return(dbModel.ToDomainModel());
        }
        public async Task <ServicesResponse <ulong> > Get(ulong gameId)
        {
            var cache = cacheCollection.FindById(gameId);

            if (cache != null)
            {
                return(new ServicesResponse <ulong>(cache.igdbId));
            }

            var url = string.Format(@"/games/?fields=name,id&filter[external.steam][eq]={0}&limit=1", gameId);
            var libraryStringResult = await IGDB.SendStringRequest(url);

            var games = JsonConvert.DeserializeObject <List <Game> >(libraryStringResult);

            if (games.Any())
            {
                cacheCollection.Upsert(new SteamIdGame()
                {
                    steamId       = gameId,
                    igdbId        = games.First().id,
                    creation_time = DateTime.Now
                });

                return(new ServicesResponse <ulong>(games.First().id));
            }
            else
            {
                return(new ServicesResponse <ulong>(0));
            }
        }
Example #15
0
        /// <inheritdoc />
        public void SaveOrUpdate(TDoc document)
        {
            var save             = DocumentAdapter.IsTransient(document);
            var incrementVersion = save;

            if (!save)
            {
                var id          = DocumentAdapter.GetId(document);
                var existingDoc = _documents.FindById(id);
                save = existingDoc == null;
                if (!save)
                {
                    incrementVersion = save = DocumentAdapter.IsChanged(existingDoc, document);
                }
            }

            if (save)
            {
                if (incrementVersion)
                {
                    DocumentAdapter.IncrementVersion(document);
                }
                _documents.Upsert(document);
            }
        }
        public async Task SaveWalletTransactionAsync(WalletTransaction walletTransaction)
        {
            var item = Mapping.Mapper.Map <WalletTransactionAdapter>(walletTransaction);
            WalletTransactionAdapter checkExist = _walletTransactionsAdapter.Find(x => x.Id.Equals(item.Id)).FirstOrDefault();

            _walletTransactionsAdapter.Upsert(item);
        }
        public async Task <ServicesResponse <ulong> > Get(ulong gameId)
        {
            var cache = cacheCollection.FindById(gameId);

            if (cache != null)
            {
                return(new ServicesResponse <ulong>(cache.igdbId));
            }

            var libraryStringResult = await IGDB.SendStringRequest("games",
                                                                   $"fields id; where external_games.uid = \"{gameId}\" & external_games.category = 1; limit 1;");

            var games = JsonConvert.DeserializeObject <List <Game> >(libraryStringResult);

            if (games.Any())
            {
                cacheCollection.Upsert(new SteamIdGame()
                {
                    steamId       = gameId,
                    igdbId        = games.First().id,
                    creation_time = DateTime.Now
                });

                return(new ServicesResponse <ulong>(games.First().id));
            }
            else
            {
                return(new ServicesResponse <ulong>(0));
            }
        }
Example #18
0
 /// <summary>
 /// Add stock and update references
 /// </summary>
 /// <param name="stock"></param>
 /// <returns></returns>
 public bool AddStock(Stock stock)
 {
     try
     {
         using (var db = new LiteDatabase(_dataBaseFile))
         {
             // Get a collection (or create, if doesn't exist)
             LiteCollection <Stock> currentCollection = db.GetCollection <Stock>("Stocks");
             if (currentCollection == null)
             {
                 throw new Exception("Update not possible data/collection does not exist");
             }
             if (!currentCollection.Upsert(stock))
             {
                 throw new Exception($"Upsert for stock [{stock.Id}], [{stock.Company}] failed");
             }
             SetReferences(stock.Financials);
         }
         return(true);
     }
     catch (Exception x)
     {
         Log.Error(x);
         return(false);
     }
 }
Example #19
0
 /// <summary>
 /// Insert or Update the user's contact. Public key is a primary key.
 /// </summary>
 /// <param name="name">Person's name or reference</param>
 /// <param name="publicKey">Valid Bitcoin-compatible Publickey (string)</param>
 /// <returns>An inserted or updated contact record.</returns>
 public Contact UpsertContact(string name, string publicKey)
 {
     try
     {
         var mycontact = collection.Find(c => c.Address == publicKey).FirstOrDefault();
         if (mycontact == null)
         {
             mycontact = new Contact()
             {
                 Name        = name,
                 Address     = publicKey,
                 AddressHash = new BitcoinPubKeyAddress(publicKey, MainNetwork).Hash.ToBytes()
             };
         }
         else
         {
             mycontact.Name = name;
         }
         collection.Upsert(mycontact);
         collection.EnsureIndex(c => c.Address);
         collection.EnsureIndex(c => c.AddressHash);
         collection.EnsureIndex(c => c.AddressHashString);
         return(mycontact);
     }
     catch (Exception)
     {
         return(null);
     }
 }
Example #20
0
 public void Put <T>(string key, T value)
 {
     _valueCollection.Upsert(new ValueRecord
     {
         Id    = key,
         Value = value
     });
 }
Example #21
0
        public void SetAppConfig(AppConfig appConfig)
        {
            LiteCollection <AppConfig> col = db.GetCollection <AppConfig>(appConfigCollectionName);

            col.Upsert(appConfig);
            cachedConfig     = appConfig;
            cacheRefreshTime = DateTime.Now;
        }
Example #22
0
        /// <summary>
        /// Adds a string netry to the barrel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Unique identifier for the entry</param>
        /// <param name="data">Data string to store</param>
        /// <param name="expireIn">Time from UtcNow to expire entry in</param>
        /// <param name="eTag">Optional eTag information</param>
        public void Add(string key, string data, TimeSpan expireIn, string eTag = null)
        {
            if (data == null)
            {
                return;
            }

            var ent = new Banana
            {
                Id             = key,
                ExpirationDate = DateTime.UtcNow.Add(expireIn),
                ETag           = eTag,
                Contents       = data
            };

            col.Upsert(ent);
        }
Example #23
0
        public override async Task LoadAsync()
        {
            Ocupado = true;
            try
            {
                LiteCollection <PokemonLTB> pokemonsDB = _dataBase.GetCollection <PokemonLTB>();

                if (pokemonsDB.Count() == 0)
                {
                    var pokemonsAPI = await _pokemonService.GetPokemonsAsync();

                    foreach (var pokemon in pokemonsAPI)
                    {
                        PokemonLTB pokeLTB = new PokemonLTB
                        {
                            Id     = pokemon.Id,
                            Name   = pokemon.Name.ToUpper(),
                            Height = pokemon.Height
                        };

                        pokemonsDB.Upsert(pokeLTB);

                        using (Stream stream = GetImageStreamFromUrl(pokemon.Sprites.FrontDefault.AbsoluteUri))
                        {
                            if (stream != null)
                            {
                                //Verfica se ja existe a imagem,se existir apaga
                                if (_dataBase.FileStorage.Exists(pokemon.Id.ToString()))
                                {
                                    _dataBase.FileStorage.Delete(pokemon.Id.ToString());
                                }
                                _dataBase.FileStorage.Upload(pokemon.Id.ToString(), pokemon.Name, stream);
                            }
                        }
                    }

                    pokemonsDB = _dataBase.GetCollection <PokemonLTB>();
                }



                Pokemons.Clear();

                foreach (var pokemon in pokemonsDB.FindAll())
                {
                    pokemon.Image = ImageSource.FromStream(() => _dataBase.FileStorage.FindById(pokemon.Id.ToString()).OpenRead());
                    Pokemons.Add(pokemon);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Erro", ex.Message);
            }
            finally
            {
                Ocupado = false;
            }
        }
Example #24
0
        public bool AddConfig(ConfigEntity config)
        {
            var configRecord = _config.FindAll().FirstOrDefault() ?? new ConfigEntity();

            configRecord.ProtectMode         = config.ProtectMode;
            configRecord.WhiteListExtensions = config.WhiteListExtensions;

            return(_config.Upsert(configRecord));
        }
Example #25
0
        private void AggregateMulti(LiteCollection <Addr> addrTable, string ip,
                                    int successCount, int failCount, DateTime first, DateTime last, IEnumerable <string> userNames)
        {
            var logprefix = "AggregateM(" + ip + "): ";
            var existing  = Items.TryGetValue(ip, out var addr);

            if (!existing)
            {
                addr        = new Addr();
                addr.AddrId = ip;
                Items.Add(ip, addr);
            }
            addr.FailCount    += failCount;
            addr.SuccessCount += successCount;
            if (first < addr.First)
            {
                addr.First = first;
            }
            if (last > addr.Last)
            {
                addr.Last = last;
            }
            foreach (var userName in userNames)
            {
                if (!string.IsNullOrEmpty(userName))
                {
                    addr.UserNames.Add(userName);
                }
            }

            if (updateDb)
            {
                var added = addrTable.Upsert(addr);
                if (added)
                {
                    Log(logprefix + "adding new db entry");
                }
                lastDbChange = DateTime.UtcNow;

                /* BlackList protection rule: TBD
                 * if (updateFw && addr.IsAttack(-1) && (addr.Prot & (long)Addr.ProtFlag.Blocked) == 0)
                 * {
                 *  Log(logprefix + "adding fw deny rule");
                 *  var fw = new WinFirewall();
                 *  if (fw.AddIp(false, ip, 3389, false, "RdpMon.BlackList (%PROTOCOL%)",
                 *      "Brute-force addresses black-listed by RdpMon"))
                 *  {
                 *      addr.Prot |= (long)Addr.ProtFlag.Blocked;
                 *      addrTable.Update(addr);
                 *  }
                 *  else
                 *      Log(logprefix + "* failed adding fw deny rule!");
                 * }
                 */
            }
        }
 /// <summary>
 /// Update or Insert wallet contract object to local data store.
 /// </summary>
 /// <param name="contract">A wallet contract object</param>
 /// <param name="reIndex">Re-index after insertion or updation. (Optional, default is false)</param>
 /// <returns>None.</returns>
 public void UpdateContract(WalletContract contract, bool reIndex = false)
 {
     collection.Upsert(contract);
     if (reIndex)
     {
         collection.EnsureIndex(c => c.ID);
         collection.EnsureIndex(c => c.Name);
         collection.EnsureIndex(c => c.OwnerPublicAddress);
     }
 }
Example #27
0
        /// <inheritdoc />
        public override void SetCanonicalChainId(Guid chainId)
        {
            LiteCollection <BsonDocument> collection = _db.GetCollection <BsonDocument>("canon");
            var docId = new BsonValue("canon");

            byte[] idBytes = chainId.ToByteArray();
            collection.Upsert(docId, new BsonDocument()
            {
                ["chainId"] = new BsonValue(idBytes)
            });
        }
Example #28
0
        /// <inheritdoc/>
        public override void IncreaseTxNonce(Guid chainId, Address signer, long delta = 1)
        {
            long nextNonce = GetTxNonce(chainId, signer) + delta;
            LiteCollection <BsonDocument> collection = TxNonceCollection(chainId);
            var docId = new BsonValue(signer.ToByteArray());

            collection.Upsert(docId, new BsonDocument()
            {
                ["v"] = new BsonValue(nextNonce)
            });
        }
Example #29
0
        /// <inheritdoc/>
        public override void IncreaseTxNonce(string @namespace, Address signer, long delta = 1)
        {
            long nextNonce    = GetTxNonce(@namespace, signer) + delta;
            var  collectionId = $"{NonceIdPrefix}{@namespace}";
            LiteCollection <BsonDocument> collection = _db.GetCollection <BsonDocument>(collectionId);
            var docId = new BsonValue(signer.ToByteArray());

            collection.Upsert(docId, new BsonDocument()
            {
                ["v"] = new BsonValue(nextNonce)
            });
        }
Example #30
0
        public IndexSortAndFilterTest()
        {
            _tempFile   = new TempFile();
            _database   = new LiteDatabase(_tempFile.Filename);
            _collection = _database.GetCollection <Item>("items");

            _collection.Upsert(new Item()
            {
                Id = "C", Value = "Value 1"
            });
            _collection.Upsert(new Item()
            {
                Id = "A", Value = "Value 2"
            });
            _collection.Upsert(new Item()
            {
                Id = "B", Value = "Value 1"
            });

            _collection.EnsureIndex("idx_value", x => x.Value);
        }