Example #1
0
        private static IPagedList <T> FetchPaged <T>(this IQueryable <T> query, IQueryable <T> queryWithChildren,
                                                     IQueryable <T> childrenQueryWithGrandchildren, int pageIndex, int pageSize)
        {
            if (pageSize == 0)
            {
                pageSize = PageSize;
            }

            if (pageIndex == 0)
            {
                pageIndex = 1;
            }

            IFutureValue <int> futureCount = query.ToFutureValue(x => x.Count());

            IEnumerable <T> values1 = queryWithChildren.ToFuture();

            childrenQueryWithGrandchildren.ToFuture();

            IEnumerable <T> allValues = values1.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return(new PagedList <T>(
                       allValues,
                       (pageIndex - 1),
                       pageSize,
                       x => futureCount.Value));
        }
Example #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="queryable"></param>
        /// <param name="startIndex"></param>
        /// <param name="maxRows">A value of Zero means we're not paging</param>
        /// <param name="hasOrderBy"></param>
        /// <returns></returns>
        public async Task <RetrievedData <T> > RetrieveUsingPagingAsync(IQueryable <T> queryable, int startIndex, int maxRows, bool hasOrderBy = false, CancellationToken token = default(CancellationToken))
        {
            IFutureEnumerable <T> result;
            int totalCount = 0;
            IFutureValue <int> futureCount = null;

            if (maxRows > 0)
            {
                futureCount = queryable.ToFutureValue(f => f.Count());
                result      = queryable.Skip(startIndex * maxRows).Take(maxRows).ToFuture <T>();
            }
            else //get all
            {
                result = queryable.ToFuture <T>();
            }
            var toReturn = (await result.GetEnumerableAsync()).ToList();

            if (futureCount != null)
            {
                totalCount = futureCount.Value;
            }
            else
            {
                totalCount = toReturn.Count;
            }
            result      = null;
            futureCount = null;
            return(new RetrievedData <T>
            {
                DataBatch = toReturn ?? new List <T>(0),
                TotalCount = totalCount
            });
        }
Example #3
0
        protected virtual PagedList <T> FindPagedInternal(int pageIndex, int pageSize, Func <ICriteria, ICriteria> func)
        {
            ICriteria rowCountCriteria = func != null?func(CreateCriteria()) : CreateCriteria();

            rowCountCriteria.ClearOrders();
            IFutureValue <int> rowCount =
                rowCountCriteria
                .SetFirstResult(0)
                .SetMaxResults(RowSelection.NoValue)
                .SetProjection(Projections.RowCount())
                .FutureValue <int>();

            ICriteria pagingCriteria = func != null?func(CreateCriteria()) : CreateCriteria();

            IList <T> qryResult =
                pagingCriteria
                .SetFirstResult((pageIndex - 1) * pageSize)
                .SetMaxResults(pageSize)
                .Future <T>()
                .ToList <T>();

            PagedList <T> result = new PagedList <T>(qryResult, pageIndex, pageSize, rowCount.Value);

            return(result);
        }
Example #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="queryable"></param>
        /// <param name="startIndex"></param>
        /// <param name="maxRows">A value of Zero means we're not paging</param>
        /// <param name="hasOrderBy"></param>
        /// <returns></returns>
        public RetrievedData <T> RetrieveUsingPaging(IQueryable <T> queryable, int startIndex, int maxRows, bool hasOrderBy = false)
        {
            IFutureEnumerable <T> result;
            int totalCount = 0;
            IFutureValue <int> futureCount = null;

            if (maxRows > 0)
            {
                futureCount = queryable.ToFutureValue(f => f.Count());
                result      = queryable.Skip(startIndex * maxRows).Take(maxRows).ToFuture <T>();
            }
            else //get all
            {
                result = queryable.ToFuture <T>();
            }
            var toReturn = result.ToList();

            if (futureCount != null)
            {
                totalCount = futureCount.Value;
            }
            else
            {
                totalCount = toReturn.Count;
            }
            result      = null;
            futureCount = null;
            return(new RetrievedData <T>
            {
                DataBatch = toReturn ?? new List <T>(0),
                TotalCount = totalCount
            });
        }
