示例#1
0
        /// <summary>
        /// 调用方法(警告,不支持重载)
        /// </summary>
        /// <param name="container">原始对象容器</param>
        /// <param name="methodName"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public object CallMethod(object container, string methodName, object[] args)
        {
            if (container == null)
            {
                return(null);
            }
            //为了提高处理效率,不考虑重载
            Type             t        = container.GetType();
            var              cacheKey = string.Concat(t.FullName, ".", methodName);
            LambdaExpression func;

            if ((func = CacheHelpers.Get <LambdaExpression>(cacheKey)) == null)
            {
                var ms = DynamicHelpers.GetMethods(t, methodName);
                if (ms.Length == 0)
                {
                    return(null);
                }
                if (ms.Length > 1)
                {
                    throw new AmbiguousMatchException(string.Concat("Ambiguous match found. name:", methodName));
                }
                var m  = ms[0];
                var pe = new List <ParameterExpression>();
            }
            //ParameterExpression expA = Expression.Parameter(typeof(string)); //参数a
            //var expCall = Expression.Call(Expression.Constant(t), m, expA); //Math.Sin(a)
            //LambdaExpression exp = Expression.Lambda(expCall, "test", new ParameterExpression[] { expA });
            //var r = exp.Compile();

            return(null);
        }
示例#2
0
        /// <summary>
        /// 动态获取索引值
        /// </summary>
        /// <param name="container">对象</param>
        /// <param name="index">索引</param>
        /// <returns>返回结果</returns>
        public object CallIndexValue(object container, object index)
        {
            if (container != null)
            {
                #region 常见类型做特殊处理
                IList list;
                if (index is int && (list = container as IList) != null)
                {
                    return(list[(int)index]);
                }
                IDictionary dic;
                if ((dic = container as IDictionary) != null)
                {
                    return(dic[index]);
                }
                if (index is int && container is string)
                {
                    return(((string)container)[(int)index]);
                }
                #endregion

                CallIndexValueDelegate d;
                Type   type = container.GetType();
                string key  = string.Concat("i.", TypeToName(type), ".", index.GetType().Name);
                if ((d = CacheHelpers.Get <CallIndexValueDelegate>(key)) == null)
                {
                    d = CreateCallIndexValueProxy(type, container, index);
                    CacheHelpers.Set(key, d);
                }
                return(d(container, index));
            }
            return(null);
        }
示例#3
0
        private CallPropertyOrFieldDelegate CreateCallPropertyOrFieldProxy(object value, string propertyName)
        {
            Type   type = value.GetType();
            string key  = string.Concat("p.", TypeToName(type), ".", propertyName);
            CallPropertyOrFieldDelegate gpf;

            if ((gpf = CacheHelpers.Get <CallPropertyOrFieldDelegate>(key)) != null)
            {
                return(gpf);
            }
            gpf = CreateCallPropertyOrFieldProxy(type, value, propertyName);
            CacheHelpers.Set(key, gpf);
            return(gpf);
        }
示例#4
0
        /// <summary>
        /// 根据方法名查找方法(缓存)
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="methodName">方法名</param>
        /// <returns></returns>
        public static MethodInfo[] GetCacheMethods(Type type, string methodName)
        {
            var cacheKey   = string.Concat(type.FullName, ".", methodName);
            var cacheValue = CacheHelpers.Get <MethodInfo[]>(cacheKey);

            if (cacheValue != null)
            {
                return(cacheValue);
            }
            var result = GetMethods(type, methodName);

            CacheHelpers.Set(cacheKey, result);
            return(result);
        }
