public int ActionsCount() { var mc = new ModelContext(SessionManager.DataSession); var output = mc.Actions.Count(); return output; }
public IList<Setting> GetSettings() { using (var db = new ModelContext()) { return db.Settings.ToList(); } }
public IList<NHibernateEClinic.Model.Action> ListActions(int startRowIndex, int pageSize, string sortExpression) { var mc = new ModelContext(SessionManager.DataSession); var output = mc.Actions.SortBy(sortExpression).Skip(startRowIndex).Take(pageSize); return output.ToList(); }
public void ModelContextResolvesItselfCorrectly() { using (var modelContext = new ModelContext(_container)) { Assert.AreSame(modelContext, modelContext.Get<ModelContext>()); } }
public PartialViewResult AjaxDown(int id, string sType, string sParam) { ModelContext db = new ModelContext(); IDevice dev = new Device(); switch (sType) { case "Fan": dev = db.Fans.Include("Speed").FirstOrDefault(p => p.Id == id); ((Fan)dev).Speed.Down(); break; case "Louvers": dev = db.LouversSet.Include("Open").FirstOrDefault(p => p.Id == id); ((Louvers)dev).Open.Down(); break; case "Tv": dev = db.TvSet.Include("Volume").FirstOrDefault(p => p.Id == id); switch (sParam) { case "Volume": ((Tv)dev).Volume.Down(); break; case "Program": ((Tv)dev).PreviousChannel(); break; } break; } db.Entry(dev).State = EntityState.Modified; db.SaveChanges(); return PartialView("DivDevice", dev); }
public void SameScopedInstancesResolvingInsideModelContext() { using (var context = new ModelContext(_container)) { Assert.AreSame(context.Get<SampleService>(), context.Get<SampleService>()); } }
public Tv GetTvOnOff(int id) { ModelContext db = new ModelContext(); db.TvSet.Find(id).OnOff(); db.SaveChanges(); return db.TvSet.Include("Volume").FirstOrDefault(p => p.Id == id); }
public Louvers GetLouversOnOff(int id) { ModelContext db = new ModelContext(); db.LouversSet.Find(id).OnOff(); db.SaveChanges(); return db.LouversSet.Include("Open").FirstOrDefault(p => p.Id == id); }
public Fan GetFanOnOff(int id) { ModelContext db = new ModelContext(); db.Fans.Find(id).OnOff(); db.SaveChanges(); return db.Fans.Include("Speed").FirstOrDefault(p => p.Id == id); }
public void DifferentScopedInstancesResolvingForDifferentModelContexts() { using (var context1 = new ModelContext(_container)) using (var context2 = new ModelContext(_container)) { Assert.AreNotSame(context1.Get<SampleService>(), context2.Get<SampleService>()); } }
public void DeleteAction(int actionId) { var mc = new ModelContext(SessionManager.DataSession); var action = SessionManager.DataSession.Load<NHibernateEClinic.Model.Action>(actionId); SessionManager.DataSession.Delete(action); SessionManager.DataSession.Flush(); }
public Lamp GetLampOnOff(int id) { ModelContext db = new ModelContext(); db.Lamps.Find(id).OnOff(); db.SaveChanges(); return db.Lamps.Find(id); }
void IModelContextPool.Put(ModelContext context) { lock (pool) { if(!pool.Contains(context)) pool.Push(context); } }
public QueryComposer(ModelContext ctx) { if (ctx == null) { throw new ArgumentNullException("ctx"); } this.Context = ctx; }
public void MultipleModelContextxResolveItselfCorrectly() { using (var context1 = new ModelContext(_container)) using (var context2 = new ModelContext(_container)) { Assert.AreNotSame(context1, context2); Assert.AreSame(context1, context1.Get<ModelContext>()); Assert.AreSame(context2, context2.Get<ModelContext>()); } }
public void EditAction(int actionId, string actionName) { var mc = new ModelContext(SessionManager.DataSession); var action = SessionManager.DataSession.Get<NHibernateEClinic.Model.Action>(actionId); action.ActionName = actionName; SessionManager.DataSession.Update(action); SessionManager.DataSession.Flush(); }
public override void AddColumn(ModelContext ctx, string columnName, object o) { base.AddColumn(ctx, columnName, null); if(o != null) { var stm = new UpdateStatementBuilder(ctx.Info.From); stm.Values.Add(new KeyOpValue(columnName, o, KvOpertation.None)); var sql = stm.ToSqlStatement(ctx); ctx.Provider.ExecuteNonQuery(sql); } }
private static void ThrowClearExceptionMsg(bool useIndex, ModelContext ctx, IDataReader dr, Exception ex) { if (useIndex) { FindMemberCastFailByIndex(ctx, dr, ex); } else { FindMemberCastFailByName(ctx, dr, ex); } }
protected static void InnerGetValue(ModelContext ctx, string columnName, object o, bool defaultFirst) { var builder = new AlterTableStatementBuilder(ctx.Info.From, defaultFirst); var mem = ctx.Info.Members.FirstOrDefault(p => p.Name == columnName); builder.AddColumn = new ColumnInfo(mem); if(o != null) { builder.DefaultValue = o; } var sql = builder.ToSqlStatement(ctx); ctx.Provider.ExecuteNonQuery(sql); }
public virtual void DropColumns(ModelContext ctx, params string[] columns) { foreach(var column in columns) { var sb = new StringBuilder("ALTER TABLE "); sb.Append(QuoteForTableName(ctx.Info.From.MainTableName)); sb.Append(" DROP COLUMN "); sb.Append(QuoteForColumnName(column)); sb.Append(";"); var sql = new SqlStatement(sb.ToString()); ctx.Provider.ExecuteNonQuery(sql); } }
private static void FindMemberCastFailByIndex(ModelContext ctx, IDataReader dr, Exception ex) { var text = new StringBuilder(); var ms = ctx.Info.SimpleMembers; for (int i = 0; i < ms.Length; i++) { CheckMemberCast(ms[i], dr[i], text); } if(text.Length > 0) { throw new DataException(text.ToString(), ex); } }
public override void Test_Retrieve_Entity_With_EntityID_Equals_To_X_Should_Return_One_Item() { using (var context = new ModelContext(Session)) { int actionID = 1; var result = (from action in context.Actions where action.ActionID == actionID select action).SingleOrDefault(); Assert.NotNull(result); Assert.Equal(result.ActionID, actionID); Console.WriteLine(result.ActionID + " " + result.ActionName); } }
private static void FindMemberCastFailByName(ModelContext ctx, IDataReader dr, Exception ex) { var text = new StringBuilder(); var ms = ctx.Info.SimpleMembers; foreach (var member in ms) { CheckMemberCast(member, dr[member.Name], text); } if (text.Length > 0) { throw new DataException(text.ToString(), ex); } }
/// <summary> /// The basic consumer receives messages pushed from the broker. /// </summary> /// <param name="model">The model context for the consumer</param> /// <param name="inputAddress">The input address for messages received by the consumer</param> /// <param name="receivePipe">The receive pipe to dispatch messages</param> /// <param name="receiveObserver">The observer for receive events</param> /// <param name="taskSupervisor">The token used to cancel/stop the consumer at shutdown</param> public RabbitMqBasicConsumer(ModelContext model, Uri inputAddress, IPipe<ReceiveContext> receivePipe, IReceiveObserver receiveObserver, ITaskSupervisor taskSupervisor) { _model = model; _inputAddress = inputAddress; _receivePipe = receivePipe; _receiveObserver = receiveObserver; _receiveSettings = model.GetPayload<ReceiveSettings>(); _pending = new ConcurrentDictionary<ulong, RabbitMqReceiveContext>(); _participant = taskSupervisor.CreateParticipant(); }
public void Save(IEnumerable<Setting> settings) { using (var db = new ModelContext()) { foreach (var setting in settings) { var dbSetting = db.Settings.FirstOrDefault(m => m.Name.Equals(setting.Name)); if (dbSetting == null) db.Settings.Add(setting); else db.Entry<Setting>(dbSetting).CurrentValues.SetValues(setting); } db.SaveChanges(); } }
/// <summary> /// The basic consumer receives messages pushed from the broker. /// </summary> /// <param name="model">The model context for the consumer</param> /// <param name="inputAddress">The input address for messages received by the consumer</param> /// <param name="receivePipe">The receive pipe to dispatch messages</param> /// <param name="receiveObserver">The observer for receive events</param> /// <param name="taskSupervisor">The token used to cancel/stop the consumer at shutdown</param> public RabbitMqBasicConsumer(ModelContext model, Uri inputAddress, IPipe<ReceiveContext> receivePipe, IReceiveObserver receiveObserver, ITaskScope taskSupervisor) { _model = model; _inputAddress = inputAddress; _receivePipe = receivePipe; _receiveObserver = receiveObserver; _receiveSettings = model.GetPayload<ReceiveSettings>(); _pending = new ConcurrentDictionary<ulong, RabbitMqReceiveContext>(); _participant = taskSupervisor.CreateParticipant($"{TypeMetadataCache<RabbitMqBasicConsumer>.ShortName} - {inputAddress}", Stop); _deliveryComplete = new TaskCompletionSource<bool>(); }
public static void init( bool persist ) { int count = 0; using ( ModelContext context = new ModelContext() ) { try { initWebUser( context ); initGuests( context ); initAdmins( context ); if ( persist ) { count = context.SaveChanges(); Log.Debug( $"INIT DataSet persisted COUNT: {count}\nDONE" ); } } catch ( Exception e ) { Log.Error( "init: ", e ); } } }
public RabbitMqBasicConsumer(ModelContext model, Uri inputAddress, IPipe<ReceiveContext> receivePipe, IReceiveObserver receiveObserver, CancellationToken cancellationToken) { _model = model; _inputAddress = inputAddress; _receivePipe = receivePipe; _receiveObserver = receiveObserver; _receiveSettings = model.GetPayload<ReceiveSettings>(); _pending = new ConcurrentDictionary<ulong, RabbitMqReceiveContext>(); _consumerComplete = new TaskCompletionSource<RabbitMqConsumerMetrics>(); _registration = cancellationToken.Register(Complete); }
public void Serialise_WithModelContext_ReturnsExpectedXml() { // Arrange string expectedXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ModelContext Id=\"fe715b9e-facc-4353-bcb1-bec1b313423a\" xmlns=\"http://api.esendex.com/ns/\"><Value>5</Value></ModelContext>"; ModelContext model = new ModelContext() { Id = new Guid("FE715B9E-FACC-4353-BCB1-BEC1B313423A"), Value = 5 }; // Act string actualXml = serialiser.Serialise<ModelContext>(model); // Assert Assert.AreEqual(expectedXml, actualXml); }
protected static void LoadValues(object obj, ModelContext ctx, IDataReader dr, bool useIndex, bool noLazy) { try { ctx.Handler.LoadSimpleValues(obj, useIndex, dr); ctx.Handler.LoadRelationValues(obj, useIndex, noLazy, dr); } catch (FormatException ex) { ThrowClearExceptionMsg (useIndex, ctx, dr, ex); throw; } catch (InvalidCastException ex) { ThrowClearExceptionMsg (useIndex, ctx, dr, ex); throw; } }
public SmsPanelPersistenceRepository(ModelContext _db) : base(_db) { db = _db; }
protected override void UpdateItem(DocumentTypeInfo item) { ModelContext.Update <DocumentTypeInfo> (item); ModelContext.SaveChanges(); }
protected override void UpdateItem(ScienceInfo item) { ModelContext.Update(item); ModelContext.SaveChanges(true); }
protected IEduProgram GetEduProgram(int eduProgramId) { return(ModelContext.Get <EduProgramInfo, int> (eduProgramId)); }
private void save() { ModelContext.init().SaveChanges(); MessageBox.Show("Успешно!"); refreshGrid(""); }
public PropertyTypesController(ModelContext context) { _context = context; }
public static async Task InsertDefaultDataAsync() { var dbContext = new ModelContext(); #region Users var allusers = dbContext.Users.ToList(); var access = new AccessLevel(); if (allusers == null || allusers.Count <= 0) { var user = new Users() { Guid = Guid.Parse("34593FF9-606D-4CFA-8B3C-1A2919BF11FF"), Name = "کاربر پیش فرض", UserName = "******", IsBlock = false, Email = "*****@*****.**", Mobile = "09382420272", Type = EnUserType.Manager, Status = true, Modified = DateTime.Now }; var ue = new UTF8Encoding(); var bytes = ue.GetBytes("2211"); var md5 = new MD5CryptoServiceProvider(); var hashBytes = md5.ComputeHash(bytes); user.Password = System.Text.RegularExpressions.Regex.Replace(BitConverter.ToString(hashBytes), "-", "") .ToLower(); dbContext.Users.Add(user); } #endregion #region Products var allKol = dbContext.Products.ToList(); if (allKol == null || allKol.Count <= 0) { var kol = DefaultProducts.SetDef(); foreach (var prd in kol) { dbContext.Products.Add(prd); } } #endregion #region Customer var allCus = dbContext.Customers.ToList(); if (allCus == null || allCus.Count <= 0) { var prd = new Customers() { Guid = Guid.NewGuid(), HardSerial = "265155255", Modified = DateTime.Now, Address = "مشهد- محمدیه 5/5- پلاک9", Name = "مجید خاکپور", Status = true, UserGuid = Guid.Parse("34593FF9-606D-4CFA-8B3C-1A2919BF11FF"), CreateDate = DateTime.Now, UserName = "", Description = "", Account = 0, AppSerial = "7225368797445068625332", CompanyName = "املاک آراد", Email = "*****@*****.**", ExpireDate = new DateTime(2022, 05, 05, 20, 26, 17), LkSerial = "", NationalCode = "0860439021", Password = "", PostalCode = "", SiteUrl = "", Tell1 = "09382420272", Tell2 = "09011804993", Tell3 = "09154751439", Tell4 = "", isBlock = false, isWebServiceBlock = false }; var prd_ = new Androids() { Guid = Guid.NewGuid(), Modified = DateTime.Now, Status = true, Name = "Emulator A50", CustomerGuid = prd.Guid, IMEI = "7e8a55a609e7ec3f" }; dbContext.Customers.Add(prd); dbContext.Androids.Add(prd_); } #endregion #region Users var allPanels = dbContext.SmsPanels.ToList(); if (allPanels == null || allPanels.Count <= 0) { var prd = new SmsPanels() { Guid = Guid.NewGuid(), Modified = DateTime.Now, Status = true, Name = "SmsSender", IsCurrent = true, API = "38782F7144637944703643765069305A514C796B5A413D3D", Sender = "10000100007766" }; dbContext.SmsPanels.Add(prd); } #endregion await dbContext.SaveChangesAsync(); dbContext.Dispose(); }
public OrderMenuItemsController(ModelContext context) { _context = context; }
public SyroeshkaRuService(UserManager <Users> userManager) { _db = new ModelContext(); _mapper = new Configure().Configuration().CreateMapper(); _userManager = userManager; }
public DatabaseController(ModelContext context, ILogger <DatabaseController> logger) { this.context = context; this.logger = logger; }
protected override void DeleteItem(DocumentTypeInfo item) { ModelContext.Remove <DocumentTypeInfo> (item); ModelContext.SaveChanges(); }
public SizeRepository(ModelContext model) { db = model; }
public Repository(ModelContext context) { Context = context; DbSet = context.Set <TEntity>(); }
public JudgeDatabase(ModelContext _db) { this.db = _db; }
public AboutController(ModelContext modelContext, Mapper mapper) { _ModelContext = modelContext; _Mapper = mapper; }
public CustomersController() { _context = new ModelContext(); }
public LeaveTypeController(ILogger <LeaveTypeController> logger) { this.logger = logger; context = new ModelContext(); }
protected ScienceInfo GetItemWithDependencies(int itemId) { return(ModelContext.Get <ScienceInfo, int> (itemId)); }
protected override void DeleteItem(ScienceInfo item) { new DeleteCommand <ScienceInfo> (ModelContext, SecurityContext).Delete(item); ModelContext.SaveChanges(); }
public HomeController(ModelContext context) { _context = context; }
/// /// You can use the following additional attributes as you write your tests: /// /// Use ClassInitialize to run code before running the first test in the class [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { ModelContext.newForUnitTests(); }
public DiscsController(ModelContext context) { _context = context; }
protected override void AddItem(DocumentTypeInfo item) { ModelContext.Add <DocumentTypeInfo> (item); ModelContext.SaveChanges(); }
/// Use ClassCleanup to run code after all tests in a class have run [ClassCleanup()] public static void MyClassCleanup() { ModelContext.release(); }
public LecturersController(ModelContext context) { _context = context; }
public override void AddColumn(ModelContext ctx, string columnName, object o) { InnerGetValue(ctx, columnName, o, true); }
public TracksController(ModelContext context) { _context = context; }
public SyroeshkaRuService() { _db = new ModelContext(); _mapper = new Configure().Configuration().CreateMapper(); }
[TestMethod()] public void TestLoadAndSaveBank() { ModelContext.beginTrans(); try { CsModelMappers.BankDBMapper pdb = new CsModelMappers.BankDBMapper(); long count = pdb.RecordCount(); if (pdb.SelectFromObjectName != pdb.ManagedTableName) { long countFromSelectObject = pdb.dbConn.getLngValue("select count(*) from " + pdb.SelectFromObjectName); Assert.AreEqual(count, countFromSelectObject, "Count of records in managedTableName {0} and SelectFromObjectName {1} should be equal, as there needs to be exactly 1 to 1 match between records in managed table and selectFromObject.", pdb.ManagedTableName, pdb.SelectFromObjectName); } if (count == 0) { Assert.Inconclusive("No Bank in database, table is empty"); } else { /** * using (DataContext ctx = DBUtils.Current().dbContext()) { * * var query = ctx.ExecuteQuery<Bank>(@"SELECT * FROM " + pdb.SelectFromObjectName ).Skip(1).Take(1); * var lst = query.ToList(); * * Assert.AreEqual(lst.Count, 1, "Expected to receive 1 record, got: " + lst.Count); * * } * todo: fix boolean fields by generating properties of original fields **/ object pid = ModelContext.CurrentDBUtils.getObjectValue("select top 1 " + pdb.pkFieldName + " from " + pdb.ManagedTableName); Bank p = pdb.findByKey(pid); Bank p2 = (Bank)p.copy(); //Test equality and hash codes Assert.AreEqual(p.GetHashCode(), p2.GetHashCode()); Assert.AreEqual(p, p2); p.isDirty = true; // force save pdb.save(p); // now reload object from database p = null; p = pdb.findByKey(pid); //test fields to be equal before and after save Assert.IsTrue(p.PrBANKID == p2.PrBANKID, "Expected Field BANKID to be equal"); Assert.IsTrue(p.PrBankName == p2.PrBankName, "Expected Field BankName to be equal"); Assert.IsTrue(p.PrBankCode == p2.PrBankCode, "Expected Field BankCode to be equal"); Assert.IsTrue(p.PrBankSWIFTCode == p2.PrBankSWIFTCode, "Expected Field BankSWIFTCode to be equal"); p.isDirty = true; //to force save ModelContext.Current.saveModelObject(p); p = ModelContext.Current.loadModelObject <Bank>(p.Id); p.loadObjectHierarchy(); string json = JsonConvert.SerializeObject(p, Formatting.Indented, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); System.IO.FileInfo jf = new System.IO.FileInfo(".\\Bank.json"); System.IO.File.WriteAllText(jf.FullName, json); if (pdb.isPrimaryKeyAutogenerated) { p.isNew = true; p.isDirty = true; try { pdb.save(p); } catch (System.Exception e) { Assert.IsTrue(e.Message.ToUpper().Contains("UNIQUE INDEX") || e.Message.Contains("Violation of UNIQUE KEY constraint"), "Insert statement produced error other than violation of unique key:" + e.Message); } } } } finally { ModelContext.rollbackTrans(); // 'Nothing should be saved to the database! } }