Example #5
0
        /// <summary>
        /// Use this API it you did an aliastobean transform to type TTransform
        /// </summary>
        /// <typeparam name="TTransform"></typeparam>
        /// <param name="queryable"></param>
        /// <param name="startIndex"></param>
        /// <param name="maxRows">A value of Zero means we're not paging</param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public RetrievedData <TTransform> RetrieveUsingPaging <TTransform>(IQueryOver <T, T> queryable, int startIndex, int maxRows, bool hasOrderBy = false)
            where TTransform : class //, IEntity<idT>
        {
            IEnumerable <TTransform> result;
            int totalCount = 0;
            IFutureValue <int> futureCount = null;

            if (maxRows > 0)
            {
                futureCount = queryable.Clone().Select(Projections.RowCount()).FutureValue <int>();
                result      = queryable.Skip(startIndex * maxRows).Take(maxRows).Future <TTransform>();
            }
            else //get all
            {
                result = queryable.Future <TTransform>();
            }
            var toReturn = result.ToList();

            if (futureCount != null)
            {
                totalCount = futureCount.Value;
            }
            else
            {
                totalCount = toReturn.Count;
            }
            result      = null;
            futureCount = null;
            return(new RetrievedData <TTransform>
            {
                DataBatch = toReturn,
                TotalCount = totalCount
            });
        }
Example #6
0
        /// <summary>
        /// The get one by moodle id.
        /// </summary>
        /// <param name="userId">
        /// The user id.
        /// </param>
        /// <param name="lmsQuizId">
        /// The lms quiz id.
        /// </param>
        /// <param name="companyLmsId">
        /// The company Lms Id.
        /// </param>
        /// <returns>
        /// The <see cref="IFutureValue{Quiz}"/>.
        /// </returns>
        public IFutureValue <Quiz> GetOneByLmsQuizId(int userId, int lmsQuizId, int companyLmsId)
        {
            QueryOver <User, User> companyQuery =
                new DefaultQueryOver <User, int>().GetQueryOver()
                .Where(x => x.Id == userId)
                .Select(res => res.Company.Id);
            IFutureValue <int> id = this.userRepository.FindOne <int>(companyQuery);

            Quiz              q   = null;
            SubModuleItem     smi = null;
            SubModuleCategory smc = null;
            User              u2  = null;

            var query =
                new DefaultQueryOver <Quiz, int>().GetQueryOver(() => q)
                .WhereRestrictionOn(x => x.LmsQuizId).IsNotNull
                .And(x => x.LmsQuizId == lmsQuizId)
                .JoinQueryOver(x => x.SubModuleItem, () => smi, JoinType.InnerJoin)
                .JoinQueryOver(() => smi.SubModuleCategory, () => smc, JoinType.InnerJoin)
                .Where(() => smc.CompanyLmsId != null && smc.CompanyLmsId == companyLmsId)
                .JoinQueryOver(() => smi.CreatedBy, () => u2, JoinType.InnerJoin)
                .Where(() => u2.Company.Id == id.Value && (int)u2.Status == 1)
                .Take(1);

            return(this.Repository.FindOne(query));
        }
        private IFutureValue <T> ExecuteQueryTreeFutureValue <T>(Expression queryExpression)
        {
            var tree = new QueryRelationTree();
            IFutureValue <T> result = null;

            foreach (var path in IncludePaths)
            {
                tree.AddNode(path);
            }

            var leafs = tree.GetLeafs();

            leafs.Sort();
            var expressions = leafs.Aggregate(new ExpressionInfo(queryExpression), FetchFromPath).GetExpressions();
            var i           = 0;

            foreach (var expression in expressions)
            {
                if (i == 0)
                {
                    result = _queryProvider.ExecuteFutureValue <T>(expression);
                }
                else
                {
                    _queryProvider.ExecuteFuture <T>(expression);
                }
                i++;
            }
            return(result);
        }