示例#5
0
        private DynamicMethodInfo GetExcuteMethodProxy(object container, string methodName, object[] args)
        {
            Type   type = container.GetType();
            string key  = string.Concat("m.", TypeToName(type), ".", methodName);

            DynamicMethodInfo[] list;

            if ((list = CacheHelpers.Get <DynamicMethodInfo[]>(key)) == null)
            {
                list = CreateDynamicMethods(type, methodName);
                CacheHelpers.Set(key, list);
            }
            if (list != null && list.Length > 0)
            {
                var argsType = new Type[args.Length];
                for (var i = 0; i < args.Length; i++)
                {
                    if (args[i] != null)
                    {
                        argsType[i] = args[i].GetType();
                    }
                }
                var m = DynamicHelpers.GetDynamicMethod(methodName, list, argsType);
                if (m != null)
                {
                    m.IsMatchParameters = true;
                    return(m);
                }


                //可选参数
                if (argsType.Length == 1 && argsType[0] != null && argsType[0] == typeof(Dictionary <object, object>) &&
                    (list[0].Parameters.Length != 1 || !list[0].Parameters[0].ParameterType.IsSubclassOf(typeof(IDictionary))))
                {
                    m = list[0];
                    m.IsMatchParameters = false;
                    return(m);
                }
            }

            return(null);
        }
示例#6
0
 /// <summary>
 /// read all tags
 /// </summary>
 /// <returns></returns>
 public ITag[] ReadTags()
 {
     if (!string.IsNullOrEmpty(this._content))
     {
         ITag[] ts;
         if (string.IsNullOrEmpty(this._key))
         {
             return(ParseTags());
         }
         if ((ts = CacheHelpers.Get <ITag[]>(this._key)) == null)
         {
             ts = ParseTags();
             CacheHelpers.Set(this._key, ts);
         }
         return(ts);
     }
     else
     {
         return(new ITag[0]);
     }
 }
