/// <summary>
        /// (re)index an entity.
        /// Non indexable entities are ignored
        /// The entity must be associated with the session
        /// </summary>
        /// <param name="entity">The entity to index - must not be null</param>
        /// <returns></returns>
        public IFullTextSession Index(object entity)
        {
            using (new SessionIdLoggingContext(sessionImplementor.SessionId))
            {
                if (entity == null)
                {
                    return(this);
                }

                System.Type clazz = NHibernateUtil.GetClass(entity);
                ISearchFactoryImplementor searchFactoryImplementor = SearchFactoryImplementor;

                // TODO: Cache that at the FTSession level
                // not strictly necesary but a small optmization
                DocumentBuilder builder = searchFactoryImplementor.DocumentBuilders[clazz];
                if (builder != null)
                {
                    object id   = session.GetIdentifier(entity);
                    Work   work = new Work(entity, id, WorkType.Index);
                    searchFactoryImplementor.Worker.PerformWork(work, eventSource);
                }

                return(this);
            }
        }
        private void ProcessWorkByLayer(IList <Work> queue, int initialSize, List <LuceneWork> luceneQueue, Layer layer)
        {
            /* By Kailuo Wang
             * This sequence of the queue is reversed which is different from the Java version
             * By reversing the sequence here, it ensures that the work that is added to the queue later has higher priority.
             * I did this to solve the following problem I encountered:
             * If you update an entity before deleting it in the same transaction,
             * There will be two Works generated by the event listener: Update Work and Delete Work.
             * However, the Update Work will prevent the Delete Work from being added to the queue and thus
             * fail purging the index for that entity.
             * I am not sure if the Java version has the same problem.
             */
            for (int i = initialSize - 1; i >= 0; i--)
            {
                Work work = queue[i];
                if (work == null || !layer.IsRightLayer(work.WorkType))
                {
                    continue;
                }

                queue[i] = null; // help GC and avoid 2 loaded queues in memory
                System.Type entityClass = work.Entity is System.Type
                                          ? (System.Type)work.Entity
                                          : NHibernateUtil.GetClass(work.Entity);

                DocumentBuilder builder = this.searchFactoryImplementor.DocumentBuilders[entityClass];
                if (builder == null)
                {
                    continue; //or exception?
                }

                builder.AddToWorkQueue(entityClass, work.Entity, work.Id, work.WorkType, luceneQueue, this.searchFactoryImplementor);
            }
        }
        private string GetEntityName(object entity)
        {
            var type = NHibernateUtil.GetClass(entity);

            if (type == typeof(Client))
            {
                return("клиента");
            }
            if (type == typeof(Supplier))
            {
                return("поставщика");
            }
            if (type == typeof(LegalEntity))
            {
                return("юр. Лица");
            }
            if (type == typeof(User))
            {
                return("пользователя");
            }
            if (type == typeof(Payer))
            {
                return("плательщика");
            }
            if (type == typeof(News))
            {
                return("новости");
            }
            return("не определено");
        }
示例#4
0
 public virtual Type GetRealType()
 {
     // NHibernate
     // https://www.nuget.org/packages/NHibernate/
     // Install-Package -Id NHibernate -Project Northwind.Logic
     // Install-Package -Id NHibernate -Project Northwind.UI
     return(NHibernateUtil.GetClass(this));
 }
示例#5
0
 public JournalRecord(Loadable loadable, string name, string filename)
 {
     CreateAt   = DateTime.Now;
     RecordId   = loadable.GetId();
     RecordType = NHibernateUtil.GetClass(loadable).Name;
     Name       = name;
     Filename   = filename;
 }
示例#6
0
        public static IEnumerable <PropertyEntry> ToPropertyEntry(
            this PreInsertEvent @event)
        {
            var entityType = NHibernateUtil.GetClass(@event.Entity);

            return(@event.State
                   .Select((t, i) => @event.Persister.PropertyNames[i])
                   .Select((name, i) => new NHibernatePropertyEntry(entityType.GetProperty(@event.Persister.PropertyNames[i]), false, null, @event.State, i)));
        }