Example #8
0
        /// <summary>
        ///     Versuch über ein Detached Criteria die Where-Klauseln zu verarbeiten, damit es mit dem Order nicht zu
        ///     komplikationen kommt.
        /// </summary>
        protected virtual IPage <T> Find(IPageable pageable, Action <DetachedCriteria> criteriaBuilder, Action <ICriteria> ordersBuilder = null)
        {
            Require.NotNull(pageable, "pageable");
            Require.NotNull(criteriaBuilder, "criteriaBuilder");

            HibernateDelegate <IPage <T> > finder = delegate(ISession session) {
                DetachedCriteria whereCriteria = DetachedCriteria.For(typeof(T));
                criteriaBuilder(whereCriteria);
                whereCriteria.SetProjection(Projections.Property("Id"));

                ICriteria elementsCriteria = session.CreateCriteria(typeof(T));
                elementsCriteria.Add(Subqueries.PropertyIn("Id", whereCriteria));

                if (ordersBuilder != null)
                {
                    ordersBuilder(elementsCriteria);
                }
                ApplyPaging(pageable, elementsCriteria);

                ICriteria countCriteria = session.CreateCriteria(typeof(T));
                countCriteria.Add(Subqueries.PropertyIn("Id", whereCriteria));
                countCriteria.SetProjection(Projections.RowCountInt64());

                IFutureValue <long> futureTotalCount = countCriteria.FutureValue <long>();
                IEnumerable <T>     futureElements   = elementsCriteria.Future <T>();
                Page <T>            page             = new Page <T>(futureElements.ToList(), pageable, futureTotalCount.Value);
                return(page);
            };

            return(HibernateTemplate.Execute(finder));
        }
Example #9
0
 /// <summary>
 /// Add an item to the dictionary
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="key"></param>
 /// <param name="value"></param>
 public void Add <T>(string key, IFutureValue <T> value)
 {
     _items.Add(new FutureHolder <T>()
     {
         Key = key, Value = value
     });
 }
Example #10
0
        /// <summary>
        /// Gets all objects that are of the right type and have the right tag. Never
        /// returns null.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tag"></param>
        /// <param name="recursive">If true this and all known subdirectories will be searched</param>
        /// <returns></returns>
        public IFutureValue <T>[] GetTaggedObjects <T>(string tag, bool recursive = false)
        {
            IFutureValue <T>[] localResult = null;
            if (_taggedObjects.ContainsKey(tag))
            {
                localResult = (from t in _taggedObjects[tag]
                               let o = t as IFutureValue <T>
                                       where o != null
                                       select o).ToArray();
            }
            else
            {
                localResult = new IFutureValue <T> [0];
            }

            IFutureValue <T>[] recursiveResult = null;
            if (recursive)
            {
                recursiveResult = (from subdir in _subDirs.Value
                                   from taggedPlot in subdir.GetTaggedObjects <T>(tag, true)
                                   select taggedPlot).ToArray();
            }
            else
            {
                recursiveResult = new IFutureValue <T> [0];
            }

            return(localResult.Concat(recursiveResult).ToArray());
        }
Example #11
0
 public LazyPage(IEnumerable <T> list, int currentpage, int pagesize, IFutureValue <long> total)
 {
     _sourcelist       = list;
     _currentPageIndex = currentpage;
     _pageSize         = pagesize;
     _totalitems       = total;
 }
Example #12
0
 /// <summary>
 /// Divide to future values that are integers. Return a double (as we should be!!).
 /// </summary>
 /// <param name="numerator"></param>
 /// <param name="denominator"></param>
 /// <returns></returns>
 public static IFutureValue <double> DivideBy(this IFutureValue <int> numerator, IFutureValue <int> denominator)
 {
     return(new DoFutureOperator <double>(
                () => ((double)numerator.Value) / ((double)denominator.Value),
                () => numerator.HasValue && denominator.HasValue,
                () => Task.WhenAll(numerator.GetAvailibleTask(), denominator.GetAvailibleTask())));
 }
Example #13
0
 public LoanHistoryByDay(IFutureValue <Loan> loan, IFutureValue <LoanHistory> before, IFutureValue <LoanHistory> expected, IFutureValue <LoanHistory> after)
 {
     _loan     = loan;
     _before   = before;
     _expected = expected;
     _after    = after;
 }
Example #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="theQueryOver"></param>
        /// <param name="startIndex"></param>
        /// <param name="maxRows">A value of Zero means we're not paging</param>
        /// <param name="hasOrderBy"></param>
        /// <returns></returns>
        public RetrievedData <T> RetrieveUsingPaging(IQueryOver <T, T> theQueryOver, int startIndex, int maxRows, bool hasOrderBy = false)
        {
            IEnumerable <T>    result;
            int                totalCount  = 0;
            IFutureValue <int> futureCount = null;

            if (maxRows > 0)
            {
                futureCount = theQueryOver.Clone().Select(Projections.RowCount()).FutureValue <int>();
                result      = theQueryOver.Skip(startIndex * maxRows).Take(maxRows).Future <T>();
            }
            else //get all
            {
                result = theQueryOver.Future <T>();
            }
            var toReturn = result.ToList();

            if (futureCount != null)
            {
                totalCount = futureCount.Value;
            }
            else
            {
                totalCount = toReturn.Count;
            }
            result      = null;
            futureCount = null;
            return(new RetrievedData <T>
            {
                DataBatch = toReturn,
                TotalCount = totalCount
            });
        }
