public object Generate(NHibernate.Engine.ISessionImplementor session, object obj) { // can operate more handy with "obj", when all entities will be inherited from // common base class // todo: ?implement somewhere const for "Entities" string? return PKGenDao.GetNextPK("Entities"); }
/// <summary> /// Returns to nhibernate the type of the parameters. /// I need only one operator. /// </summary> /// <param name="criteria"></param> /// <param name="criteriaQuery"></param> /// <returns></returns> public override NHibernate.Engine.TypedValue[] GetTypedValues( NHibernate.ICriteria criteria, NHibernate.Expressions.ICriteriaQuery criteriaQuery) { return new TypedValue[] { new TypedValue(GetITypeFromCLRType(mValueToCompareTo.GetType()), mValueToCompareTo)}; }
private static int Seed() { using (var session = SessionFactory.OpenSession()) using (var tx = session.BeginTransaction()) { var editora = new Editora { Nome = "Addion Wesley" }; session.Save(editora); var autores = new[] { "Gamma", "Helm", "Jhonson", "Vlissides" } .Select(nome => new Autor { Nome = nome }) .ToArray(); foreach (var autor in autores) session.Save(autor); var livro = new Livro { Nome = "Design Patterns - GoF", Sinopse = "O clássico", Editora = editora }; foreach (var autor in autores) livro.Autores.Add(autor); session.Save(livro); tx.Commit(); return livro.Id; } }
public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, NHibernate.Type.IType[] types) { IAuditable auditable = entity as IAuditable; if (auditable != null) { IClock clock = kernel.Resolve<IClock>(); IApplicationContext appContext = kernel.Resolve<IApplicationContext>(); currentState[Array.IndexOf<string>(propertyNames, "UpdatedAt")] = clock.Now; currentState[Array.IndexOf<string>(propertyNames, "UpdatedBy")] = appContext.FullUserName; Project auditProject = auditable.AuditProject; if (auditProject != null) { ProjectHistoryStep historyStep = new ProjectHistoryStep(); historyStep.Description = string.Format("Updated {0}", auditable.HistoryDescription); historyStep.At = clock.Now; historyStep.By = appContext.FullUserName; historyStep.Project = auditProject; historyStep.Create(); } return true; } return false; }
// this piece of code was difficult for me to come up with. public object Generate(NHibernate.Engine.ISessionImplementor session, object obj) { var record = obj as IIdentifiable; if (record == null) throw new ArgumentOutOfRangeException("obj"); return record.ComputeIdentity(); }
public override bool OnFlushDirty( object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, NHibernate.Type.IType[] types) { if (previousState != null) { for (int i = 0; i < propertyNames.Length; i++) { string msg = string.Format(">>>>-->>>>> {0}: Previous Name = {1} , Curr Value = {2}", propertyNames[i], previousState[i], currentState[i]); //System.Diagnostics.Debug.WriteLine(msg); System.Diagnostics.Trace.WriteLine(msg); Trace.WriteLine(msg); } } return base.OnFlushDirty(entity, id, currentState, previousState, propertyNames, types); }
public void OnLoad(NHibernate.Event.LoadEvent @event, LoadType loadType) { if (null == @event.Result) return; // Short circuit if (!ShouldContinue(@event.Session, @event.Result.GetType())) return; ISecurable securable = @event.Result as ISecurable; if (null == securable) { // TODO: Consider making this an Exception... System.Console.WriteLine("Implements ISecurable but can't be cast as ISecurable..."); return; } // Attempt at fixing the Day->Trip problem... if ("InternalLoadLazy".Equals(loadType.ToString())) return; var entityName = @event.Session.GetFilterParameterValue("EntityNameFilter.EntityName") as string; //bool canLoad = securable.GetAccessList().Where(ace => ace.EntityName == entityName).Any(); System.Console.WriteLine("ACL size: {0}", securable.AccessControlList.Count()); bool canLoad = securable.IsLoadableFor(entityName); System.Console.WriteLine("loadType {0}\tLockMode: {1}", loadType, @event.LockMode); System.Console.WriteLine("CanLoad entity {2} for organization [{0}]? {1}", entityName, canLoad, @event.Result.GetType().FullName); if (!canLoad) { @event.Result = null; } }
public static IList<Row> GetRows (NHibernate.ISession session, DataFilter dataFilter) { lock (session) return dataFilter.Analysis.First().Parameters .Select(o => new AnalysisParameterRow(o, dataFilter) as Row) .ToList(); }
public static void ConfigureDataAccess(IPersistenceConfigurer databaseConfigurer, InstanceScope sessionScope, out NHibernate.Cfg.Configuration cfg) { NHibernate.Cfg.Configuration configuration = null; ObjectFactory.Initialize(i => ConfigureDataAccess(i, databaseConfigurer, sessionScope, out configuration)); ObjectFactory.AssertConfigurationIsValid(); cfg = configuration; }
OnPrepareStatement(NHibernate.SqlCommand.SqlString sql) { System.Diagnostics.Debug.WriteLine("NH: " + sql); if (_log.IsDebugEnabled) _log.Debug(sql); return base.OnPrepareStatement(sql); }
/// <summary> /// 采用NHibernate的Transaction /// 在外部开始Transaction,外部处理Exception /// </summary> /// <param name="cmds"></param> /// <param name="session"></param> public static void UpdateTransaction(ICollection<MyDbCommand> cmds, NHibernate.ISession session) { if (cmds == null) { throw new ArgumentNullException("cmds"); } if (cmds.Count == 0) { return; } if (session == null) { throw new ArgumentNullException("session"); } DbConnection conn = session.Connection as DbConnection; if (conn == null) { throw new NotSupportedException("session must be DbConnection session"); } DbHelper.UpdateTransaction(cmds, new DbHelper.SetCommand(delegate(MyDbCommand cmd) { session.Transaction.Enlist(cmd.Command); cmd.Command.Connection = conn; })); }
public void WrapDbDriver_Inject_does_not_throw_for_NH_310() { using (NHibernate.Version(NHibernateVersion.NH_310)) { _sut.Inject(); } }
public void MapToEntityFromMap(NHibernate.Envers.Configuration.AuditConfiguration verCfg, object obj, IDictionary<object, object> data, object primaryKey, NHibernate.Envers.Reader.IAuditReaderImplementor versionsReader, long revision) { // //TODO in implementing second phase///////////// //if (obj == null) { // return; // } ////System.Type entityClass = ReflectionTools.loadClass(owningEntityName); // System.Runtime.Remoting.ObjectHandle hdl = Activator.CreateInstance(owningEntityName); // System.Type entityClass = hdl.GetType(); // Object value; // try { // value = versionsReader.CreateQuery().ForEntitiesAtRevision(entityClass, revision) // .Add(AuditEntity.relatedId(owningReferencePropertyName).eq(primaryKey)).GetSingleResult(); // } catch (NoResultException e) { // value = null; // } catch (NonUniqueResultException e) { // throw new AuditException("Many versions results for one-to-one relationship: (" + owningEntityName + // ", " + owningReferencePropertyName + ")"); // } // Setter setter = ReflectionTools.getSetter(obj.getClass(), propertyData); // setter.set(obj, value, null); }
private ISession getExistingOrNewSession(NHibernate.ISessionFactory factory) { if (HttpContext.Current != null) { ISession session = GetExistingWebSession(); if (session == null) { session = openSessionAndAddToContext(factory); } else if (!session.IsOpen) { session = openSessionAndAddToContext(factory); } return session; } if (currentSession == null) { currentSession = factory.OpenSession(); } else if (!currentSession.IsOpen) { currentSession = factory.OpenSession(); } return currentSession; }
public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types) { { for (var i = 0; i < state.Length; i++) { switch (propertyNames[i]) { case "CreatedOn": state[i] = state[i] ?? DateTime.UtcNow; break; case "CreatedBy": state[i] = state[i] ?? CurrentUser.Identity.Name; break; case "ModifiedOn": state[i] = DateTime.UtcNow; break; case "ModifiedBy": state[i] = CurrentUser.Identity.Name; break; } } return base.OnSave(entity, id, state, propertyNames, types); } }
public virtual void MapTypes(List<Type> allTypes, NHibernate.Cfg.Configuration cfg, Func<string, string> formatter) { var m = new HbmMapping(); m.Items = allTypes.Select(t => { var sc = new HbmSubclass(); sc.name = GetName(t); sc.extends = GetName(t.BaseType); sc.discriminatorvalue = map.GetOrCreateDefinition(t).Discriminator ?? t.Name; sc.lazy = false; sc.lazySpecified = true; var propertyMappings = GetPersistables(t) .Select(p => p.Attribute.GetPropertyMapping(p.DeclaringProperty, formatter)) .ToList(); if (propertyMappings.Count > 0) { if (sc.Items == null) sc.Items = propertyMappings.ToArray(); else sc.Items = sc.Items.Union(propertyMappings).ToArray(); } logger.DebugFormat("Generating subclass {0} with discriminator {1} extending {2} with {3} items ({4} property mappings)", sc.name, sc.discriminatorvalue, sc.extends, sc.Items != null ? sc.Items.Length.ToString() : "(null)", propertyMappings.Count); return sc; }).ToArray(); if (Debugger.IsAttached) { var dbg = m.AsString(); } cfg.AddDeserializedMapping(m, "N2"); }
public JsonResult getTable() { using (var session = NHibernate.OpenSession()) { using (var transaction = session.BeginTransaction()) { var sql = String.Format("SELECT * FROM information_schema.tables"); var query = session.CreateSQLQuery(sql); var result = query.List(); List <string> tableName = new List <string>(); object tableSpec; IList collection; for (int i = 0; i < result.Count; i++) { tableSpec = result[i]; collection = (IList)tableSpec; tableName.Add(collection[2].ToString()); } return(Json(tableName, JsonRequestBehavior.AllowGet)); } } }
public virtual void MapTypes(List<Type> allTypes, NHibernate.Cfg.Configuration cfg, Func<string, string> formatter) { var m = new HbmMapping(); m.Items = allTypes.Select(t => { var sc = new HbmSubclass(); sc.name = GetName(t); sc.extends = GetName(t.BaseType); sc.discriminatorvalue = map.GetOrCreateDefinition(t).Discriminator ?? t.Name; sc.lazy = false; sc.lazySpecified = true; var propertyMappings = GetPersistables(t) .Select(p => p.Attribute.GetPropertyMapping(p.DeclaringProperty, formatter)) .ToList(); if (propertyMappings.Count > 0) { if (sc.Items == null) sc.Items = propertyMappings.ToArray(); else sc.Items = sc.Items.Union(propertyMappings).ToArray(); } return sc; }).ToArray(); var dbg = m.AsString(); cfg.AddDeserializedMapping(m, "N2"); }
/// <summary> /// Returns to nhibernate the type of the parameters. /// I need only one operator. /// </summary> /// <param name="criteria"></param> /// <param name="criteriaQuery"></param> /// <returns></returns> public override NHibernate.Engine.TypedValue[] GetTypedValues( NHibernate.ICriteria criteria, NHibernate.Criterion.ICriteriaQuery criteriaQuery) { return new TypedValue[] { new TypedValue(GetITypeFromCLRType(mValueToCompareTo.GetType()), mValueToCompareTo, EntityMode.Poco)}; }
public override void AddToCriteria(NHibernate.ICriteria criteria) { if (IsGreaterThan()) criteria.Add(Restrictions.Gt(_Projections.EmptyGroupDoubleAvg(PropertyName), GetValue())); else criteria.Add(Restrictions.Lt(_Projections.EmptyGroupDoubleAvg(PropertyName), GetValue())); }
protected virtual void BuildSchema(NHib.Cfg.Configuration config) { // this NHibernate tool takes a configuration (with mapping info in) // and exports a database schema from it new SchemaExport(config) .Create(false, false); }
public GroupingControlForm(NHibernate.ISessionFactory sessionFactory) { InitializeComponent(); this.session = sessionFactory.OpenSession(); tlvGroupedFiles.CanExpandGetter += x => (((tlvBranch)x).Data is SpectrumSourceGroup && ((tlvBranch)x).Children.Any()); tlvGroupedFiles.ChildrenGetter += getChildren; tlvGroups.AspectGetter += x => { var nodeTracker = ((tlvBranch) x); var offsetCorrection = 0; while (nodeTracker.Parent.Text != null) { offsetCorrection++; nodeTracker = nodeTracker.Parent; } return ((tlvBranch) x).Text + new string(' ',offsetCorrection*7); }; tlvGroups.AutoCompleteEditor = false; tlvGroups.ImageGetter += delegate(object x) { return (((tlvBranch)x).Data is SpectrumSourceGroup) ? Properties.Resources.XPfolder_closed : Properties.Resources.file; }; ApplyDefaultGroups(null, null); }
private ISession openSessionAndAddToContext(NHibernate.ISessionFactory factory) { ISession session = factory.OpenSession(); HttpContext.Current.Items.Remove(GetType().FullName); HttpContext.Current.Items.Add(GetType().FullName, session); return session; }
/// <summary> /// Occurred when the specified entity is saved. /// </summary> public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types) { if(entity is IStateEntity) return ((IStateEntity)entity).IsSaved = true; return false; }
public static void GenerateSchema(NHibernate.Cfg.Configuration cfg, ISession session) { var dialect = Dialect.GetDialect(cfg.Properties); var drops = cfg.GenerateDropSchemaScript(dialect); ExecuteSqlScripts(drops, session); var scripts = cfg.GenerateSchemaCreationScript(dialect); ExecuteSqlScripts(scripts, session); }
private void ValidarNome(Visao visao, NHibernate.ISession session) { var qdtVisoesComMesmoNome = session.Query<Visao>() .Count(i => i.Nome.Equals(visao.Nome) && (i.Id != visao.Id)); if (qdtVisoesComMesmoNome > 0) throw new BLLException("Esse nome já está sendo usado por outra visão"); }
public override void MontarCriterios(NHibernate.Criterion.DetachedCriteria criterios) { #region Pré-condições Assertion.NotNull(criterios, "Criterios está nulo").Validate(); #endregion criterios.Add(Expression.Eq("Vigente", true)); }
private static void BuildSchema(NHibernate.Cfg.Configuration config) { new SchemaUpdate(config).Execute(false, true); string schemaFile = Path.Combine(Path.GetDirectoryName(typeof (SubscriptionService).Assembly.Location), typeof (SubscriptionService).Name + ".sql"); new SchemaExport(config).SetOutputFile(schemaFile).Execute(false, false, false); }
public void NullSafeSet(IDbCommand cmd, object value, int index, bool[] settable, NHibernate.Engine.ISessionImplementor session) { NHibernateUtil.Int32.NullSafeSet(cmd, (value == null) ? (object)null : ((ContentRelation)value).ForeignID, index); //if(value == null) // cmd.Parameters[index] = DBNull.Value; //else // cmd.Parameters[index] = ((ContentRelation)value).ForeignID; }
public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql) { //if (NumberOfRequests++ > 10) //{ // new SoundPlayer("http://www.shockwave-sound.com/sound-effects/scream-sounds/2scream.wav").PlaySync(); //} return base.OnPrepareStatement(sql); }
private static void TreatConfiguration(NHibernate.Cfg.Configuration configuration) { var update = new SchemaUpdate(configuration); update.Execute(false, true); // configuration.SetProperty("current_session_context_class", "web"); }
protected override Proxy.IProxyFactory BuildProxyFactory(PersistentClass persistentClass, NHibernate.Properties.IGetter idGetter, NHibernate.Properties.ISetter idSetter) { // allows defining a custom proxy factory, which is responsible for // generating lazy proxies for a given entity. // // Here we simply use the default... return base.BuildProxyFactory(persistentClass, idGetter, idSetter); }
public JsonResult getDataType() { using (var session = NHibernate.OpenSession()) { using (var transaction = session.BeginTransaction()) { var query = session.CreateSQLQuery("select Name from DataType"); var result = query.List(); return(Json(result, JsonRequestBehavior.AllowGet)); } } }
public string Generator(string tableName, string fieldName1, string dataType1, string fieldName2, string dataType2, string Parent) { try { if (Parent == null) //=> No Relation { var projectCollection = ProjectCollection.GlobalProjectCollection; string projPath = "~/BlogIT.Web.csproj"; var p = projectCollection.LoadProject(Server.MapPath(projPath)); string projItem1 = "~/Entities/" + tableName + ".cs"; GenerateTable genTable = new GenerateTable(tableName); genTable.AddFields(fieldName1, dataType1, fieldName2, dataType2); genTable.GenerateCSharpCode(Server.MapPath(projItem1)); p.AddItem("Compile", Server.MapPath(projItem1)); p.Save(); string projItem2 = "~/Mapping/" + tableName + "Map.cs"; GenerateMap genMap = new GenerateMap(tableName); genMap.AddConstructor(fieldName1, fieldName2, tableName); genMap.GenerateCSharpCode(Server.MapPath(projItem2)); p.AddItem("Compile", Server.MapPath(projItem2)); p.Save(); ProjectCollection.GlobalProjectCollection.UnloadProject(p); p.Build(); NHibernate.OpenSession(); } else if (Parent != null)//=> Relation To Parent { var projectCollection = ProjectCollection.GlobalProjectCollection; string projPath = "~/MVCNHibernate.csproj"; var p = projectCollection.LoadProject(Server.MapPath(projPath)); string fileNameEn = "~/Entities/" + tableName + ".cs"; GenerateTable genTable = new GenerateTable(tableName); genTable.RelationalAddFields(tableName, fieldName1, dataType1, fieldName2, dataType2, Parent); genTable.GenerateCSharpCode(Server.MapPath(fileNameEn)); string projItem1 = "~/Entities/" + tableName + ".cs"; p.AddItem("Compile", Server.MapPath(projItem1)); p.Save(); string fileNameMap = "~/Mapping/" + tableName + "Map.cs"; GenerateMap genMap = new GenerateMap(tableName); genMap.RelationalAddConstructor(fieldName1, fieldName2, tableName, Parent); genMap.GenerateCSharpCode(Server.MapPath(fileNameMap)); string projItem2 = "~/Mapping/" + tableName + "Map.cs"; p.AddItem("Compile", Server.MapPath(projItem2)); p.Save(); //ProjectCollection.GlobalProjectCollection.UnloadProject(p); ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); p.Build(); NHibernate.OpenSession(); } return("Database generated Successfully "); } catch { return("Database did not generate Successfully "); } }