示例#7
0
        private IEnumerable <object> GetDomainEvents(
            Type eventType,
            object entity,
            IEnumerable <PropertyEntry> properties)
        {
            var entityType = NHibernateUtil.GetClass(entity);

            return(SelfAndInterfaces(entityType.GetInterfaces(), entityType)
                   .Select(t => Activator.CreateInstance(eventType.MakeGenericType(t), entity, entityType, properties)));
        }
示例#8
0
 public override DataTemplate SelectTemplate(object item, DependencyObject container)
 {
     if (item != null)
     {
         string           resourceKey = NHibernateUtil.GetClass(item).Name + "_template";
         FrameworkElement element     = (FrameworkElement)container;
         return(element.TryFindResource(resourceKey) as DataTemplate);
     }
     return(null);
 }
示例#9
0
        public static bool IsTransient(ISession session, object obj)
        {
            ISessionFactoryImplementor sessionFactoryImpl = session.SessionFactory as ISessionFactoryImplementor;
            // Here `obj` may be an instance of an NHibernate proxy, so we cannot simply use
            // `obj.GetType().FullName`, we need to get the real underlying type.
            var persister = new SessionFactoryHelper(sessionFactoryImpl)
                            .RequireClassPersister(NHibernateUtil.GetClass(obj).FullName);
            bool?yes = persister.IsTransient(obj, (ISessionImplementor)session);

            return(yes ?? default(bool));
        }
示例#10
0
 public string MapToFile(object entity)
 {
     try
     {
         var clazz = NHibernateUtil.GetClass(entity);
         var root  = Path.Combine(RootDir, clazz.Name.Pluralize());
         var id    = Util.GetValue(entity, "Id");
         return(Directory.GetFiles(root, id + ".*").FirstOrDefault());
     }
     catch (DirectoryNotFoundException) {
         return(null);
     }
 }
示例#11
0
        public static T CastAs <T>(this object source) where T : class
        {
            if (source is INHibernateProxy)
            {
                var type = NHibernateUtil.GetClass(source);
                if (type != typeof(T))
                {
                    throw new ApplicationException(string.Format("Cannot cast {0} to {1}", type.Name, typeof(T).Name));
                }

                return(((INHibernateProxy)source).HibernateLazyInitializer.GetImplementation() as T);
            }
            return(source as T);
        }
示例#12
0
 public void CanUseClassConstraint()
 {
     using (ISession session = OpenSession())
     {
         var crit = session
                    .CreateCriteria(typeof(Animal), "a")
                    .Add(Property
                         .ForName("a.class")
                         .Eq(typeof(Animal)));
         var results = crit.List <Animal>();
         Assert.AreEqual(1, results.Count);
         Assert.AreEqual(typeof(Animal), NHibernateUtil.GetClass(results[0]));
     }
 }
示例#13
0
        public static IEnumerable <PropertyEntry> ToPropertyEntry(
            this PreUpdateEvent @event)
        {
            var entityType = NHibernateUtil.GetClass(@event.Entity);

            return(@event.State
                   .Select((t, i) => @event.Persister.PropertyNames[i])
                   .Select((name, i) =>
            {
                var isModified = @event.Persister.PropertyTypes[i].IsModified(@event.OldState[i], @event.State[i], new[] { false }, @event.Session);

                return new NHibernatePropertyEntry(entityType.GetProperty(@event.Persister.PropertyNames[i]), isModified, @event.OldState, @event.State, i);
            }));
        }
        private void GeneralizationPropertyChanged(object entity, string message = null)
        {
            var idLabel = BindingHelper.TryGetDescription(NHibernateUtil.GetClass(entity), "Id");

            if (idLabel == null)
            {
                idLabel = "Код " + GetEntityName(entity);
            }
            From = "*****@*****.**";
            PropertyBag["message"] = message;
            PropertyBag["admin"]   = SecurityContext.Administrator;
            PropertyBag["entity"]  = entity;
            PropertyBag["type"]    = Inflector.Pluralize(NHibernateUtil.GetClass(entity).Name);
            PropertyBag["idLabel"] = idLabel;
        }
