Beispiel #1
0
        public IList <Product> GetRangeInCategory(int categoryId, int start, int end)
        {
            var criteria = DetachedCriteria.For <Product>()
                           .CreateCriteria("Categories")
                           .Add(Expression.Eq("Id", categoryId));

            return((IList <Product>)ActiveRecordMediator.SlicedFindAll(typeof(Product), start, end, criteria));
        }
Beispiel #2
0
        public static T FindAndCheck <T>(uint id) where T : Service
        {
            var client = ActiveRecordMediator <T> .FindByPrimaryKey(id);

            SecurityContext.Administrator.CheckRegion(client.HomeRegion.Id);
            SecurityContext.Administrator.CheckType(client.Type);
            return(client);
        }
Beispiel #3
0
 /// <summary>
 /// Closes the passed in session.
 /// Intended to be used in conjunction with checkSession.
 /// </summary>
 /// <param name="collection"></param>
 /// <param name="session">The session to close</param>
 /// <param name="sessionConfirmed">Used to remember if a session created by checkSession is still open.</param>
 internal static void cleanupSession(this IPersistentCollection collection, ISession session, ref bool sessionConfirmed)
 {
     if (session != null)
     {
         sessionConfirmed = false;
         ActiveRecordMediator.GetSessionFactoryHolder().ReleaseSession(session);
     }
 }
Beispiel #4
0
        public void delete(int id)
        {
            users auth = ActiveRecordBase <users> .Find(id);

            ActiveRecordMediator <users> .Delete(auth);

            RedirectToReferrer();
        }
Beispiel #5
0
        public void delete_usertags(int id)
        {
            usertags tag = ActiveRecordBase <usertags> .Find(id);

            ActiveRecordMediator <usertags> .Delete(tag);

            RedirectToReferrer();
        }
Beispiel #6
0
        /// <summary>
        /// Starts a <see cref="UnitOfWork" /> and creates the in memory db schema.
        /// </summary>
        /// <example>Using <see cref="RhinoContainer" />, <see cref="IoC" />, and <see cref="UnitOfWork" /> in your tests.
        /// <code lang="c#" escaped="true">
        /// using NUnit.Framework;
        /// using Rhino.Commons;
        /// using Rhino.Commons.ForTesting;
        ///
        /// [TestFixture]
        /// public class FooTest : NHibernateInMemoryTest
        /// {
        ///		[TestFixtureSetup]
        ///		public void TestFixtureSetup()
        ///		{
        ///			OneTimeInitialize("RhinoContainer.boo", typeof(Foo).Assembly);
        ///		}
        ///
        ///		[Setup]
        ///		public void TestSetup()
        ///		{
        ///			/// Creates a top level UnitOfWork, remember to clean me up
        ///			CreateUnitOfWork();
        ///		}
        ///
        ///		[TearDown]
        ///		public void TestTearDown()
        ///		{
        ///			/// Cleanup the top level UnitOfWork
        ///			UnitOfWork.Current.Dispose();
        ///		}
        ///
        ///		[Test]
        ///		public void CanSaveFoo()
        ///		{
        ///			Foo f = new Foo();
        ///			Foo res = null;
        ///			f.Name = "Bar";
        ///
        ///			Assert.AreEqual(Guid.Empty, f.Id);
        ///
        ///			With.Transaction(delegate
        ///			{
        ///				IoC.Resolve&lt;IRepository&lt;Foo&gt;&gt;.Save(f);
        ///			});
        ///
        ///			Assert.AreNotEqual(Guid.Empty, f.Id);
        ///
        ///			using(UnitOfWork.Start())
        ///				res = IoC.Resolve&lt;IRepository&lt;Foo&gt;&gt;.Load(f.Id);
        ///
        ///			Assert.IsNotNull(res);
        ///			Assert.AreEqual("Bar", res.Name);
        ///		}
        /// }
        /// </code>
        /// </example>
        /// <seealso cref="RhinoContainer" />
        /// <seealso cref="IoC" />
        /// <seealso cref="UnitOfWork" />
        public void CreateUnitOfWork()
        {
            UnitOfWork.Start();
            ISession session = ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(typeof(ActiveRecordBase));

            dbConnection = session.Connection;
            SetupDB();
        }
Beispiel #7
0
        public static Estabelecimento FindByCNPJ(string cnpj)
        {
            DetachedCriteria crit = DetachedCriteria.For <Estabelecimento>();

            crit.Add(Expression.Eq("CNPJ", cnpj));

            return(ActiveRecordMediator <Estabelecimento> .FindFirst(crit));
        }
Beispiel #8
0
 public IList <T> GetOtherMapBySql(string sql)
 {
     return((IList <T>) ActiveRecordMediator <T> .Execute(
                delegate(ISession session, object instance)
     {
         return session.CreateSQLQuery(sql).AddEntity("synonym", typeof(T)).List <T>();
     }, new T()));
 }