Example #15
0
        public void SecondLevelCacheWithMixedCacheRegionsFuture()
        {
            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    User user = new User()
                    {
                        Name = "test"
                    };
                    s.Save(user);
                    tx.Commit();
                }

            using (ISession s = OpenSession())
            {
                // cacheable Future, not evaluated yet
                IFutureValue <User> userFuture =
                    s.CreateCriteria <User>()
                    .Add(Restrictions.NaturalId().Set("Name", "test"))
                    .SetCacheable(true)
                    .SetCacheRegion("region1")
                    .FutureValue <User>();

                // different cache-region causes batch to be non-cacheable
                int count =
                    s.CreateCriteria <User>()
                    .SetProjection(Projections.RowCount())
                    .SetCacheable(true)
                    .SetCacheRegion("region2")
                    .FutureValue <int>()
                    .Value;

                Assert.That(userFuture.Value, Is.Not.Null);
                Assert.That(count, Is.EqualTo(1));

                DeleteObjectsOutsideCache(s);
            }

            using (ISession s = OpenSession())
            {
                IFutureValue <User> userFuture =
                    s.CreateCriteria <User>()
                    .Add(Restrictions.NaturalId().Set("Name", "test"))
                    .SetCacheable(true)
                    .SetCacheRegion("region1")
                    .FutureValue <User>();

                int count =
                    s.CreateCriteria <User>()
                    .SetProjection(Projections.RowCount())
                    .SetCacheable(true)
                    .SetCacheRegion("region2")
                    .FutureValue <int>()
                    .Value;

                Assert.That(userFuture.Value, Is.Null,
                            "query results should not come from cache");
            }
        }
Example #16
0
        /// <summary>
        /// The get one by id.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <returns>
        /// The <see cref="IFutureValue{T}"/>.
        /// </returns>
        public virtual IFutureValue <T> GetOneById(TId id)
        {
            IFutureValue <T> result = this.Repository.Session.CreateCriteria(typeof(T))
                                      .Add(Restrictions.IdEq(id))
                                      .FutureValue <T>();

            return(result);
        }
Example #17
0
 /// <summary>
 /// When requested, we will extract the value from the source.
 /// </summary>
 /// <typeparam name="TSource"></typeparam>
 /// <typeparam name="TResult"></typeparam>
 /// <param name="source"></param>
 /// <param name="extractor"></param>
 /// <returns></returns>
 public static IFutureValue <TResult> ExtractValue <TSource, TResult>(this IFutureValue <TSource> source, Func <TSource, TResult> extractor)
 {
     return(new DoFutureOperator <TResult>(
                () => extractor(source.Value),
                () => source.HasValue,
                () => source.GetAvailibleTask()
                ));
 }
Example #18
0
 /// <summary>
 /// Select pattern - so that one can access the monad in situ.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <typeparam name="M"></typeparam>
 /// <param name="self"></param>
 /// <param name="map"></param>
 /// <returns></returns>
 public static IFutureValue <T> Select <T, M>(this IFutureValue <M> self, Func <M, T> map)
 {
     return(new DoFutureOperator <T>(
                () => map(self.Value),
                () => self.HasValue,
                () => self.GetAvailibleTask()
                ));
 }
Example #19
0
        /// <summary>
        /// Exists.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public virtual bool Exists(TId id)
        {
            IFutureValue <T> result = this.Repository.Session.CreateCriteria(typeof(T))
                                      .Add(Restrictions.IdEq(id))
                                      .FutureValue <T>();

            return(!(result.Value == null));
        }
Example #20
0
        public int QuantidadeVeiculosEmuso()
        {
            IFutureValue <int> criteria = _session.CreateCriteria <Veiculo>()
                                          .Add(Restrictions.Eq("Situacao", Situacao.Emuso))
                                          .SetProjection(Projections.Count("Id"))
                                          .FutureValue <int>();

            return(criteria.Value);
        }
 protected virtual PagesGridViewModel<SiteSettingPageViewModel> CreateModel(IEnumerable<SiteSettingPageViewModel> pages,
     PagesFilter request, IFutureValue<int> count, IEnumerable<LookupKeyValue> categoriesFuture, IList<LookupKeyValue> layouts)
 {
     return new PagesGridViewModel<SiteSettingPageViewModel>(
         pages.ToList(),
         request,
         count.Value,
         categoriesFuture.ToList()) { Layouts = layouts };
 }