示例#15
0
        public static bool Is <T>(this object entity)
        {
            if (entity == null)
            {
                return(false);
            }

            var proxy = entity as INHibernateProxy;

            if (proxy != null)
            {
                return(typeof(T).IsAssignableFrom(NHibernateUtil.GetClass(entity)));
            }

            return(entity is T);
        }
示例#16
0
 protected void SessionGaurd <T>(ISession session, T entity, Action <ISession, T> action)
 {
     if (session != null && session.IsOpen)
     {
         action(session, entity);
     }
     else
     {
         using (var s = Env.Factory.OpenSession())
             using (var t = s.BeginTransaction()) {
                 var e = s.Load(NHibernateUtil.GetClass(entity), Util.GetValue(entity, "Id"));
                 action(s, (T)e);
                 s.Flush();
                 t.Commit();
             }
     }
 }
        public override bool IsValid(object instance, object fieldvalue)
        {
            if (fieldvalue == null)
            {
                return(true);
            }
            var instanceType = NHibernateUtil.GetClass(instance);
            var model        = AR.Holder.GetModel(instanceType);

            if (model == null)
            {
                throw new ValidationFailure("Couldn't figure out the primary key for " + instanceType.FullName +
                                            " so can't ensure the uniqueness of any field. Validator failed.");
            }

            return(AR.Execute(instanceType, session => {
                var origflushmode = session.FlushMode;
                session.FlushMode = FlushMode.Never;

                try {
                    var criteria = session.CreateCriteria(model.Type)
                                   .SetProjection(Projections.RowCount());

                    if (Property.Name.Equals(model.PrimaryKey.Key, StringComparison.InvariantCultureIgnoreCase))
                    {
                        // IsUniqueValidator is on the PrimaryKey Property, simplify query
                        criteria.Add(Restrictions.Eq(Property.Name, fieldvalue));
                    }
                    else
                    {
                        var id = instance.GetType().GetProperty(model.PrimaryKey.Key).GetValue(instance, null);
                        ICriterion pKeyCriteria = (id == null)
                                                    ? Restrictions.IsNull(model.PrimaryKey.Key)
                                                    : Restrictions.Eq(model.PrimaryKey.Key, id);

                        criteria.Add(Restrictions.And(Restrictions.Eq(Property.Name, fieldvalue), Restrictions.Not(pKeyCriteria)));
                    }

                    return criteria.UniqueResult <int>() == 0;
                } finally {
                    session.FlushMode = origflushmode;
                }
            }));
        }
示例#18
0
        public static bool EqualDomainObjects(object obj1, object obj2)
        {
            if (obj1 == null || obj2 == null)
            {
                return(false);
            }

            if (NHibernateUtil.GetClass(obj1) != NHibernateUtil.GetClass(obj2))
            {
                return(false);
            }

            if (obj1 is IDomainObject)
            {
                return((obj1 as IDomainObject).Id == (obj2 as IDomainObject).Id);
            }

            return(obj1.Equals(obj2));
        }
示例#19
0
        /// <summary>
        /// Called when a new entity is added to the persistence context via <see cref="PersistenceContext.Lock(ClearCanvas.Enterprise.Core.Entity)"/> with
        /// <see cref="DirtyState.New"/>.
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <param name="propertyNames"></param>
        /// <param name="types"></param>
        /// <returns></returns>
        public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types)
        {
            // ignore the addition of log entries (any subclass of LogEntry)
            if (typeof(LogEntry).IsAssignableFrom(NHibernateUtil.GetClass(entity)))
            {
                return(false);
            }

            // we could validate the entity here, but it seems rather counter-productive, given
            // that the entity is not actually being written to the DB yet and further changes
            // may be made to it by the application before it is written.  Therefore, we choose
            // not to validate the entity here, but instead put it in a queue to be validated at flush time
            _pendingValidations.Enqueue((DomainObject)entity);

            // build a list of property diffs
            // the previous state is "null" since the entity was just created
            var propertyDiffs = GetPropertyDiffs(propertyNames, types, state, null);

            RecordChange(entity, EntityChangeType.Create, propertyDiffs);
            return(false);
        }
