// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DbCtx db) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } db.Database.EnsureCreated(); app.UseCors(x => x .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
public static void AuditEntities(this DbCtx db, IPrincipal principal) { try { var modifiedEntries = db.ChangeTracker.Entries() .Where(x => x.Entity is IHasAudit <string, DateTime?> && (x.State == EntityState.Added || x.State == EntityState.Modified)); var username = principal != null ? principal.Identity.Name : "anonymous"; var now = DateTime.UtcNow; foreach (var entry in modifiedEntries) { var entity = (IHasAudit <string, DateTime?>)entry.Entity; if (entry.State == EntityState.Added) { entity.CreatedAt = now; entity.Creator = username; } else { db.Entry(entity).Property(x => x.CreatedAt).IsModified = false; db.Entry(entity).Property(x => x.Creator).IsModified = false; } entity.ModifiedAt = now; entity.Modifier = username; } } catch (Exception ex) { } }
public static async Task PostPlaying(DbCtx context, User user, TrackLocationWithProfile playing) { RETRY: var track = await context.Tracks.FindAsync(playing.trackid); var list = playing.listid > 0 ? await context.Lists.FindAsync(playing.listid) : null; if (track?.IsVisibleToUser(user) == true) { context.Plays.Add(new PlayRecord { Track = track, User = user, listid = list?.IsVisibleToUser(user) == true ? playing.listid : 0, audioprofile = playing.profile ?? "", time = DateTime.Now }); } user.last_playing = playing.ToString(); // context.Entry(user).State = EntityState.Modified; user.version++; if (await context.FailedSavingChanges()) { goto RETRY; } }
// Main code middleware code. public async Task InvokeAsync(HttpContext httpContext, DbCtx ctx) { string apiKey = httpContext.Request.Headers["ApiKey"]; string requestedEndpoint = httpContext.Request.Path; DbLog log = new DbLog(requestedEndpoint); // Log the request. User user = ctx.Users.Find(apiKey); if (user != null) { // Log request against a registered user. user.DbLogs.Add(log); } else { // Log request from unrecognised users. string guid = Guid.NewGuid().ToString(); log.Id = "unknown-" + guid; ctx.DbLogs.Add(log); } ctx.SaveChanges(); await _next(httpContext); }
/// <summary> /// 添加一个设备 /// </summary> /// <param name="title">设备的标题</param> /// <param name="worth">设备的价格</param> /// <param name="dateTime">设备的购买日期</param> /// <param name="remark">备注</param> /// <param name="equipmentTypeId">设备所属小类的Id</param> /// <param name="adminId">当前管理员的Id</param> /// <returns> /// 0 : 输入的设备种类Id不合法, /// 1 : 操作成功 /// </returns> public int AddEquipment(string title, double worth, DateTime dateTime, string remark, int equipmentTypeId, int adminId) { var equipmentType = DbCtx.EquipmentTypes .FirstOrDefault(et => et.Id == equipmentTypeId); if (equipmentType == null || equipmentType.Type == 0) { return(0); } var admin = DbCtx.Admins .FirstOrDefault(a => a.Id == adminId); //根据adminId得到admin,不能直接传进来admin给这个DbCtx用!!! if (admin == null) { throw new MyException("此处需要有管理操作", -1); } string logicId = Util.GenerateIntId(); DbCtx.Equipments.Add(new Equipment() { LogicId = logicId, Title = title, Worth = worth, PurchasingDate = dateTime, Remark = remark, State = 1, //默认正常 EquipmentType = equipmentType, User = null, Admin = admin }); DbCtx.SaveChanges(); return(1); }
/// <summary> /// 设备的归还 /// </summary> /// <param name="equipmentId"></param> /// <returns> /// 0 : 指定Id的设备不存在 /// 1 : 操作成功 /// -1 : 指定设备未被领用 /// </returns> public int ReturnEquipment(int equipmentId, string adminAccount) { var equipment = DbCtx.Equipments .FirstOrDefault(e => e.Id == equipmentId); if (equipment == null) { return(0); } if (equipment.User == null) { return(-1); } DbCtx.Histories.Add(new History() { ReturnDate = DateTime.Now, EquipmentTitle = equipment.Title, UserName = equipment.User.Name, AdminAccount = adminAccount }); //添加归还记录 equipment.User = null; //删除当前领用用户 DbCtx.Entry(equipment).State = EntityState.Modified; DbCtx.SaveChanges(); return(1); }
StartReportingActivities(Topic topic, Discussion disc, Session session) { _topic = topic; _disc = disc; _session = session; var moder = DbCtx.Get().Person.Single(p => p.Name.StartsWith("moder")); _clienRt = new ClientRT(disc.Id, ConfigManager.ServiceServer, moder.Name, moder.Id, DeviceType.Wpf); _clienRt.onJoin += OnJoined; _hardReportTCS = new TaskCompletionSource <ReportCollector>(); _remoteScreenshotTCS = new TaskCompletionSource <Dictionary <int, byte[]> >(); Task.Factory.StartNew(async() => { while (_servicingPhotonClient) { _clienRt.Service(); await Utils.Delay(80); } }, TaskCreationOptions.LongRunning); return(new Tuple <Task <Dictionary <int, byte[]> >, Task <ReportCollector> >(_remoteScreenshotTCS.Task, _hardReportTCS.Task)); }
/// TODO: MOVE public static async Task <bool> AddStickyNote(DbCtx ctx, string patientApiKey, JObject stickyJson) { try { string stickyContent = (string)stickyJson["content"]; float stickyScale = (float)stickyJson["scale"]; if (!(string.IsNullOrWhiteSpace(stickyContent) || stickyScale == 0)) { Patient patient = (Patient)GetEntityByForeignKey(ctx, patientApiKey, Collection.patients); StickyNote stickyNote = new StickyNote() { PatientId = patient.Id, Scale = stickyScale, Content = stickyContent }; patient.Stickies.Add(stickyNote); await ctx.SaveChangesAsync(); return(true); } } catch (Exception e) { Console.WriteLine(e); } return(false); }
public void HandleRecontext() { SetStyle(); Opacity = DataContext == null ? 0 : 1; //Drawing.HandleRecontext(); var ap = DataContext as ArgPoint; _commentDismissalRecognizer.Reset(ap); UpdateLocalReadCounts(DbCtx.Get(), ap); new CommentNotificationDeferral(Dispatcher, DbCtx.Get(), lstBxComments1); UpdateRemoteReadCounts(DbCtx.Get(), ap); if (DataContext == null) { EditingMode = false; } else { EditingMode = SessionInfo.Get().person.Id == ap.Person.Id; } BeginSrcNumberInjection(); UpdateOrderedSources(); BeginAttachmentNumberInjection(); UpdateOrderedMedia(); ///commentsViewer.ScrollToBottom(); }
private void LoginProcedure() { login = LoginDriver.Run(LoginFlow.ForEventGen); if (login == null) { System.Windows.Application.Current.Shutdown(); return; } if (login.discussion == null) { MessageDlg.Show( "In this application even moderator should select real, existing discussion"); System.Windows.Application.Current.Shutdown(); return; } Topics = new ObservableCollection <Topic>(login.discussion.Topic); Persons = new ObservableCollection <Person>(DaoHelpers.personsOfDiscussion(login.discussion)); setPostLoginInfo(); FillTopics(login.discussion); sharedClient.start(login, DbCtx.Get().Connection.DataSource, login.devType); sharedClient.clienRt.onStatsEvent += OnStatsEvent; }
public static async Task <IEntity> GetEntityByPrimaryKey(DbCtx ctx, string key, Collection collection) { try { switch (collection) { case Collection.users: return(await ctx.Users.FindAsync(key)); case Collection.patients: return(await ctx.Patients.FindAsync(key)); case Collection.carers: return(await ctx.Carers.FindAsync(key)); case Collection.calendars: return(await ctx.Calendars.FindAsync(key)); case Collection.stickies: return(await ctx.Stickies.FindAsync(key)); default: throw new Exception("Unknown table."); } } catch (Exception e) { Console.WriteLine("Unexpected error: " + e.Message); } return(null); }
//returns current person taken from the same context as entity is attached to public Person getPerson(object entity) { if (_person == null) { return(null); } if (entity == null) { entity = discussion; } //discussion not set if (entity == null) { return(_person); } if (IsAttachedTo(PrivateCenterCtx.Get(), entity)) { return(PrivateCenterCtx.Get().Person.FirstOrDefault(p0 => p0.Id == _person.Id)); } else if (IsAttachedTo(PublicBoardCtx.Get(), entity)) { return(PublicBoardCtx.Get().Person.FirstOrDefault(p0 => p0.Id == _person.Id)); } else if (IsAttachedTo(DbCtx.Get(), entity)) { return(DbCtx.Get().Person.FirstOrDefault(p0 => p0.Id == _person.Id)); } return(_person); }
private void ShowLargeBadgeView(ArgPoint ap) { scene.IsHitTestVisible = false; blockWorkingAreaTransforms = true; if (_lbv == null) { _lbv = new LargeBadgeView(); } var ArgPointId = ap.Id; DbCtx.DropContext();//it can become stale while modal view was closed. _lbv.DataContext = DbCtx.Get().ArgPoint.FirstOrDefault(p0 => p0.Id == ArgPointId); _lbv.SetRt(UISharedRTClient.Instance); //mainGrid.Children.Add(_lbv); int indexOfLaserScene = mainGrid.Children.IndexOf(laserScene); if (!mainGrid.Children.Contains(_lbv)) { mainGrid.Children.Insert(indexOfLaserScene, _lbv); } ResizeLargeBadgeView(); _lbv.HorizontalAlignment = HorizontalAlignment.Center; _lbv.VerticalAlignment = VerticalAlignment.Center; }
/// TODO: MOVE public static async Task <ICollection <CalendarEntry> > GetCalendarEntries(DbCtx ctx, string patientId, string pageStr, string nItemsStr) { try { int page; int nItems; int startIndex; var worker = await ctx.Patients.FindAsync(patientId); // Get only entries from todays date onwards. ICollection <CalendarEntry> entries = worker.CalendarEntries.Where(entry => entry.Start > DateTime.Now).ToList(); if (pageStr != "all") // Paginate { page = Math.Abs(int.Parse(pageStr)); nItems = Math.Abs(int.Parse(nItemsStr)); startIndex = (page - 1) * nItems; nItems = nItems - ((page * nItems) - entries.Count); List <CalendarEntry> entriesList = entries.ToList(); // Return paginated collection. return(entriesList.GetRange(startIndex, nItems)); } // Return whole collection. return(entries); } catch (Exception e) { Console.WriteLine(e); } return(null); }
public static async Task <bool> CreatePatientActivityLog(DbCtx ctx, string patientApiKey, JObject logJson) { try { var jsonDict = JObject.FromObject(logJson).ToObject <Dictionary <string, object> >(); string caption = (string)jsonDict["Caption"]; string description = (string)jsonDict["JsonDescription"]; string location = (string)jsonDict["Location"]; ActivityLog log = new ActivityLog() { Caption = caption, JsonDescription = description, Location = location, DateTime = DateTime.Now }; Patient patient = (Patient)GetEntityByForeignKey(ctx, patientApiKey, Collection.patients); patient.ActivityLogs.Add(log); await ctx.SaveChangesAsync(); return(true); } catch (Exception e) { Console.WriteLine(e); } return(false); }
/// TODO: MOVE public static async Task <ICollection <ActivityLog> > GetLogs(DbCtx ctx, string patientId, string pageStr, string nItemsStr) { try { int page; int nItems; int startIndex; var worker = await ctx.Patients.FindAsync(patientId); ICollection <ActivityLog> logs = worker.ActivityLogs; if (pageStr != "all") // Paginate { page = Math.Abs(int.Parse(pageStr)); nItems = Math.Abs(int.Parse(nItemsStr)); startIndex = (page - 1) * nItems; nItems = nItems - ((page * nItems) - logs.Count); List <ActivityLog> entriesList = logs.ToList(); // Return paginated collection. return(entriesList.GetRange(startIndex, nItems)); } // Return whole collection. return(logs); } catch (Exception e) { Console.WriteLine(e); } return(null); }
private void lstBxPersons_SelectionChanged(object sender, SelectionChangedEventArgs e) { SelectedPerson = e.AddedItems[0] as Person; decoration.SetGreetingName(SelectedPerson.Name); //enum all discussions of the person if (SelectedPerson != null) { DiscCtx ctx = DbCtx.Get(); IQueryable <Discussion> myDiscussions = (from t in ctx.Topic where t.Person.Any(p0 => p0.Id == SelectedPerson.Id) select t.Discussion).Distinct(); _discussions.Clear(); foreach (var d in myDiscussions) { _discussions.Add(d); } //add dummy discussion for moderator if (SelectedPerson.Name.StartsWith("moder")) { _discussions.Add(DummyDiscussion); } lblSelDiscussion.Visibility = Visibility.Visible; } else { lblSelDiscussion.Visibility = Visibility.Hidden; } }
public static IEntity GetEntityByForeignKey(DbCtx ctx, string key, Collection collection) { try { IEntity e; switch (collection) { case Collection.patients: e = ctx.Patients .Where(p => p.User.ApiKey == key) .FirstOrDefault(); break; case Collection.carers: e = ctx.Carers .Where(c => c.User.ApiKey == key) .FirstOrDefault(); break; default: throw new Exception("Unknown table."); } return(e); } catch (Exception e) { Console.WriteLine("Unexpected error: " + e.Message); } return(null); }
/// TODO: MOVE public static async Task <bool> MessagePatient(DbCtx ctx, string carerApiKey, string patientId, JObject messageJson) { try { var jsonDict = JObject.FromObject(messageJson).ToObject <Dictionary <string, object> >(); string title = (string)jsonDict["Title"]; string message = (string)jsonDict["Message"]; Carer carer = (Carer)GetEntityByForeignKey(ctx, carerApiKey, Collection.carers); if (carer != null) { Patient patient = (Patient) await GetEntityByPrimaryKey(ctx, patientId, Collection.patients); if (patient != null) { PatientMessage messageObj = new PatientMessage() { Read = null, Sent = DateTime.Now, Title = title, Message = message, CarerId = carer.Email }; patient.Messages.Add(messageObj); await ctx.SaveChangesAsync(); return(true); } } return(false); } catch (Exception e) { Console.WriteLine(e); return(false); } }
public AccountService(IConfiguration config, UserManager <User> userManager, RoleManager <IdentityRole> roleManager, IEmailSenderService emailSender, DbCtx ctx) { this.config = config; this.userManager = userManager; this.roleManager = roleManager; this.emailSender = emailSender; this.ctx = ctx; }
public static IEnumerable <Person> personsOfDiscussion(Discussion d) { var q = from p in DbCtx.Get().Person where p.Topic.Any(t0 => t0.Discussion.Id == d.Id) select p; return(q); }
/// <summary> /// Given the info record saves it to repository. /// </summary> /// <param name="info">Record information to save.</param> public void Save(ProductInfo info) { SetupHelpers(); Product p = Mapper.Map <ProductInfo, Product>(info); DbCtx.Products.AddObject(p); DbCtx.SaveChanges(); }
void SaveProcedure() { var ap = DataContext as ArgPoint; if (ap == null) { return; } if (DateTime.Now.Subtract(_lastSave).TotalMilliseconds < 100) { return; } _lastSave = DateTime.Now; var lastComment = ap.Comment.LastOrDefault(); //finalize edited comment if (!string.IsNullOrWhiteSpace(txtNewComment.Text) && DaoUtils.NEW_COMMENT != txtNewComment.Text) { if (lastComment == null || (lastComment != null && txtNewComment.Text != lastComment.Text)) { DaoUtils.HandleCommentCommit(txtNewComment.Text, ap); //txtNewComment.Text = DaoUtils.NEW_COMMENT; txtNewComment.Text = ""; } } if (!ap.ChangesPending) { return; } ap.ChangesPending = false; //save changes try { DbCtx.Get().SaveChanges(); } catch { } if (_sharedClient != null) { _sharedClient.clienRt.SendStatsEvent(StEvent.BadgeEdited, SessionInfo.Get().person.Id, ap.Topic.Discussion.Id, ap.Topic.Id, DeviceType.Wpf); _sharedClient.clienRt.SendArgPointChanged(ap.Id, ap.Topic.Id, SessionInfo.Get().person.Id); } }
public DbCtx GetDbContext() { var options = new DbContextOptionsBuilder <DbCtx>() .UseInMemoryDatabase(databaseName: "DbCtx_Test") .Options; var dbContext = new DbCtx(options); return(dbContext); }
public static IEnumerable <Discussion> discussionsOfSession(Session s) { var sessionId = s.Id; var q = from d in DbCtx.Get().Discussion where d.GeneralSide.Any(gs0 => gs0.Person.Session.Id == sessionId) select d; return(q); }
public void create_varioTrigger() { var trigger = new VarioTrigger { Sensors = _ports, }; DbCtx.Triggers.Add(trigger); DbCtx.SaveChanges(); }
public void create_pulsetrigger() { var trigger = new PushTrigger { Sensors = _ports }; DbCtx.Triggers.Add(trigger); DbCtx.SaveChanges(); }
public void create_switchTrigger() { var trigger = new SwitchTrigger { Sensors = _ports, TriggerOnState = true, }; DbCtx.Triggers.Add(trigger); DbCtx.SaveChanges(); }
/// <summary> /// Given the bProductId and Product removes it from database. /// </summary> /// <param name="ProductId">Id of record to locate.</param> public void Remove(int ProductId) { SetupHelpers(); Product p = LocateRecord(ProductId); if (p != null) { DbCtx.Products.DeleteObject(p); DbCtx.SaveChanges(); } }
public void create_cronTrigger() { var trigger = new CronTrigger { Sensors = _ports, CronExpression = "* * * 8" }; DbCtx.Triggers.Add(trigger); DbCtx.SaveChanges(); }