示例#7
0
        /// <summary>
        /// 异步呈现内容
        /// </summary>
        /// <param name="writer">TextWriter</param>
        public async Task RenderAsync(System.IO.TextWriter writer)
        {
            ITag[] ts;
            if (!string.IsNullOrEmpty(this._content))
            {
                if (string.IsNullOrEmpty(this._key))
                {
                    ts = await ParseTagsAsync();
                }
                else if ((ts = CacheHelpers.Get <ITag[]>(this._key)) == null)
                {
                    ts = await ParseTagsAsync();

                    CacheHelpers.Set(this._key, ts);
                }
            }
            else
            {
                ts = new ITag[0];
            }

            await RenderAsync(writer, ts);
        }
        /// <inheritdoc />
        public async Task <List <EventViewModel> > Search(string keyword, List <SearchFilter> filters, Guid?userId)
        {
            List <Guid> searchCategories = filters.Where(x => x.Key == SearchParam.Category)
                                           .Select(x => Guid.Parse(x.Value)).ToList();

            var isOnline = filters.Find(x => x.Key == SearchParam.IsOnline) != null;

            var cords = filters.Find(x => x.Key == SearchParam.Location)?.Value.Split(",").Select(double.Parse)
                        .ToArray();

            var date = filters.Find(x => x.Key == SearchParam.Date)?.Value;

            // TODO: this search is not explicit does it want to be?
            // TODO: order of the result?

            IEnumerable <Event> events;

            String searchKey = keyword + String.Concat(filters.Select(x => x.Key + x.Value.ToString()));

            events = await CacheHelpers.Get <List <Event> >(DistributedCache, searchKey, "Search");

            if (events == null)
            {
                events = ApplicationContext.Events
                         .Include(x => x.EventCategories)
                         .Include(x => x.Promos)
                         .AsSplitQuery().AsEnumerable();

                if (!string.IsNullOrEmpty(keyword))
                {
                    events = events.Where(x => x.Name.Contains(keyword !));
                }

                if (isOnline)
                {
                    events = events.Where(x => x.IsOnline);
                }

                if (searchCategories.Any())
                {
                    events = events.Where(x => x.EventCategories.Any(c => searchCategories.Contains(c.CategoryId)));
                }

                if (cords != null)
                {
                    events = events.Where(x => !x.IsOnline && EventDistance(x.Address.Lat, x.Address.Lon, cords));
                }

                if (date != null)
                {
                    var realDate = DateTime.Parse(date);
                    events = events.Where(x =>
                                          new DateTime(x.StartLocal.Year, x.StartLocal.Month, x.StartLocal.Day).Equals(new DateTime(
                                                                                                                           realDate.Year,
                                                                                                                           realDate.Month, realDate.Day)));
                }

                events = events.Take(50);

                Logger.LogInformation("Caching search");

                // cache specific search
                await CacheHelpers.Set <List <Event> >(DistributedCache, searchKey, "Search", events.ToList());
            }
            else
            {
                Logger.LogInformation("Found search in cache");
            }

            WorkQueue.QueueWork(token =>
                                AnalyticsService.CaptureSearchAsync(token, keyword, String.Join(",", filters), userId, DateTime.Now));
            if (userId != null)
            {
                WorkQueue.QueueWork(token =>
                                    RecommendationService.InfluenceAsync(token, (Guid)userId, keyword, filters, DateTime.Now));
            }

            return(events.Select(e =>
            {
                var mapped = Mapper.Map <EventViewModel>(e);
                var promoViewModel = mapped.Promos.Where(x => x.Active && x.Start < DateTime.Now && DateTime.Now < x.End).Select(promo => Mapper.Map <PromoViewModel>(promo)).FirstOrDefault();
                mapped.Promos = new List <PromoViewModel> {
                    promoViewModel
                };
                return mapped;
            }).ToList());
        }
        /// <inheritdoc />
        /// <exception cref="EventNotFoundException">Thrown if the event is not found</exception>
        public async Task <EventDetailModel> GetForPublic(Guid id, Guid?userId)
        {
            var e = await CacheHelpers.Get <Event>(DistributedCache, id.ToString(), "PublicEvent");

            if (e == null)
            {
                e = await ApplicationContext.Events
                    .Include(x => x.Promos)
                    .Include(x => x.Address)
                    .Include(x => x.EventCategories).ThenInclude(x => x.Category)
                    .Include(x => x.Images)
                    .Include(x => x.Thumbnail)
                    .Include(x => x.SocialLinks).AsSplitQuery().AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);

                if (e == null)
                {
                    Logger.LogInformation("Event: {ID} not fond", id);
                    throw new EventNotFoundException();
                }

                Logger.LogInformation("Caching event: {ID}", id);

                await CacheHelpers.Set <Event>(DistributedCache, id.ToString(), "PublicEvent", e);
            }
            else
            {
                Logger.LogInformation("Found event: {ID} in cache", id);
            }

            // queue analytics, recommendation and popularity work
            WorkQueue.QueueWork(token => AnalyticsService.CapturePageViewAsync(token, e.Id, userId, DateTime.Now));

            if (userId != null)
            {
                WorkQueue.QueueWork(token =>
                                    RecommendationService.InfluenceAsync(token, (Guid)userId, e.Id, Influence.PageView, DateTime.Now));
            }

            WorkQueue.QueueWork(token => PopularityService.PopulariseEvent(token, e.Id, DateTime.Now));

            return(new EventDetailModel
            {
                Id = e.Id,
                Address = e.Address,
                Name = e.Name,
                Description = e.Description,
                Categories = e.EventCategories.Select(c => Mapper.Map <CategoryViewModel>(c.Category)).ToList(),
                Images = e.Images.Select(i => Mapper.Map <ImageViewModel>(i)).ToList(),
                Price = e.Price,
                Thumbnail = Mapper.Map <ImageViewModel>(e.Thumbnail),
                EndLocal = e.EndLocal,
                IsOnline = e.IsOnline,
                SocialLinks = e.SocialLinks.Select(s => Mapper.Map <SocialLinkViewModel>(s)).ToList(),
                StartLocal = e.StartLocal,
                TicketsLeft = e.TicketsLeft,
                EndUTC = e.EndUTC,
                StartUTC = e.StartUTC,
                Promos = e.Promos.Where(x => x.Active && x.Start < DateTime.Now && DateTime.Now < x.End)
                         .Select(promo => Mapper.Map <PromoViewModel>(promo)).ToList(),
                Finished = e.Finished
            });
        }