示例#20
0
        public OrderDetailsViewModel(IOrder order, List <uint> fProducts = null)
        {
            InitFields();
            orderId = order.Id;
            type    = NHibernateUtil.GetClass(order);
            if (IsCurrentOrder)
            {
                DisplayName = "Текущий заказ";
            }
            else
            {
                DisplayName = "Архивный заказ";
            }
            Lines           = new NotifyValue <IList <IOrderLine> >(new List <IOrderLine>(), Filter);
            MatchedWaybills = new MatchedWaybills(this,
                                                  CurrentLine.OfType <SentOrderLine>().ToValue(),
                                                  new NotifyValue <bool>(!IsCurrentOrder));
            if (User.CanExport(this, type.Name))
            {
                ExcelExporter.Properties = new[] { "Lines" }
            }
            ;
            else
            {
                ExcelExporter.Properties = new string[0];
            }
            ExcelExporter.ActiveProperty.Refresh();
            frozenProducts = fProducts ?? new List <uint>();

            FilterItems = new List <Selectable <Tuple <string, string> > >();
            FilterItems.Add(
                new Selectable <Tuple <string, string> >(Tuple.Create("InFrozenOrders", "Позиции присутствуют в замороженных заказах")));
            FilterItems.Add(new Selectable <Tuple <string, string> >(Tuple.Create("IsMinCost", "Позиции по мин.ценам")));
            FilterItems.Add(new Selectable <Tuple <string, string> >(Tuple.Create("IsNotMinCost", "Позиции не по мин.ценам")));
            FilterItems.Add(new Selectable <Tuple <string, string> >(Tuple.Create("OnlyWarning", "Только позиции с корректировкой")));

            PrintMenuItems = new ObservableCollection <MenuItem>();
            IsView         = true;
        }
        public object Update(uint id, bool?status, bool?free, bool?accounted, decimal?payment, DateTime?freePeriodEnd, string addComment)
        {
            var account = DbSession.Load <Account>(id);

            //хак будь бдителен, что бы получить объект реального типа и работали проверки
            //account is UserAccount нужно спросить тип объекта у хибера и загружать объект с учетом правильного типа
            account         = (Account)DbSession.Load(NHibernateUtil.GetClass(account), id);
            account.Comment = addComment;
            var result = UpdateAccounting(account.Id, accounted, payment, free, freePeriodEnd);

            if (status != null)
            {
                if (account is UserAccount)
                {
                    var user = ((UserAccount)account).User;
                    SetUserStatus(user.Id, status, addComment);
                }
                else if (account is AddressAccount)
                {
                    var address = ((AddressAccount)account).Address;
                    SetAddressStatus(address.Id, status, addComment);
                }
                else if (account is SupplierAccount)
                {
                    SetSupplierStatus(((SupplierAccount)account).Supplier, status.Value, addComment);
                }
                else
                {
                    account.Status = status.Value;
                }
            }
            DbSession.Save(account);
            if (freePeriodEnd.HasValue)
            {
                result = new { data = freePeriodEnd.Value.ToShortDateString() }
            }
            ;
            return(result);
        }
示例#22
0
        private System.Tuple <IObservable <EventPattern <HttpProgressEventArgs> >, IObservable <Stream> > ObserveLoad(Loadable loadable)
        {
            ProgressMessageHandler progress = null;
            HttpClientHandler      handler  = null;
            var client = Settings.Value.GetHttpClient(Shell.Config, ref progress, ref handler);

            var data = new[] {
                String.Format("urn:data:{0}:{1}", NHibernateUtil.GetClass(loadable).Name.ToLower(), loadable.GetId())
            };

            //review - я не понимаю как это может быть но если сделать dispose у observable
            //то ожидающий запрос тоже будет отменен и cancellationtoke не нужен
            //очевидного способа как это может работать нет но как то оно работает
            var result = Tuple.Create(
                Observable.FromEventPattern <HttpProgressEventArgs>(progress, "HttpReceiveProgress"),
                Observable
                .Using(() => client, c => c.PostAsJsonAsync("Download", data).ToObservable())
                .Do(r => r.EnsureSuccessStatusCode())
                .SelectMany(r => r.Content.ReadAsStreamAsync().ToObservable())
                );

            return(Env.WrapRequest(result));
        }