Example #22
0
        public decimal UltimaQuilometragemDoVeiculo(Veiculo veiculo)
        {
            IFutureValue <decimal> criteria = _session.CreateCriteria <Hodometro>()
                                              .Add(Restrictions.Eq("Veiculo.Id", veiculo.Id))
                                              .SetProjection(Projections.Max("Quilometragem"))
                                              .FutureValue <decimal>();

            return(criteria.Value);
        }
Example #23
0
        /// <summary>
        /// The get applet sub module items by user id.
        /// </summary>
        /// <param name="userId">
        /// The user id.
        /// </param>
        /// <returns>
        /// The <see cref="IEnumerable{SubModuleItem}"/>.
        /// </returns>
        public IEnumerable <SubModuleItemDTO> GetQuizSMItemsByUserId(int userId)
        {
            QueryOver <User, User> query =
                new DefaultQueryOver <User, int>().GetQueryOver()
                .Where(x => x.Id == userId)
                .Select(res => res.Company.Id);
            IFutureValue <int> companyId = this.userRepository.FindOne <int>(query);

            SubModuleItemFromStoredProcedureDTO dto = null;
            SubModuleItem     smi    = null;
            SubModuleCategory smc    = null;
            Quiz quiz                = null;
            SubModuleItemTheme theme = null;
            User u         = null;
            var  queryOver =
                new DefaultQueryOver <SubModuleItem, int>().GetQueryOver(() => smi)
                .JoinQueryOver(x => x.SubModuleCategory, () => smc)
                .JoinQueryOver(() => smi.Quizes, () => quiz)
                .JoinQueryOver(() => smi.Themes, () => theme, JoinType.LeftOuterJoin)
                .JoinQueryOver(() => smc.User, () => u, JoinType.InnerJoin)
                .Where(() => smi.CreatedBy != null && smc.User != null && ((smi.CreatedBy.Id == userId && smc.User.Id == userId) ||
                                                                           (u.Company.Id == companyId.Value && quiz.LmsQuizId != null)))
                .SelectList(res =>
                            res.Select(() => smi.CreatedBy.Id)
                            .WithAlias(() => dto.createdBy)
                            .Select(() => smi.Id)
                            .WithAlias(() => dto.subModuleItemId)
                            .Select(() => smc.SubModule.Id)
                            .WithAlias(() => dto.subModuleId)
                            .Select(() => smi.SubModuleCategory.Id)
                            .WithAlias(() => dto.subModuleCategoryId)
                            .Select(() => smi.IsShared)
                            .WithAlias(() => dto.isShared)
                            .Select(() => smi.ModifiedBy.Id)
                            .WithAlias(() => dto.modifiedBy)
                            .Select(() => smi.DateCreated)
                            .WithAlias(() => dto.dateCreated)
                            .Select(() => smi.DateModified)
                            .WithAlias(() => dto.dateModified)
                            .Select(() => smi.IsActive)
                            .WithAlias(() => dto.isActive)
                            .Select(() => theme.Id)
                            .WithAlias(() => dto.themeId))
                .TransformUsing(Transformers.AliasToBean <SubModuleItemFromStoredProcedureDTO>());
            var result =
                this.Repository.FindAll <SubModuleItemFromStoredProcedureDTO>(queryOver)
                .ToList()
                .Select(x => new SubModuleItemDTO(x))
                .ToList();
            var themeIds   = result.Where(x => x.themeId.HasValue).Select(x => x.themeId.Value).ToList();
            var themeQuery = new DefaultQueryOver <SubModuleItemTheme, int>().GetQueryOver().WhereRestrictionOn(x => x.Id).IsIn(themeIds);
            var themes     = this.themeRepository.FindAll(themeQuery).ToList();

            result.ForEach(x => x.themeVO = x.themeId.HasValue ? themes.FirstOrDefault(t => t.Id == x.themeId).Return(tt => new SubModuleItemThemeDTO(tt), null) : null);
            return(result);
        }
        static void Main(string[] args)
        {
            IFutureValue <int> v1future = FutureCalculate(10);
            IFutureValue <int> v2future = FutureCalculate(5);

            IFutureValue <int> vtotal = $(v1future + v2future);

            // Expect this to write out 15!
            Console.WriteLine($"Final value is {vtotal.Value}.");
        }
