public void Insert(LoggedEvent log) { var e = _events.FindById(log.Id); if (e == null) { try { _events.Insert(new Event { Id = log.Id, Host = log.Host, Type = log.Type, StartTime = log.TimeStamp }); return; } catch (Exception ex) { if (!ex.Message.Contains("duplicate")) { throw ex; } } } if (e == null) { e = _events.FindById(log.Id); } e.Duration = Math.Abs(e.StartTime - log.TimeStamp); e.Alert = e.Duration > Event.AlertTreshold; _events.Update(e); }
public IActionResult Detail(int id) { var challenge = _challengeCollection.FindById(id); if (challenge == null) { return(NotFound()); } return(View(new ChallengeDetailViewModel { Id = challenge.Id, Title = challenge.Title, Description = challenge.Description, Bet = challenge.Bet, Start = challenge.Start, End = challenge.End, Participants = ( from p in challenge.Participants let checkins = _checkinCollection.Find(c => c.UserId == p.UserId && c.ChallengeId == id).ToList() let firstCheckin = checkins.OrderBy(c => c.CheckinDate).FirstOrDefault() let lastCheckin = checkins.OrderByDescending(c => c.CheckinDate).FirstOrDefault() select new ChallengeParticipantViewModel { UserId = p.UserId, Name = p.Name, Joined = p.Joined, StartingWeight = firstCheckin?.Weight, LastCheckin = lastCheckin?.CheckinDate, LastWeight = lastCheckin?.Weight, Weightloss = firstCheckin?.Weight - lastCheckin?.Weight }).ToList() })); }
/// <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 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); }
public T Get(T defaultValue) { var entity = _collection.FindById(_id); if (entity is null) { return(defaultValue); } return(entity.Value); }
/// <summary> /// 修改一条数据 /// </summary> /// <param name="id">Id</param> /// <param name="data">数据</param> /// <returns></returns> public new ReturnPost UpData(string id, entity.Project data) { var old = _col.FindById(id); var updata = Class2Class.C2C(old, data); if (_col.Update(updata)) { return new ReturnPost() { Data = updata, Message = true }; } return new ReturnPost() { Message = false }; }
public string GetConfig(string userId) { var obj = liteCollection.FindById(userId); if (obj != null) { return(obj.Config); } return(null); }
public void CreateEmployeeHistory(Guid employeeId, Guid managerId, Title title, Level level, Decimal salary, Decimal bonus, ActionType action, DateTime date) { LiteCollection <Employee> employees = PersistenceStore.Current.GetEmployeeStore(); var employee = employees.FindById(employeeId); var manager = managerId == Guid.Empty ? new Employee() { Id = Guid.Empty } : employees.FindById(managerId); HistoryFactory.CreateHistory(employee, manager, title, level, salary, bonus, action, date); }
public Result <GiftAidDeclaration> ReadRecord(int id) { var donation = _declarations.FindById(id); if (donation == null) { return(Result.Fail <GiftAidDeclaration>(null, $"Could not find donation with id: {id}.", ErrorType.DonationNotFound)); } return(Result.Ok(donation)); }
public T Get <T>(string key) { var record = _valueCollection.FindById(key); if (record == null) { return(default(T)); } return((T)record.Value); }
public IActionResult Checkin(int challengeId) { var challenge = _challengeCollection.FindById(challengeId); if (challenge == null) { return(NotFound()); } return(View(challenge)); }
/// <summary> /// Checks to see if the key exists in the Barrel. /// </summary> /// <param name="key">Unique identifier for the entry to check</param> /// <returns>If the key exists</returns> public bool Exists(string key) { if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentException("Key can not be null or empty.", nameof(key)); } var ent = col.FindById(key); return(ent != null); }
public void Get(IModelRequest req) { var customer = customers.FindById(new ObjectId(req.PathParam("id"))); if (customer == null) { req.NotFound(); } else { req.Model(customer); } }
private void TimesheetDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) { int ID = int.Parse(TimesheetDataGridView.Rows[e.RowIndex].Cells["IDColumn"].Value.ToString()); TimesheetRecord iTimesheetRecord = m_timesheets.FindById(ID); switch (TimesheetDataGridView.Columns[e.ColumnIndex].Name) { case "ClientColumn": iTimesheetRecord.Client = TimesheetDataGridView.Rows[e.RowIndex].Cells["ClientColumn"].Value.ToString(); break; case "ProjectColumn": iTimesheetRecord.Project = TimesheetDataGridView.Rows[e.RowIndex].Cells["ProjectColumn"].Value.ToString(); break; case "DateColumn": iTimesheetRecord.TaskDate.FromString(TimesheetDataGridView.Rows[e.RowIndex].Cells["DateColumn"].Value.ToString()); break; case "TaskColumn": iTimesheetRecord.TaskTitle = TimesheetDataGridView.Rows[e.RowIndex].Cells["TaskColumn"].Value.ToString(); break; case "StartTimeColumn": iTimesheetRecord.StartTime.FromString(TimesheetDataGridView.Rows[e.RowIndex].Cells["StartTimeColumn"].Value.ToString()); break; case "EndTimeColumn": iTimesheetRecord.EndTime.FromString(TimesheetDataGridView.Rows[e.RowIndex].Cells["EndTimeColumn"].Value.ToString()); break; } m_timesheets.Update(iTimesheetRecord); }
private string GetUserId(string userName) { lock (userIdLock) { var cache = cacheCollection.FindById(userName); if (cache != null) { return(cache.Id); } WaitRequest(); var idUrl = string.Format( @"http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key={0}&vanityurl={1}", Steam.ApiKey, userName); var idStringResult = httpClient.GetStringAsync(idUrl).GetAwaiter().GetResult(); var idResult = JsonConvert.DeserializeObject <ResolveVanityResult>(idStringResult); if (idResult.response.success == 42) { throw new Exception("Failed to resolve Steam user id: " + idResult.response.message); } cacheCollection.Insert(new SteamNameCache() { Id = idResult.response.steamid, Name = userName, UpdateDate = DateTime.Now }); return(idResult.response.steamid); } }
public async Task Refresh() { var result = await backendService.GetSpeakSessions().ConfigureAwait(false); foreach (var room in result.SpeakSessions.Select(s => s.Room)) { if (rooms.FindById(room.Id) == null) { rooms.Insert(room); } else { rooms.Update(room); } } foreach (var session in result.SpeakSessions) { if (collection.FindById(session.Id) == null) { collection.Insert(session); } else { collection.Update(session); } } }
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)); } }
public VpdbRelease GetRelease(string releaseId) { var release = _releases.Include(x => x.Game).FindById(releaseId); if (release == null) { return(null); } if (release.Game.Backglass != null) { release.Game.Backglass = _files.FindById(release.Game.Backglass.Id); } if (release.Game.Logo != null) { release.Game.Logo = _files.FindById(release.Game.Logo.Id); } release.Versions.ToList().ForEach(version => { version.Files.ToList().ForEach(file => { file.Reference = _files.FindById(file.Reference.Id); file.PlayfieldImage = _files.FindById(file.PlayfieldImage.Id); if (file.PlayfieldVideo != null) { file.PlayfieldVideo = _files.FindById(file.PlayfieldVideo.Id); } file.Compatibility = file.Compatibility.Select(build => _builds.FindById(build.Id)).ToList(); }); }); release.Authors.ToList().ForEach(author => { author.User = _users.FindById(author.User.Id); }); return(release); }
public FinanceWindow() { InitializeComponent(); using (var db = new LiteDatabase("pcclinic.db")) { LiteCollection <Finance> financeCollection = db.GetCollection <Finance>("finances"); string query; try { query = financeCollection.FindById(1).Money.ToString(); } catch (NullReferenceException) { // LiteCollection <Finance> financeCOllection = db.GetCollection <Finance>("finances"); Finance finance = new Finance(0m); financeCollection.Insert(finance); query = financeCOllection.FindById(1).Money.ToString(); } lblMoney.Content = "Money: £" + query; } }
private void ReadAndUpgradeStats() { meta = database.GetMetaData(StatsTable); trackEntries = database.GetCollection <StatsData>(StatsTable); trackEntries.EnsureIndex(x => x.Time); if (meta.Version != StatsVersion) { statsPoints = new StatsMeta { LastSend = Tools.Now, }; meta.Version = StatsVersion; UpdateMeta(); } else { statsPoints = JsonConvert.DeserializeObject <StatsMeta>(meta.CustomData, JsonSettings); // Upgrade steps here } overallStats = trackEntries.FindById(0); if (overallStats is null) { overallStats = new StatsData { Id = 0 }; } }
GetById(int id) { try { DTO.UsersDTO dataSet = dataColl.FindById(id); Response <DTO.UsersDTO> response = null; if (dataSet != null) { response = new Response <DTO.UsersDTO>() { Result = Response.Results.success, Data = dataSet }; } else { response = new Response <DTO.UsersDTO>() { Result = Response.Results.notSuccess, Message = "Not Found" }; } return(response); } catch (Exception ex) { return(new Response <DTO.UsersDTO> { Result = Response.Results.error, Message = ex.Message }); } }
public static Task OnHttpRequest <T, O>(Microsoft.AspNetCore.Http.HttpContext e, string path, O context, LiteCollection <T> collec, ArrayActionsCreate <T, O> create, ArrayActionsSelectGet <T, O> selectGet, ArrayActionsSelectPost <T, O> selectPost, ArrayActionsSelectDelete <T, O> selectDelete) { var method = Program.FindRequestMethod(e); //If the action is "@new", create a new one if (path == "@new" && method == RequestHttpMethod.post) { return(create(e, context)); } //Find it in the collection by ID T entry = collec.FindById(path); if (entry != null) { if (method == RequestHttpMethod.get) { return(selectGet(e, entry, context)); } if (method == RequestHttpMethod.post) { return(selectPost(e, entry, context)); } if (method == RequestHttpMethod.delete) { return(selectDelete(e, entry, context)); } } //Throw not found throw new StandardError("Array Element Not Found", StandardErrorCode.NotFound); }
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)); } }
public static SMessage DeleteSMessage(SMessage smessage) { LiteDatabase db = null; try { ConnectionString cn = ldbConfig.ldbSMessageConnectionString; db = new LiteDatabase(cn); LiteCollection <SMessage> dbSMessage = db.GetCollection <SMessage>("SMessage"); //dbSMessage.Delete(Query.EQ("Id", smessage.Id)); //LiteCollection<SMessage> lst=dbSMessage.Where(x => x.Id == smessage.Id).ToList<SMessage>(); SMessage sm = dbSMessage.FindById(smessage.Id); if (sm != null) { sm.IsDeleted = 1; } dbSMessage.Update(sm); //List<SMessage> lst = dbSMessage.FindAll().Where(x => x.IsDeleted != 1).ToList<SMessage>(); return(sm); } catch (Exception ex) { DBHelper.LogFile(ex); return(null); } }
/// <summary> /// 获取远程桌面的设置信息,包含分辨率和音频重定向等. /// </summary> public static DbItemSetting GetRemoteSetting(DbItemRemoteLink itemRemoteLink) { if (itemRemoteLink.Type == (int)RemoteType.rdp) { return(_tableSetting_rdp.FindById(itemRemoteLink.Id)); } if (itemRemoteLink.Type == (int)RemoteType.ssh) { return(_tableSetting_ssh.FindById(itemRemoteLink.Id)); } if (itemRemoteLink.Type == (int)RemoteType.telnet) { return(_tableSetting_telnet.FindById(itemRemoteLink.Id)); } return(null); }
public async Task <Client> GetClient(int id) { var c = await Task.Run(() => { return(clients.FindById(id)); }); return(c); }
public T Get(Guid id) { Connect(); var result = _coll.FindById(id); Disconnect(); return(result); }
/// <summary> /// 获取配色的相关信息 /// </summary> /// <param name="name"></param> /// <returns></returns> public static DbPuttyColor GetPuttyColor(string name) { if (string.IsNullOrEmpty(name)) { name = "默认配色"; } return(_tablePuttyColor.FindById(name)); }
public TEntity Select(int id) { try { return(collection.FindById(id)); } catch { return(null); } }
public List <Session> GetUsersSessions(string username, IQueryCollection q) { var job = q.ContainsKey("job") ? q["job"][0] : ""; var start = q.ContainsKey("start") ? q["start"][0] : ""; var end = q.ContainsKey("end") ? q["end"][0] : ""; var earned = q.ContainsKey("earned") ? q["earned"][0] : ""; Query query = Query.EQ(nameof(Session.Username), username); if (job != "") { var jobid = _users.FindById(username).Jobs.FirstOrDefault(j => j.Name == job).Id; query = Query.And(query, Query.EQ(nameof(Session.JobId), jobid)); } if (start != "" && DateTime.TryParse(start, out var s)) { query = Query.And(query, Query.Where(nameof(Session.StartDate), b => b.AsDateTime >= s)); } if (end != "" && DateTime.TryParse(end, out var e)) { query = Query.And(query, Query.Where(nameof(Session.EndDate), b => b.AsDateTime <= e)); } if (earned != "" && double.TryParse(earned, out var h)) { query = Query.And(query, Query.GTE(nameof(Session.Earned), h)); } //if(start != "" && DateTime.TryParse(start, out var s)) //{ // query = Query.And(query, Query.GTE(nameof(Session.StartDate), s)); //} //if(end != "" && DateTime.TryParse(end, out var e)) //{ // query = Query.And(query, Query.LTE(nameof(Session.EndDate), e)); //} var result = _sessions.Find(query, limit: 50).OrderByDescending(x => x.StartDate).ToList(); return(result); }