示例#23
0
        public static LogObjectType GetLogObjectType(object entity)
        {
            var type = NHibernateUtil.GetClass(entity);

            if (type == typeof(Client))
            {
                return(LogObjectType.Client);
            }
            if (type == typeof(Supplier))
            {
                return(LogObjectType.Supplier);
            }
            if (type == typeof(Address))
            {
                return(LogObjectType.Address);
            }
            if (type == typeof(User))
            {
                return(LogObjectType.User);
            }

            throw new Exception(String.Format("Не могу определить тип объекта для {0}", entity));
        }
示例#24
0
        public void VerifyHistoryNae1()
        {
            // load original "tnae1" TargetNotAuditedEntity to force load "str1" UnversionedStrTestEntity as Proxy
            var original = Session.Get <TargetNotAuditedEntity>(tnae1_id);

            var uste1 = Session.Get <UnversionedStrTestEntity>(uste1_id);
            var uste2 = Session.Get <UnversionedStrTestEntity>(uste2_id);

            var rev1 = AuditReader().Find <TargetNotAuditedEntity>(tnae1_id, 1);
            var rev2 = AuditReader().Find <TargetNotAuditedEntity>(tnae1_id, 2);
            var rev3 = AuditReader().Find <TargetNotAuditedEntity>(tnae1_id, 3);
            var rev4 = AuditReader().Find <TargetNotAuditedEntity>(tnae1_id, 4);

            Assert.AreEqual(uste1, rev1.Reference);
            Assert.AreEqual(uste2, rev2.Reference);
            Assert.AreEqual(uste2, rev3.Reference);
            Assert.AreEqual(uste1, rev4.Reference);

            Assert.IsTrue(original.Reference is INHibernateProxy);
            Assert.AreEqual(typeof(UnversionedStrTestEntity), NHibernateUtil.GetClass(original.Reference));
            Assert.AreEqual(typeof(UnversionedStrTestEntity), NHibernateProxyHelper.GetClassWithoutInitializingProxy(rev1.Reference));
            Assert.AreEqual(typeof(UnversionedStrTestEntity), NHibernateUtil.GetClass(rev1.Reference));
        }
示例#25
0
        private static object CloneSingle(object cloneObject)
        {
            if (cloneObject == null)
            {
                return(null);
            }
            if (cloneObject is ICloneable)
            {
                return((cloneObject as ICloneable).Clone());
            }

            Type itemType = NHibernateUtil.GetClass(cloneObject);

            if (itemType.IsClass)
            {
                object newObject = Activator.CreateInstance(itemType);
                FieldsCopy(cloneObject, ref newObject);

                return(newObject);
            }

            throw new NotSupportedException();
        }
示例#26
0
 public virtual Type GetRealType()
 {
     return(NHibernateUtil.GetClass(this));
 }