Beispiel #9
0
        public void CountQuery_ByType()
        {
            Prepare();
            CountQuery cq          = new CountQuery(typeof(Post));
            int        recordCount = (int)ActiveRecordMediator.ExecuteQuery(cq);

            Assert.AreEqual(3, recordCount);
        }
Beispiel #10
0
        public long CountAllInCategory(int categoryId)
        {
            var criteria = DetachedCriteria.For <Product>()
                           .CreateCriteria("Categories")
                           .Add(Expression.Eq("Id", categoryId));

            return(ActiveRecordMediator.Count(typeof(Product), criteria));
        }
Beispiel #11
0
        private static uint GetNextHighestPlayerId()
        {
            ScalarQuery idQuery = new ScalarQuery(typeof(CharacterRecord), QueryLanguage.Hql,
                                                  "select max(chr.EntityId) from CharacterRecord chr");
            object highestId = ActiveRecordMediator.ExecuteQuery(idQuery);

            return(highestId == null ? 0 : (highestId as CharacterRecord).EntityLowId + 1);
        }
        public void delete(int id)
        {
            person person = ActiveRecordBase <person> .Find(id);

            ActiveRecordMediator <person> .Delete(person);

            RedirectToAction("list");
        }
Beispiel #13
0
        public static Org GetSystemOrg()
        {
            if (_systemOrg == null)
            {
                _systemOrg = ActiveRecordMediator <Org> .FindAllByProperty("Name", "OIF")[0];
            }

            return(_systemOrg);
        }
 public void TearDown()
 {
     if (_session != null)
     {
         var holder = ActiveRecordMediator.GetSessionFactoryHolder();
         holder.ReleaseSession(session);
         _session = null;
     }
 }
 public void reorder_nav([ARDataBind("navs", Validate = true, AutoLoad = AutoLoadBehavior.NewRootInstanceIfInvalidKey)] categories[] navs)
 {
     HelperService.writelog("Editing reordering nav categories");
     foreach (categories nav in navs)
     {
         ActiveRecordMediator <categories> .Save(nav);
     }
     RedirectToAction("list_nav");
 }
        public void Delete(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            ActiveRecordMediator <T> .Delete(entity);
        }
Beispiel #17
0
        public List <Answer> GetTopAnswers(int questionId, int answerStart, int maxResults)
        {
            var answeres = ActiveRecordMediator <Answer> .SlicedFindAll(answerStart, maxResults,
                                                                        DetachedCriteria.For <Answer>().
                                                                        Add(Restrictions.Eq("QuestionId", questionId)),
                                                                        Order.Desc("Votes"));

            return(new List <Answer>(answeres));
        }
Beispiel #18
0
 public Token(MembershipUser user)
 {
     _user    = user;
     _BTTUser = (BTTUser)HttpContext.Current.Cache["user" + user.UserName];
     if (_BTTUser == null)
     {
         _BTTUser = ActiveRecordMediator <BTTUser> .FindByPrimaryKey(new Guid(user.ProviderUserKey.ToString()));
     }
 }
Beispiel #19
0
        public void CountQuery_PositionalParameters()
        {
            Prepare();
            object[]   parameters  = new object[] { "c" };
            CountQuery cq          = new CountQuery(typeof(Post), "Category = ?", parameters);
            int        recordCount = (int)ActiveRecordMediator.ExecuteQuery(cq);

            Assert.AreEqual(2, recordCount);
        }
Beispiel #20
0
 public void NHibernateNoTxVerification()
 {
     InitModel();
     using (ISession session = ActiveRecordMediator.GetSessionFactoryHolder().GetSessionFactory(typeof(ActiveRecordBase)).OpenSession())
     {
         session.Save(new SSAFEntity("example"));
         Assert.AreEqual(1, session.CreateQuery("from SSAFEntity").List <SSAFEntity>().Count);
     }
 }
        public void Evict(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            ActiveRecordMediator.Evict(entity);
        }
Beispiel #22
0
        private static ISession GetSession()
        {
            if (SessionScope.Current == null)
            {
                throw new InvalidOperationException("No active SessionScope found.");
            }

            return(ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(typeof(ActiveRecordBase)));
        }
        public void Setup()
        {
            Environment.CurrentDirectory    = TestContext.CurrentContext.TestDirectory;
            Global.Config.DocsPath          = "../../../AdminInterface/Docs/";
            Global.Config.RegisterListEmail = "*****@*****.**";

            ForTest.InitialzeAR();
            IntegrationFixture2.Factory = ActiveRecordMediator.GetSessionFactoryHolder().GetSessionFactory(typeof(ActiveRecordBase));
        }
        public void DeleteTag(int id, int advertisementId)
        {
            tags tag = ActiveRecordBase <tags> .Find(id);

            advertisement advertisement = ActiveRecordBase <advertisement> .Find(advertisementId);

            advertisement.Tags.Remove(tag);
            ActiveRecordMediator <advertisement> .Save(advertisement);
        }
        public void InsertOrUpdate(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            ActiveRecordMediator <T> .Save(entity);
        }
        public void Dispose()
        {
            ISessionFactoryHolder holder = ActiveRecordMediator.GetSessionFactoryHolder();

            foreach (ISessionFactory factory in holder.GetSessionFactories())
            {
                factory.Dispose();
            }
        }
