public void Language_Void_ContextLanguageName() { // arrange. var context = new DefaultContext(); // act. string language = context.Language; // assert. Assert.AreEqual("en", language); }
protected override object Evaluate(CommonRequest request) { using (var ctx = new DefaultContext()) { //var now = DateTime.Parse(request.context.Request.Params["date"] ?? Now.ToString("yyyy-MM-dd")); //var dates = Range(1, 7).Select(p => now.AddDays(-1 * p)).ToList(); //var list = dates.Select(p => ctx.Population.Count(m => m.CreateOn==p)).ToList(); List <string> ranges = new List <string>(); ranges.Add("1~20"); ranges.Add("21~40"); ranges.Add("41~60"); ranges.Add("61~80"); ranges.Add("81~100"); ranges.Add("101~150"); ranges.Add("151~200"); var num = new List <int>(); for (int i = 0; i < ranges.Count(); i++) { if (ranges[i].Contains("~")) { var arr = ranges[i].Split('~'); int[] ar = new int[2]; for (int j = 0; j < arr.Length; j++) { ar[j] = Convert.ToInt32(arr[j]); } int min = ar[0]; int max = ar[1]; int n = ctx.Population.Where(p => p.PAge >= min && p.PAge <= max && p.PAge != null).Count(); num.Add(n); } } for (int i = 0; i < ranges.Count; i++) { ranges[i] += "岁"; } return(new { //sum = list.Sum(), //xaxis = dates.Select(p => p.ToString("yyyy-MM-dd")).ToList(), //series = list sum = num.Sum(), xaxis = ranges.ToList(), series = num }); } }
public void ImportRecruitQuestions(DefaultContext _context, List <RecruitQuestion> models) { var connectionString = _context.Database.GetDbConnection().ConnectionString; var newRecruitQuestions = new List <RecruitQuestion>(); foreach (var recruitQuestionModel in models) { var existingEntity = _context.RecruitQuestions.FirstOrDefault(x => x.RecruitId == recruitQuestionModel.RecruitId && x.QuestionId == recruitQuestionModel.QuestionId); if (existingEntity == null) { newRecruitQuestions.Add(recruitQuestionModel); } } _context.RecruitQuestions.AddRange(newRecruitQuestions); _context.SaveChanges(); }
public IEnumerable GetList() { using (DefaultContext db = new DefaultContext()) { var query = from Commercial in db.Set <Commercial>() select new { CommercialId = Commercial.ID_COMMERCIAL, CommercialNom = Commercial.NOM_COMMERCIAL, CommercialPrenom = Commercial.PRENOM_COMMERCIAL, CommercialEmail = Commercial.EMAIL_COMMERCIAL, CommercialMDP = Commercial.MDP_COMMERCIAL }; return(query.ToList()); } }
//[TestMethod] public void TestIndex() { DbContextOptionsBuilder optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseSqlServer("Data Source=localhost;Initial Catalog=AFPA_2020;Integrated Security=True;"); DefaultContext dbContext = new DefaultContext(optionsBuilder.Options); EtablissementController controller = new EtablissementController(dbContext); var result = controller.Index(); Assert.IsInstanceOfType(result, typeof(ViewResult)); ViewResult viewResult = result as ViewResult; Assert.IsInstanceOfType(viewResult.Model, typeof(IEnumerable <Etablissement>)); Assert.IsNotNull(viewResult.Model); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { DefaultContext context = (DefaultContext)validationContext.GetService(typeof(DefaultContext)); var userName = (string)value; if (userName == null) { return(ValidationResult.Success); } var anyMatch = context.Users.Any(u => u.UserName.ToLower().Equals(userName.ToLower())); if (anyMatch) { return(new ValidationResult($"The username ${userName} already exists. Please choose a different one.")); } return(ValidationResult.Success); }
protected override object Evaluate(CommonRequest request) { var user = CurrentUserInformation; var requser = JsonConvert.DeserializeObject <UserInformation>(request.data); if (user == null) { return(new CommonOutputT <string> { success = false, message = "请先登录" }); } if (requser == null) { return(new CommonOutputT <string> { success = false, message = "请求参数错误" }); } if (user.UILoginName != requser.UILoginName) { return(new CommonOutputT <string> { success = false, message = "只能更改自己的密码" }); } using (var ctx = new DefaultContext()) { requser.TransactionID = Guid.NewGuid().ToString(); requser.VersionNo++; requser.UpdateOn = DateTime.Now; requser.UpdateBy = user.UILoginName; ctx.UserInformation.AddOrUpdate(requser); ctx.SaveChanges(); } return(new CommonOutputT <string> { success = true, message = "操作成功" }); }
public static void Seed(DefaultContext context, AppSettings settings) { var anyModulesExist = context.Modules.FirstOrDefault() != null; if (!anyModulesExist) { context.Modules.Add(new Module { Description = "Test Pilot", Name = "Sexton's Test Pilot", Published = false, SpecialCode = settings.ModuleSpecialCode, Labs = new List <Lab> { new Lab { Name = "Test Pilot Lab", EstimatedCpusUsed = 1, EstimatedMemoryUsedMb = 4096, Type = ELabType.Permanent, LabDifficulty = 1, LabVms = new List <LabVm> { new LabVm { Name = "Test Pilot VM", VmTemplate = new VmTemplate { HypervisorVmTemplates = new List <HypervisorVmTemplate> { new HypervisorVmTemplate { HypervisorNodeId = 1, TemplateVmId = 109 } } } } } } } }); context.SaveChanges(); } }
protected override object Evaluate(CommonRequest request) { var searchModel = request.data.Deserialize <FactoryBuildingSearchModel>(); var industrialParkName = searchModel?.FBNameOfIndustrialPark; using (var ctx = new DefaultContext()) { IQueryable <FactoryBuilding> queryable = ctx.FactoryBuilding.Where(building => building.IsDeleted == 0); if (!string.IsNullOrEmpty(industrialParkName)) { queryable = queryable.Where(t => t.FBNameOfIndustrialPark == industrialParkName); } return (queryable .Join(ctx.Poi.Where(t => t.Longitude.Length > 0 && t.Latitude.Length > 0), building => building.FBNameOfIndustrialPark, poi => poi.PAddress, (building, poi) => poi).OrderBy(poi => poi.ord).ToList()); } }
public GenericErrorResponse Validate(DefaultContext dbContext) { if (!string.IsNullOrEmpty(Email) && dbContext.Users.Count(u => u.Email == Email) != 0) { return(new GenericErrorResponse { Message = "The specified personal email is already in use" }); } if (Password != ConfirmPassword) { return(new GenericErrorResponse { Message = "Passwords do not match" }); } return(null); }
public Factory() { DbContext = new DefaultContext(); AccountsService = new AccountsService(DbContext); ClientsService = new ClientsService(DbContext); OpeningsService = new OpeningsService(DbContext); DocumentsService = new DocumentsService(DbContext); ReportsService = new ReportsService(DbContext); DataInitializatorService = new DataInitializatorService(DbContext); ProfitLossService = new ProfitLossService(this); BalanceService = new BalanceService(this); AccountsPrintService = new AccountsPrintService(this); OpeningsPrintService = new OpeningsPrintService(this); DocumentsPrintService = new DocumentsPrintService(this); ReportsPrintService = new ReportsPrintService(this); ProfitLossPrintService = new ProfitAndLossPrintService(this); BalancePrintService = new BalancePrintService(this); }
/// <summary> /// Remove user from db and locally /// </summary> public async Task RemoveUser(int id) { using (var context = new DefaultContext()) { var userToRemove = await context.Users.Where(q => q.Id == id).FirstOrDefaultAsync(); if (userToRemove != null) { //Remove from db context.Users.Remove(userToRemove); await context.SaveChangesAsync(); //Remove from local list var local = Users.Where(q => q.Id == id).FirstOrDefault(); Users.Remove(local); } } }
public override void ExecuteCmdlet() { CloudStorageAccount account; if (Context != null) { account = Context.StorageAccount; } else { account = StorageUtilities.GenerateCloudStorageAccount(new ARMStorageProvider(StorageClient), ResourceGroupName, Name); } // Clear the current storage account for both SM and RM GeneralUtilities.ClearCurrentStorageAccount(true); DefaultContext.SetCurrentStorageAccount(account.ToString(true)); WriteObject(account.Credentials.AccountName); }
// Возвращаемый тип можно изменить на IEnumerable, однако для обеспечения поддержки // постраничного просмотра и сортировки необходимо добавить следующие параметры: // int maximumRows // int startRowIndex // out int totalRowCount // string sortByExpression public IQueryable <WebFormsTest.Models.Payment> GetPayments([Control] DateTime?PayDateField, [Control] string customerName = "") { DefaultContext db = new DefaultContext(); var query = db.Payments.Include(x => x.Customer); if (PayDateField.HasValue) { var payDateField = PayDateField.GetValueOrDefault(); query = query.Where(x => x.PaymentDate.Day == payDateField.Day && x.PaymentDate.Month == payDateField.Month && x.PaymentDate.Year == payDateField.Year); } if (!string.IsNullOrWhiteSpace(customerName)) { query = query.Where(x => x.Customer.CustomerName.Contains(customerName)); } return(query); }
protected override void ProcessRecord() { CloudStorageAccount account; if (Context != null) { account = Context.StorageAccount; } else { account = StorageUtilities.GenerateCloudStorageAccount(StorageClient, ResourceGroupName, StorageAccountName); } // Clear the current storage account for both SM and RM GeneralUtilities.ClearCurrentStorageAccount(true); DefaultContext.SetCurrentStorageAccount(account.ToString(true)); WriteObject(account.Credentials.AccountName); }
/** * * <summary> * * </summary> * */ protected void SaveButton_Click(object sender, EventArgs e) { //Use Entity Framework to connect to the server using (DefaultContext db = new DefaultContext()) { //Use the Game model to create a new game object //and save a new record GameInfo newGame = new GameInfo(); //int GameID = 0; //if(Request.QueryString.Count > 0) //our URL has an ID in it //{ //Get the ID from the URL //GameID = Convert.ToInt32(Request.QueryString["GameID"]); //Get the current game from the Entity Framework Database //newGame = (from GameInfo in db.GameInfoes //where GameInfo.GameID == GameID //select GameInfo).FirstOrDefault(); //} //Add data to the new game record //newGame.GameID = Convert.ToInt32(GameIDTextBox.Text); newGame.GameTitle = GameTitleTextBox.Text; newGame.GameType = GameTypeTextBox.Text; newGame.GameDate = Convert.ToDateTime(GameDateTextBox.Text); newGame.GameTurns = Convert.ToInt32(GameTurnsTextBox.Text); newGame.GameServer = GameServerTextBox.Text; newGame.GameSpectators = Convert.ToInt32(GameSpectatorsTextBox.Text); //Use LINQ/ADO.NET to insert new game into the database //if(GameID == 0) //{ // db.GameInfoes.Add(newGame); //} //Save our changes db.SaveChanges(); //Redirect back to the updated game page Response.Redirect("~/Games/Tracking.aspx"); } }
public static List <string> GetStrings(this DefaultContext context, string query) { using (var command = context.Database.GetDbConnection().CreateCommand()) { command.CommandText = query; command.CommandType = CommandType.Text; context.Database.OpenConnection(); var entities = new List <string>(); using (var result = command.ExecuteReader()) { while (result.Read()) { entities.Add(result.GetString(0)); } } return(entities); } }
protected override object Evaluate(CommonRequest request) { var pois = DeserializeObject <List <Poi> >(request?.data); var builder = new StringBuilder(); int i = 0; using (var ctx = new DefaultContext()) { foreach ( var poi in pois.Select(p => p.PAddress).SelectMany(addr => ctx.Poi.Where(p => p.PAddress == addr))) { ctx.Poi.Remove(poi); if (pois[pois.Count - 1].ord <= 0) { poi.ord = ++i; } } ctx.SaveChanges(); return(new { success = true, message = "±£´æ³É¹¦", response = pois.Where(p => !string.IsNullOrEmpty(p.Latitude) && !string.IsNullOrEmpty(p.Longitude)) .AsParallel() .Select(poi => Make(new CommonRequest { auth = request?.auth, context = request?.context, data = SerializeObject(poi), method = "savepoievaluator" }).Eval(new CommonRequest { auth = request?.auth, context = request?.context, data = SerializeObject(poi), method = "savepoievaluator" })) .ToList() }); } }
public IEnumerable GetList() { using (DefaultContext db = new DefaultContext()) { var query = from Module in db.Set <Module>() select new { ModuleId = Module.ID_MODULE, ModuleLibelle = Module.LIBELLE_MODULE, ModulePrixHT = Module.PRIX_HT_MODULE, ModuleDebutPointX = Module.DEBUT_POINT_X, ModuleFinPointX = Module.FIN_POINT_X, ModuleDebutPointY = Module.DEBUT_POINT_Y, ModuleFinPointY = Module.FIN_POINT_Y, }; return(query.ToList()); } }
public Main() { InitializeComponent(); defaultContext = new DefaultContext(); List <String> tableNames = defaultContext.GetScheme(); import = new Import(defaultContext, tables_cb, tableNames); export = new Export(defaultContext, tables_cb_e, tableNames); marker = new Watermark(defaultContext); export_bt.Enabled = true; delete_pb.Visible = false; delete_pb.Minimum = 1; delete_pb.Maximum = 11; delete_pb.Value = 1; delete_pb.Step = 1; }
public override void OnInitialize(IFlyerProperty property) { m_FlyerProprety = property; m_CfgEternityProxy = GameFacade.Instance.RetrieveProxy(ProxyName.CfgEternityProxy) as CfgEternityProxy; m_Context = new DefaultContext(); m_Context.AddObject(this, true); m_Context.AddObject(typeof(IBulletTargetProperty), property, true); m_Context.AddObject(typeof(IActionFactory), TimelineActionFactory.Factory, true); m_Context.AddObject(typeof(IBaseActionProperty), property, true); m_Context.AddObject(typeof(IMoveActionProperty), property, true); ContextAddOtherObject(); m_StateMachine = new FlyerStateMachine(m_Context); m_StateMachine.CompletedHandler += OnStateMachineComplete; m_StageType = FlyerStageType.Flying; m_StateMachine.SetInitialState(FlyerStateToken.Flying); }
protected override object Evaluate(CommonRequest request) { using (var ctx = new DefaultContext()) { var xaxis = new List <string>(); var series = new List <int>(); foreach (var line in ctx.FactoryBuilding.GroupBy(t => t.FBNameOfIndustrialPark)) { xaxis.Add(line.Key); series.Add(line.Count()); } return(new { sum = series.Sum(), xaxis = xaxis, series = series }); } }
public AccountController( IActivationMail activationMail, IPasswordResetMail passwordResetMail, IPaymentServices paymentServices, DefaultContext dbContext, AppConfiguration configuration, UserManager <Profile> userManager, SignInManager <Profile> signInManager, IHttpContextAccessor httpContextAccessor ) { this.activationMail = activationMail; this.passwordResetMail = passwordResetMail; this.paymentServices = paymentServices; this.dbContext = dbContext; this.configuration = configuration; this.userManager = userManager; this.signInManager = signInManager; this.httpContextAccessor = httpContextAccessor; }
public async Task DeleteMissingProperties(DefaultContext context) { var labVmIds = LabVms.Select(t => t.Id).ToList(); var vmsToRemove = await context.LabVms .Where(t => t.LabId == Id && !labVmIds.Contains(t.Id)).ToListAsync(); context.LabVms.RemoveRange(vmsToRemove); var interfaceIds = LabVms.SelectMany(t => t.TemplateInterfaces).Select(i => i.Id).ToList(); var interfacesToRemove = await context.VmInterfaceTemplates .Where(t => labVmIds.Contains(t.LabVmId) && !interfaceIds.Contains(t.Id)).ToListAsync(); context.VmInterfaceTemplates.RemoveRange(interfacesToRemove); var bridgeTemplateIds = BridgeTemplates.Select(t => t.Id).ToList(); var bridgeTemplatesToRemove = await context.BridgeTemplates .Where(t => t.LabId == Id && !bridgeTemplateIds.Contains(t.Id)).ToListAsync(); context.BridgeTemplates.RemoveRange(bridgeTemplatesToRemove); }
protected override object Evaluate(CommonRequest request) { var xaxis = new List <string>(); var series = new List <int>(); using (var context = new DefaultContext()) { foreach (var line in context.Population.GroupBy(p => p.PNeighborhoodVillageCommittee)) { xaxis.Add(line.Key); series.Add(line.Count()); } return(new { sum = series.Sum(), xaxis, series }); } }
/// <summary> /// Обновляет модели и сообщает об изменении /// </summary> /// <param name="UDict">Набор моделей для обновления</param> /// <returns>Набор сообщений</returns> static List <Messadge> GetUPDMessadge(Dictionary <int, SGSPointData> UDict) { var res = new List <Messadge>(); using (var context = new DefaultContext <SGSPointData>()) { foreach (var kvp in UDict) { var model = context.Values.Where(m => m.IdSGSPoint == kvp.Value.IdSGSPoint && m.DateOfValue == kvp.Value.DateOfValue).FirstOrDefault(); model.PointValue = kvp.Value.PointValue; res.Add(new Messadge { MNumber = kvp.Key, MessadgeString = "Модель существует в БД, значение обновлено." }); } context.SaveChanges(); } return(res); }
public void SyncRecruitQuestions(DefaultContext _context, List <RecruitQuestion> models) { var deletedEntities = new List <RecruitQuestion>(); foreach (var existingItem in _context.RecruitQuestions) { var newItem = models.FirstOrDefault(x => x.RecruitId == existingItem.RecruitId && x.QuestionId == existingItem.QuestionId); if (newItem == null) { deletedEntities.Add(existingItem); } } if (deletedEntities.HasItems()) { _context.RecruitQuestions.RemoveRange(deletedEntities); } _context.SaveChanges(); }
public IEnumerable GetList() { using (DefaultContext db = new DefaultContext()) { var query = from Client in db.Set <Client>() select new { ClientId = Client.ID_CLIENT, ClientNom = Client.NOM_CLIENT, ClientPrenom = Client.PRENOM_CLIENT, ClientAdresse = Client.ADRESSE_CLIENT, ClientVille = Client.VILLE_CLIENT, ClientDateCrea = Client.DATE_CREATION_CLIENT, ClientDateModif = Client.DATE_MODIFICATION_CLIENT, }; return(query.ToList()); } }
/// <summary> /// 角色Entiy 被销毁时 /// </summary> public override void OnDestroy() { base.OnDestroy(); m_ISpacecraftSkillProperty.SetChangeGuideSkillTargetAction(null); m_ISpacecraftSkillProperty.SetSkillBttonIsDown(false); SkillRPCNet skillRPC = m_Context.GetObject <SkillRPCNet>(); if (skillRPC != null) { skillRPC.Close(); } skillRPC = null; m_Context.Clear(true); m_RunningData = null; m_CfgEternityProxy = null; m_Context = null; m_StateMachine = null; m_ISpacecraftSkillProperty = null; }
static internal void Requete1() { using (DefaultContext dbContext = new DefaultContext()) { var query = dbContext.Customers.Where(e => e.CustomerId == "ANATR").Include(e => e.Orders) .ThenInclude(e => e.OrderDetails) .ThenInclude(e => e.Product); foreach (var item in query) { Console.WriteLine("Id customer :" + item.CustomerId + " Pays :" + item.Country); foreach (var commande in item.Orders) { Console.WriteLine("Numéro de la commande :" + commande.OrderId); foreach (var details in commande.OrderDetails) { Console.WriteLine("Nom du produit :" + details.Product.ProductName); } } } } }
public override void OnInitialize(ISpacecraftSkillProperty property) { m_ISpacecraftSkillProperty = property; m_CfgEternityProxy = GameFacade.Instance.RetrieveProxy(ProxyName.CfgEternityProxy) as CfgEternityProxy; m_PlayerSkillProxy = GameFacade.Instance.RetrieveProxy(ProxyName.PlayerSkillProxy) as PlayerSkillProxy; m_Context = new DefaultContext(); m_RunningData = new SkillRunningData(); m_Context.AddObject(this, true); m_Context.AddObject(typeof(IActionFactory), TimelineActionFactory.Factory, true); m_Context.AddObject(m_RunningData, true); m_Context.AddObject(typeof(IBaseActionProperty), property, true); m_Context.AddObject(typeof(IBindNodeActionProperty), property, true); ContextAddOtherObject(); m_StateMachine = new SkillStateMachine(m_Context); m_StateMachine.CompletedHandler += OnStateMachineComplete; m_StateMachine.ChangedHandler += OnStateMachineChanged; }
/// <summary> /// Creates and starts a new context. /// </summary> /// <param name="transactionScopeOption"> /// The transaction scope option. /// </param> /// <param name="transactionOptions"> /// The transaction options. /// </param> /// <returns> /// The <see cref="IContext"/>. /// </returns> public IContext StartNewContext(TransactionScopeOption transactionScopeOption, TransactionOptions transactionOptions) { if (!this.IsReady) { Log.Error(Resources.ContextFactoryNotReady); throw new BackstageException(Resources.ContextFactoryNotReady); } var context = new DefaultContext(this); context.Start(transactionScopeOption, transactionOptions); return context; }
protected BaseService() { Context = new DefaultContext("DefaultConnection"); }