Пример #1
0
 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;
            }
        }
Пример #4
0
        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;
            }
        }
Пример #8
0
        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);
        }
        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);
        }
    OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
 {
     System.Diagnostics.Debug.WriteLine("NH: " + sql);
     if (_log.IsDebugEnabled)
         _log.Debug(sql);
     return base.OnPrepareStatement(sql);
 }
Пример #11
0
        /// <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 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()));
 }
Пример #13
0
 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;
 }
Пример #14
0
		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");
		}
Пример #15
0
        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;
        }
Пример #16
0
        /// <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 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);
            }
        }
Пример #18
0
 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();
 }
Пример #19
0
        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");
        }
Пример #20
0
 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);
 }
 /// <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)};
 }
Пример #22
0
 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;
 }
Пример #23
0
 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);
 }
Пример #24
0
        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);
 }
Пример #29
0
		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);
		}
        private static void TreatConfiguration(NHibernate.Cfg.Configuration configuration)
        {
            var update = new SchemaUpdate(configuration);
            update.Execute(false, true);
            //            configuration.SetProperty("current_session_context_class", "web");


        }