Example #25
0
        public bool ExistFascicleDefinition(int idCategory)
        {
            IFutureValue <int> result = NHibernateSession.QueryOver <CategoryFascicle>()
                                        .Where(x => x.FascicleType != FascicleType.SubFascicle)
                                        .Where(x => x.Category.Id == idCategory)
                                        .SelectList(list => list.SelectCount(s => s.Id))
                                        .FutureValue <int>();

            return(result.Value > 0);
        }
        private static IFutureValue <long> MontarQueryPaginado <T>(IQueryOver <T, T> query, int pagina, int tamanhoPagina) where T : class
        {
            IFutureValue <long> count = query.ToRowCountInt64Query().FutureValue <long>();

            if (pagina > 0 && tamanhoPagina > 0)
            {
                query.Skip((pagina - 1) * tamanhoPagina).Take(tamanhoPagina);
            }

            return(count);
        }
Example #27
0
        /// <summary>
        /// Show how the LINQ from statement in P01 is syntatic sugar already
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            IFutureValue <int> v1future = FutureCalculate(10);
            IFutureValue <int> v2future = FutureCalculate(5);

            IFutureValue <int> vtotal = v1future
                                        .SelectMany(v1 => v2future, (u, v) => u + v);

            // Expect this to write out 15!
            Console.WriteLine($"Final value is {vtotal.Value}.");
        }
Example #28
0
        public async Task SecondLevelCacheWithMixedCacheableAndNonCacheableFutureAsync()
        {
            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    User user = new User()
                    {
                        Name = "test"
                    };
                    await(s.SaveAsync(user));
                    await(tx.CommitAsync());
                }

            using (ISession s = OpenSession())
            {
                // cacheable Future, not evaluated yet
                IFutureValue <User> userFuture =
                    s.CreateCriteria <User>()
                    .Add(Restrictions.NaturalId().Set("Name", "test"))
                    .SetCacheable(true)
                    .FutureValue <User>();

                int count =
                    await(s.CreateCriteria <User>()
                          .SetProjection(Projections.RowCount())
                          .FutureValue <int>()
                          .GetValueAsync());

                Assert.That(await(userFuture.GetValueAsync()), Is.Not.Null);
                Assert.That(count, Is.EqualTo(1));

                await(DeleteObjectsOutsideCacheAsync(s));
            }

            using (ISession s = OpenSession())
            {
                IFutureValue <User> userFuture =
                    s.CreateCriteria <User>()
                    .Add(Restrictions.NaturalId().Set("Name", "test"))
                    .SetCacheable(true)
                    .FutureValue <User>();

                int count =
                    await(s.CreateCriteria <User>()
                          .SetProjection(Projections.RowCount())
                          .FutureValue <int>()
                          .GetValueAsync());

                Assert.That(await(userFuture.GetValueAsync()), Is.Not.Null,
                            "query results should come from cache");
                Assert.That(count, Is.EqualTo(0),
                            "query results should not come from cache");
            }
        }
        static void Main(string[] args)
        {
            IFutureValue <int> v1future = FutureCalculate(10);

            IFutureValue <int> vtotal = from v1 in v1future
                                        select v1 + 1;

            //IFutureValue<int> vtotal = $(v1future + 1);

            // Expect this to write out 11!
            Console.WriteLine($"Final value is {vtotal.Value}.");
        }