Beispiel #27
0
        /// <summary>
        /// Atualiza um relacionamento "N para N".
        /// </summary>
        /// <typeparam name="I">O tipo da tabela intermediária</typeparam>
        /// <typeparam name="F">O tipo do dado da outra ponta do relacionamento</typeparam>
        /// <param name="itens">A coleção que armazena os registros <typeparamref name="I"/>, da tabela intermediária</param>
        /// <param name="selecionados">Uma lista de elementos <typeparamref name="F"/>, da outra ponta do relacionamento</param>
        /// <param name="creator">Um delegate especificando a criação de novos registros na tabela intermediária</param>
        /// <param name="getter">Um delegate especificando a obtenção de um registro do tipo <typeparamref name="I"/> (tabela da outra ponta do relacionamento) a partir de um registro <typeparamref name="F"/> (tabela intermediária)</param>
        /// <param name="delete">Um delegate especificando a exclusão de um registro da lista de itens</param>
        public static void AtualizaRelacionamento <I, F>(IList <I> itens, IEnumerable <F> selecionados,
                                                         Converter <F, I> creator, Converter <I, F> getter,
                                                         Action <I> delete)
            where I : class, IRecord
            where F : class, IRecord
        {
            if (itens == null)
            {
                throw new ArgumentNullException("itens");
            }
            if (creator == null)
            {
                throw new ArgumentNullException("creator");
            }
            if (getter == null)
            {
                throw new ArgumentNullException("getter");
            }
            if (selecionados == null)
            {
                selecionados = new F[0];
            }

            // preenche lista com todas as possibilidades de selecionados
            var todos = new List <F>(ActiveRecordMediator <F> .FindAll());

            // preenche mapa com os registros de relacionamento atuais
            var atuais = new Dictionary <F, I>();

            foreach (I item in itens)
            {
                atuais.Add(getter(item), item);
            }

            // cria novos registros selecionados novos, e previne exclusão de já existentes
            foreach (F selecionado in selecionados)
            {
                I item;
                if (!atuais.TryGetValue(selecionado, out item))
                {
                    item = creator(selecionado);
                    itens.Add(item);
                    atuais.Add(selecionado, item);
                }
                todos.Remove(selecionado);
            }

            // exclui os relacionamentos já existentes
            foreach (F selecionado in todos)
            {
                I item;
                if (atuais.TryGetValue(selecionado, out item))
                {
                    delete(item);
                }
            }
        }
Beispiel #28
0
        protected override int ExecuteInsert(IDictionary values)
        {
            ActiveRecordDataSourceCreateEventArgs args = new ActiveRecordDataSourceCreateEventArgs();

            args.ModelType    = BuildManager.GetType(Source.TypeName, false, true);
            args.CreateValues = values;

            CreateValuesFromCreateParameters(args);

            IClassMetadata meta = ActiveRecordMediator.GetSessionFactoryHolder().GetSessionFactory(args.ModelType).GetClassMetadata(args.ModelType);

            if (!meta.HasIdentifierProperty)
            {
                throw new ApplicationException("ActiveRecordDataSourceView requires a primary key for the update method.");
            }

            Source.OnBeforeCreate(args);

            if (args.Cancel)
            {
                return(0);
            }

            try
            {
                if (args.Entity == null)
                {
                    args.Entity = Activator.CreateInstance(args.ModelType);
                }

                foreach (string key in args.CreateValues.Keys)
                {
                    meta.SetPropertyValue(args.Entity, key, args.CreateValues[key]);
                }

                ActiveRecordMediator.Create(args.Entity);
            }
            catch (Exception e)
            {
                args.Exception = e;
                args.WasError  = true;

                Source.OnCreateError(args);

                if (Source.ThrowOnError && !args.DoNotThrow)
                {
                    throw;
                }

                return(0);
            }

            Source.OnCreate(args);

            return(1);
        }
Beispiel #29
0
 /// <summary> </summary>
 public void Update(int id, [DataBind("tag")] taxonomy tag)
 {
     try {
         ActiveRecordMediator <taxonomy> .Save(tag);
     } catch (Exception ex) {
         Flash["error"] = ex.Message;
         Flash["tag"]   = tag;
     }
     RedirectToAction("index");
 }
Beispiel #30
0
        /// <summary> </summary>
        public void massDeleteTags(int[] ids)
        {
            foreach (int id in ids)
            {
                taxonomy tag = ActiveRecordBase <taxonomy> .Find(id);

                ActiveRecordMediator <taxonomy> .Delete(tag);
            }
            RedirectToReferrer();
        }