示例#27
0
        private static void ProcessContainedIn(Object instance, List <LuceneWork> queue, DocumentMapping documentMapping,
                                               ISearchFactoryImplementor searchFactoryImplementor)
        {
            foreach (var containedIn in documentMapping.ContainedIn)
            {
                object value = containedIn.Getter.Get(instance);

                if (value == null)
                {
                    continue;
                }

                Array array = value as Array;
                if (array != null)
                {
                    foreach (object arrayValue in array)
                    {
                        // Highly inneficient but safe wrt the actual targeted class, e.g. polymorphic items in the array
                        System.Type valueType = NHibernateUtil.GetClass(arrayValue);
                        if (valueType == null || !searchFactoryImplementor.DocumentBuilders.ContainsKey(valueType))
                        {
                            continue;
                        }

                        ProcessContainedInValue(arrayValue, queue, valueType, searchFactoryImplementor.DocumentBuilders[valueType],
                                                searchFactoryImplementor);
                    }
                }
                else if (typeof(IEnumerable).IsAssignableFrom(value.GetType()))
                {
                    // NB We only see ISet and IDictionary`2 as IEnumerable
                    IEnumerable collection = value as IEnumerable;
                    if (typeof(IDictionary).IsAssignableFrom(value.GetType()))
                    {
                        collection = ((IDictionary)value).Values;
                    }

                    if (collection == null)
                    {
                        continue;
                    }

                    foreach (object collectionValue in collection)
                    {
                        // Highly inneficient but safe wrt the actual targeted class, e.g. polymorphic items in the array
                        System.Type valueType = NHibernateUtil.GetClass(collectionValue);
                        if (valueType == null || !searchFactoryImplementor.DocumentBuilders.ContainsKey(valueType))
                        {
                            continue;
                        }

                        ProcessContainedInValue(collectionValue, queue, valueType,
                                                searchFactoryImplementor.DocumentBuilders[valueType], searchFactoryImplementor);
                    }
                }
                else
                {
                    System.Type valueType = NHibernateUtil.GetClass(value);
                    if (valueType == null || !searchFactoryImplementor.DocumentBuilders.ContainsKey(valueType))
                    {
                        continue;
                    }

                    ProcessContainedInValue(value, queue, valueType, searchFactoryImplementor.DocumentBuilders[valueType],
                                            searchFactoryImplementor);
                }
            }

            //an embedded cannot have a useful @ContainedIn (no shared reference)
            //do not walk through them
        }
        private object UpdateAccounting(uint accountId, bool?accounted, decimal?payment, bool?isFree, DateTime?freePeriodEnd)
        {
            object result  = null;
            var    account = DbSession.Load <Account>(accountId);

            //хак будь бдителен, что бы получить объект реального типа и работали проверки
            //account is UserAccount нужно спросить тип объекта у хибера и загружать объект с учетом правильного типа
            account = (Account)DbSession.Load(NHibernateUtil.GetClass(account), accountId);

            if (freePeriodEnd.HasValue)
            {
                account.FreePeriodEnd = freePeriodEnd.Value;
            }

            if (accounted.HasValue)
            {
                if (accounted.Value)
                {
                    account.Accounted();
                }
                else
                {
                    account.BeAccounted = false;
                }
            }

            if (isFree.HasValue)
            {
                IEnumerable <Address> addresses = null;
                if (account is UserAccount)
                {
                    addresses = ((UserAccount)account).User
                                .AvaliableAddresses
                                .Where(a => a.Accounting.IsFree)
                                .ToArray();
                }

                account.IsFree = isFree.Value;

                if (addresses != null && !account.IsFree && addresses.Any())
                {
                    foreach (var address in addresses)
                    {
                        address.Accounting.IsFree = isFree.Value;
                    }
                    result = new {
                        accounts = addresses.Select(a => new {
                            id   = a.Accounting.Id,
                            free = a.Accounting.IsFree
                        }).ToArray(),
                        message = String.Format("Следующие адреса доставки стали платными: {0}", addresses.Implode(a => a.Value))
                    };
                }
            }

            if (payment.HasValue)
            {
                Admin.CheckPermisions(PermissionType.ChangePayment);
                account.Payment = payment.Value;
            }

            if (account.IsChanged(a => a.Payment))
            {
                Mail().AccountChanged(account);
            }

            DbSession.Save(account);

            return(result);
        }
示例#29
0
 public static bool IsAssignableFrom <T>(object source) where T : class
 {
     return((source is INHibernateProxy)
         ? (NHibernateUtil.GetClass(source).IsAssignableFrom(typeof(T)))
         : (source.GetType().IsAssignableFrom(typeof(T))));
 }
 public DocumentBuilder GetDocumentBuilder(object entity)
 {
     System.Type type = NHibernateUtil.GetClass(entity);
     return(GetDocumentBuilder(type));
 }