Example #30
0
        public BatchCompletionStatus GetCompletionStatus(BatchRun batchRun)
        {
            IFutureValue <decimal?> timeTaken =
                GetResultsQuery(batchRun)
                .Where(result => result.MillisecondsTaken != null)
                .Select(Projections.Sum <BatchRunResult>(result => result.MillisecondsTaken))
                .Cacheable()
                .FutureValue <decimal?>();
            IFutureValue <double?> averageTimeTaken =
                GetResultsQuery(batchRun)
                .Where(result => result.MillisecondsTaken != null)
                .Select(Projections.Avg <BatchRunResult>(result => result.MillisecondsTaken))
                .Cacheable()
                .FutureValue <double?>();
            IFutureValue <int> pending =
                GetResultsQuery(batchRun)
                .Where(result => result.Status == JobExecutionStatus.Pending)
                .Select(Projections.Count <BatchRunResult>(result => result.Id))
                .Cacheable()
                .FutureValue <int>();
            IFutureValue <int> failed =
                GetResultsQuery(batchRun)
                .Where(result => result.Status == JobExecutionStatus.Failed)
                .Select(Projections.Count <BatchRunResult>(result => result.Id))
                .Cacheable()
                .FutureValue <int>();
            IFutureValue <int> succeeded =
                GetResultsQuery(batchRun)
                .Where(result => result.Status == JobExecutionStatus.Succeeded)
                .Select(Projections.Count <BatchRunResult>(result => result.Id))
                .Cacheable()
                .FutureValue <int>();
            IFutureValue <int> total =
                GetResultsQuery(batchRun)
                .Select(Projections.Count <BatchRunResult>(result => result.Id))
                .Cacheable()
                .FutureValue <int>();


            double averageTime   = averageTimeTaken.Value.GetValueOrDefault();
            int    pendingNumber = pending.Value;

            return(new BatchCompletionStatus
            {
                Total = total.Value,
                Failed = failed.Value,
                Pending = pendingNumber,
                Succeeded = succeeded.Value,
                TimeTaken = TimeSpan.FromMilliseconds(Convert.ToDouble(timeTaken.Value.GetValueOrDefault())),
                AverageTimeTaken = averageTime.ToString("0.00ms"),
                EstimatedTimeRemaining = TimeSpan.FromMilliseconds(averageTime * pendingNumber)
            });
        }
 protected virtual PagesGridViewModel<SiteSettingPageViewModel> CreateModel(IEnumerable<SiteSettingPageViewModel> pages,
     PagesFilter request, IFutureValue<int> count, IList<LookupKeyValue> layouts)
 {
     return new PagesGridViewModel<SiteSettingPageViewModel>(
         pages.ToList(),
         request,
         count.Value) { Layouts = layouts };
 }
 protected virtual PagesGridViewModel<SiteSettingPageViewModel> CreateModel(IEnumerable<PageProperties> pages,
     PagesFilter request, IFutureValue<int> count, IList<LookupKeyValue> layouts, IList<CategoryLookupModel> categoriesLookupList)
 {
     var pagesList = new List<SiteSettingPageViewModel>();
     foreach (var page in pages)
     {
         var model = new SiteSettingPageViewModel();
         model.Id = page.Id;
         model.Version = page.Version;
         model.Title = page.Title;
         model.PageStatus = page.Status;
         model.CreatedOn = page.CreatedOn.ToFormattedDateString();
         model.ModifiedOn = page.ModifiedOn.ToFormattedDateString();
         model.PageUrl = page.PageUrl;
         model.IsMasterPage = page.IsMasterPage;
         model.LanguageId = page.Language != null ? page.Language.Id : Guid.Empty;
         pagesList.Add(model);
     }
     return new PagesGridViewModel<SiteSettingPageViewModel>(
         pagesList,
         request,
         count.Value) { Layouts = layouts, CategoriesLookupList = categoriesLookupList};
 }
 /// <summary>
 /// Write out a line...
 /// </summary>
 /// <param name="futureString"></param>
 public static void FutureWriteLine(IFutureValue<string> futureString)
 {
     _lines.Add(() => futureString.Value);
 }
 public static IActionBuilder ConductContent(this IActionBuilder builder, IFutureValue<StockDetailModel> detailModel, Conductor<IStockTickerContentViewModel> conductor)
 {
     return builder.Execute<IConductStockTickerContent>(new { detailModel, conductor = (Action<IStockTickerContentViewModel>)conductor.ActivateItem });
 }
Example #35
0
 /// <summary>
 /// Divide the first by the second histogram
 /// </summary>
 /// <param name="hnum"></param>
 /// <param name="denom"></param>
 /// <returns></returns>
 public static IFutureValue<NTH1> DividedBy(this IFutureValue<NTH1> hnum, IFutureValue<NTH1> denom)
 {
     return from hn in hnum
            from hd in denom
            select InternalDivide(hn, hd);
 }
 // NOTE: Lazy initialized detail model is provided here.
 public ConductStockTickerContent(IFutureValue<StockDetailModel> detailModel, Action<IStockTickerContentViewModel> conductor, IContentViewModelFactory contentFactory)
 {
     this.detailModel = detailModel;
     this.conductor = conductor;
     this.contentFactory = contentFactory;
 }