protected virtual R OnFunction <R>(Func <TDataContext, R> func) { using (var dataContext = _dataContextFactory.Create()) { return(func(dataContext)); } }
public IList <User> GetUsers() { using (var dataContext = _dataContextFactory.Create()) { return(dataContext.Users.Include(_ => _.Address).ToList()); } }
public void Create(Event item) { using (var ctx = _dataContextFactory.Create()) { ctx.InsertOnSubmit(item); ctx.SubmitChanges(); } }
private void SubscribeUser(int userId, string userName) { using (FreelanceContext context = dataContextFactory.Create()) { if (context.Clients.Any(x => x.Id == userId && x.IsActive == true)) { return; } Client newClient = new Client { Id = userId, Name = userName, IsActive = true }; bool userExists = context.Clients.Any(x => x.Id == userId); if (userExists) { context.Clients.Update(newClient); } else { context.Clients.Add(newClient); } context.SaveChanges(); } }
public JsonResult Types(string query, DateTime start, DateTime end) { var finder = new LogFinder(contextFactory.Create()); var types = finder.GetTypes(query, start, end); var rows = types.Select(x => new { c = new object[] { new { v = x.Type }, new { v = x.Total }, new { v = x.FirstHit, f = x.FirstHit.ToString() }, new { v = x.LastHit, f = x.LastHit.ToString() } } }); return(Json(new { cols = new[] { new { id = "Type", label = "Type", type = "string" }, new { id = "Total", label = "Total", type = "number" }, new { id = "FirstHit", label = "FirstHit", type = "date" }, new { id = "LastHit", label = "LastHit", type = "date" } }, rows = rows })); }
public IEnumerable <PickedStockData> Analyze2(DateTime start, DateTime end) { using (var context = _dataContextFactory.Create()) { var picked = context.StockCompany .Select(x => new { x.StockCompanyId, x.StockCode, x.MarketCode, x.CompanyName, DailyPrices = x.DailyPrices.Where(d => start <= d.DealDate && d.DealDate <= end) }) .Where(x => x.DailyPrices.OrderByDescending(d => d.DealDate).FirstOrDefault().ClosingPrice *_magnification <= x.DailyPrices.Max(m => m.ClosingPrice) && //.Where(x => x.DailyPrices.Min(m => m.ClosingPrice) * magnification <= x.DailyPrices.Max(m => m.ClosingPrice) && _minTurnover <= x.DailyPrices.Average(a => a.Turnover) && (x.MarketCode == MarketCode.TSE_Mothers || x.MarketCode == MarketCode.JQ_Standard)) .ToList() .Select(x => new PickedStockData { StockCompanyId = x.StockCompanyId, StockCode = x.StockCode, MarketCode = x.MarketCode, CompanyName = x.CompanyName, CurrentPrice = x.DailyPrices.OrderByDescending(p => p.DealDate).First().ClosingPrice, MaxPrice = x.DailyPrices.Max(m => m.ClosingPrice), MinPrice = x.DailyPrices.Min(m => m.ClosingPrice) }) .Where(x => _limitLowPrice <= x.CurrentPrice) .Where(x => x.CurrentPrice <= x.MaxPrice / _magnification) .ToList(); return(picked); } }
public T Add(int id, T data) { using (var dataContext = dataContextFactory.Create()) { return(dataContext.Add(id, data)); } }
public ActionResult Create(VendorCredentialModel inputModel) { if (!ModelState.IsValid) { var resultModel = VendorCredentialModel.ForCreate(dataContextFactory, inputModel.VendorId); resultModel.CredentialName = inputModel.CredentialName; resultModel.CredentialValue = inputModel.CredentialValue; return(View("CreateEdit", resultModel)); } using (var dataContext = dataContextFactory.Create()) { var vendor = dataContext.Vendors.Single(v => v.ObjectId == inputModel.VendorId); // ensuring the vendor is authorized dataContext.VendorCredentials.Add(new VendorCredential() { Vendor = vendor, CredentialName = inputModel.CredentialName, CredentialValue = SymmetricEncryption.EncryptForDatabase(Encoding.UTF8.GetBytes(inputModel.CredentialValue)) }); dataContext.SaveChanges(); } Flash.Success("VendorCredential was successfully saved."); return(RedirectToAction("Details", "Vendor", new { key = inputModel.VendorId })); }
public void EnsureDatabase() { using (FreelanceContext context = dataContextFactory.Create()) { context.Database.EnsureCreated(); } }
public async Task <List <SensorDTO> > GetSensorsAsync() { await using var context = _dataContextFactory.Create(); var query = context .Set <Sensor>().AsNoTracking().Where(f => !f.IsDeleted); var sensors = await query.ToListAsync(); return(_mapper.Map <List <Sensor>, List <SensorDTO> >(sensors)); }
protected virtual string OnAction(Action <TDataContext> action) { ResultArg = string.Empty; using (var dataContext = _dataContextFactory.Create()) { action(dataContext); } return(ResultArg); }
public TestData GetTestDataById(int id) { TestData testData; using (var dataContext = dataContextFactory.Create()) { testData = dataContext.TestDataGet(id); } return(testData); }
public object[] GetAnswerOptionsByQuestionId(int questionid) { using (var ctx = _dataContextFactory.Create()) { return(ctx.GetTable <AnswerOption>().Where(x => x.QuestionId == questionid). Select(x => new { Id = x.Id, Description = x.Description, QuestionId = x.QuestionId }).ToArray()); } }
public EDados[] getDados() { using (var context = _context.Create()) { return((from af in context.ateliware_favorite select new EDados { key = af.ateliware_favorite_id, id = af.id, name = af.nome, language = af.language, updatedBy = af.update_date }).ToArray()); } }
protected override IEnumerable <BusinessRuleValidationResult> ExecuteValidation(Feature entity, DbEntityEntry entityEntry) { using (var fullContext = dataContextFactory.Create()) { var duplicateFeatureCode = (from x in fullContext.Features where x.FeatureCode == entity.FeatureCode && x.VendorId == entity.VendorId && x.FeatureId != entity.FeatureId select x) .Include(x => x.SkuFeatures.Select(f => f.Sku)).FirstOrDefault(); if (duplicateFeatureCode != null) { if (duplicateFeatureCode.SkuFeatures.Any()) { yield return (new BusinessRuleValidationResult( string.Format("Feature Code already used for feature '{0}' on SKU '{1}'.", duplicateFeatureCode.FeatureName, duplicateFeatureCode.SkuFeatures.First().Sku.SkuCode), this, "FeatureCode") ); } else { yield return (new BusinessRuleValidationResult( string.Format("Feature Code already used for feature '{0}'.", duplicateFeatureCode.FeatureName), this, "FeatureCode")); } } } yield return(BusinessRuleValidationResult.Success); }
public async Task Handle(SensorActivationStateChangedNotification notification, CancellationToken cancellationToken) { await using var context = _dataContextFactory.Create(); var sensor = await context.Sensors.AsNoTracking() .FirstOrDefaultAsync(f => f.Id == notification.SensorId, cancellationToken); if (sensor == null) { throw new SensorNotFoundException(notification.SensorId); } if (sensor is StaticSensor staticSensor) { if (staticSensor.IsAvailable()) { staticSensor.Readings = await context.StaticSensorReadings .Where(z => z.StaticSensorId == staticSensor.Id) .OrderByDescending(z => z.Created) .Take(10) .ToListAsync(cancellationToken); } await _sensorCacheHelper.UpdateStaticSensorCacheAsync(staticSensor); } }
/// <summary> /// インポート済みか /// </summary> /// <param name="date"></param> /// <returns></returns> private bool IsImported(DateTime date) { using (var context = _dataContextFactory.Create()) { return(context.DailyPrice.Any(x => x.DealDate == date)); } }
public void Start() { var context = _contextFactory.Create(); while (true) { var logItem = new LogItem() { TimeStamp = DateTime.UtcNow, ThreadId = Thread.CurrentThread.ManagedThreadId, Ip = LocalIpAddress(), ApplicationName = AppDomain.CurrentDomain.FriendlyName, Message = "machine status", Type = "pretty.agent", Object = new { CpuUsage = GetCpuUsage(), AvaliableMemory = GetMemory(), NetworkUsage = GetNetwork() } }; if (HttpContext.Current != null) { logItem.Host = HttpContext.Current.Request.Url.Authority; logItem.Url = HttpContext.Current.Request.Url.ToString(); } Console.WriteLine(logItem.ToJson()); new LogInserter(context).Insert("logs", logItem); Thread.Sleep(5000); } }
public async Task Handle(StaticSensorVisibilityStateChangedNotification notification, CancellationToken cancellationToken) { await using var context = _dataContextFactory.Create(); var sensorQuery = await context.StaticSensors.AsNoTracking() .Where(z => z.Id == notification.SensorId) .Select(x => new { sensor = x, readings = x.Readings .OrderByDescending(z => z.Created) .Take(10) .ToList() }) .FirstOrDefaultAsync(cancellationToken); if (sensorQuery == null) { throw new SensorNotFoundException(notification.SensorId); } sensorQuery.sensor.Readings = sensorQuery.readings; await _sensorCacheHelper.UpdateStaticSensorCacheAsync(sensorQuery.sensor); }
public void Store(InputDocumentWithExtractedWords inputDocumentWithExtractedWords) { using (var context = dataContextIsolationFactory.Create()) { var inputDocument = inputDocumentWithExtractedWords.InputDocument; var document = new Document { Content = inputDocument.DocumentContent, Name = inputDocument.DocumentName }; context.Documents.Add(document); context.IndexEntries .AddRange( inputDocumentWithExtractedWords .ExtractedWords .Select(word => new IndexEntry { Document = document, Word = word })); context.SaveChanges(); } }
void SetupDatabase(IDataContextFactory <HealthDataContext> dataContext) { using (var db = dataContext.Create()) { db.DropTable <User>(); db.CreateTableIfNotExists <User>(); /*db.CreateTableIfNotExists<FitbitDevice>(); * db.CreateTableIfNotExists<Heartbeat>();*/ db.InsertOrReplace(new User { Id = 0, Name = "Empty", Surname = "Empty", Email = "empty", Password = "******", Admin = false, Doctor = false, RememberMe = false, Timestamp = DateTime.Now }); db.InsertOrReplace(new User { Id = 1, Name = "Alessandro", Surname = "Vaprio", Email = "*****@*****.**", Password = "******", Admin = true, Doctor = true, RememberMe = false, Timestamp = DateTime.Now }); /*db.InsertOrReplace(new FitbitDevice { Id = "D1", AccountId = "A1" }); * db.InsertOrReplace(new FitbitDevice { Id = "D2", AccountId = "A2" }); * * db.Insert(new Heartbeat { DeviceId = "D1", Timestamp = DateTime.Now, Value = 60 }); * db.Insert(new Heartbeat { DeviceId = "D1", Timestamp = DateTime.Now, Value = 80 }); * db.Insert(new Heartbeat { DeviceId = "D1", Timestamp = DateTime.Now, Value = 65 }); * db.Insert(new Heartbeat { DeviceId = "D2", Timestamp = DateTime.Now, Value = 60 }); * db.Insert(new Heartbeat { DeviceId = "D2", Timestamp = DateTime.Now, Value = 70 }); * * db.InsertOrReplace(new Category { Id = 1, Name = "Band" }); * db.InsertOrReplace(new Category { Id = 2, Name = "Smartwatch" });*/ } }
protected override IEnumerable <BusinessRuleValidationResult> ExecuteValidation(DomainLicense entity, DbEntityEntry entityEntry) { using (var context = dataContextFactory.Create()) { var sku = context.Licenses .Include(x => x.Sku) .Where(x => x.ObjectId == entity.LicenseId) .Select(x => x.Sku) .FirstOrDefault(); if (sku == null) { yield return(new BusinessRuleValidationResult("Sku could not be resolved for license.", this, null)); } if (sku.MaxDomains.HasValue && !context.DomainLicenses.Any(x => x.DomainLicenseId == entity.DomainLicenseId)) { int usedDomainsCount = context.DomainLicenses.Count(x => x.LicenseId == entity.LicenseId); int maxDomains = sku.MaxDomains.Value; if (usedDomainsCount < maxDomains) { yield return(BusinessRuleValidationResult.Success); } else { yield return(new BusinessRuleValidationResult("Domain cannot be added. This license reached maximum domains count violation.", this, null)); } } else { yield return(BusinessRuleValidationResult.Success); } } }
private IEnumerable <Client> GetClients() { using (FreelanceContext context = dataContextFactory.Create()) { return(context.Clients.ToArray()); } }
public IDictionary <int, UserNotificationContainer> GetUsersForNotification(DateTime fromDate, DateTime toDate) { IDictionary <int, UserNotificationContainer> result = new Dictionary <int, UserNotificationContainer>(); using (var dataContext = dataContextFactory.Create()) { var usersForNotification = dataContext.p_GetUsersForNotification(fromDate, toDate); foreach (var user in usersForNotification) { UserNotificationContainer container; if (!result.ContainsKey(user.ID)) { container = new UserNotificationContainer() { SendDailyNotification = user.SendDailyNotification, SendWeeklyNotification = user.SendWeeklyNotification, UserID = user.ID, Name = user.Name, Email = user.Email, Days = new List <DateTime>() }; result.Add(user.ID, container); } else { container = result[user.ID]; } container.Days.Add(user.Date); } } return(result); }
//TODO: check this code public async Task Handle(EmulationStartedNotification notification, CancellationToken cancellationToken) { _sensorCacheHelper.ClearCache(); await _applicationDatabaseInitializer.InitializeDbAsync(); await using var context = _dataContextFactory.Create(); context.Sensors.RemoveRange(context.Sensors); await context.SaveChangesAsync(cancellationToken); foreach (var device in notification.Emulator.Devices) { if (device.SensorType == typeof(StaticSensor)) { context.Add(new StaticSensor { ApiKey = device.ApiKey, Latitude = device.Latitude, Longitude = device.Longitude }); } if (device.SensorType == typeof(PortableSensor)) { context.Add(new PortableSensor { ApiKey = device.ApiKey }); } } await context.SaveChangesAsync(cancellationToken); }
public string GetAesKeyByUserId(string userId) { using (var dataContext = dataContextFactory.Create()) { return(dataContext.GetAesKeyForUser(userId)); } }
public object[] GetAllQuestionTypes() { using (var ctx = _dataContextFactory.Create()) { ctx.SetDeferredLoadingEnabled(false); return(ctx.GetTable <QuestionType>().ToArray()); } }
public ProjectService(IDataContextFactory dataContextFactory, IEmployeeService employeeService, ICommonMapper commonMapper) { _context = dataContextFactory.Create(ConnectionType.Ip); _employeeService = employeeService; _commonMapper = commonMapper; _utilityCommonDbContext = _commonMapper.GetCommonDataBAseContext(); }
public async Task <bool> Handle(DeleteSensorCommand request, CancellationToken cancellationToken) { await using var context = _dataContextFactory.Create(); var sensor = await context.Sensors.FirstOrDefaultAsync(f => f.Id == request.Id, cancellationToken); if (sensor == null) { throw new SensorNotFoundException(request.Id); } if (sensor.IsActive) { throw new SensorUnableApplyActionException(SensorUnableApplyActionException.Actions.Delete, "Sensor is active"); } if (!request.IsCompletely) { sensor.IsDeleted = true; } else { context.Sensors.Remove(sensor); } await context.SaveChangesAsync(cancellationToken); await _mediator.Publish(new SensorDeletedNotification(sensor), cancellationToken); return(true); }
public List <User> GetAllusers(IDataContextFactory <HealthDataContext> dbfactory) { List <User> users = new List <User>(); using (var context = dbfactory.Create()) { users = context.Users.ToList(); } return(users); }
//private readonly IDataContext _identityContext; public EmployeeService(IDataContextFactory dataContextFactory) { this.context = dataContextFactory.Create(ConnectionType.Ip); //this._identityContext = dataContextFactory.Create(ConnectionType.User); }
/// <summary> /// Convert transaction item to a transaction request /// </summary> /// <returns>TransactionRequest</returns> public TransactionRequest ToTransactionRequest(IDataContextFactory dataContextFactory) { using (var context = dataContextFactory.Create()) { var skus = new List<string>(); foreach (var item in Items) { if (!context.Vendors.Any(x => x.ObjectId == VendorId)) throw new ArgumentException(String.Format("Vendor with GUID '{0}' not found!", VendorId)); var sku = (from x in context.SKUs where x.VendorId == VendorId && (x.SkuCode == item.SkuString || x.SkuAternativeCode == item.SkuString) select x).FirstOrDefault(); if (sku != null) skus.Add(sku.SkuId.ToString()); else skus.Add(string.Format("{0} - {1}", item.ItemName, item.SkuString)); } return new TransactionRequest() { PurchasedSkus = skus.ToArray(), PurchaserName = (Billing != null) ? Billing.Name : "", PurchaserEmail = PayerEmail, }; } }
public ProjectService(IDataContextFactory dataContextFactory) { _context = dataContextFactory.Create(ConnectionType.Ip); }
public ManagerService(IDataContextFactory dataContextFactory) { this.context = dataContextFactory.Create(ConnectionType.Ip); }
public EmployeeService(IDataContextFactory dataContextFactory) { this.context = dataContextFactory.Create(ConnectionType.Ip); }