public override void Parse(string inValue, FilterHelper.ColumnFilterInfo info)
        {
            if (!string.IsNullOrEmpty(inValue))
            {
                inValue = inValue.ToLower().Trim();

                if (_enumType != null)
                {
                    var equalValues = new List<object>();
                    foreach (var field in _enumType.GetFields(BindingFlags.Static | BindingFlags.Public))
                    {
                        var displayAttribute = field.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
                        var display = displayAttribute == null ? field.Name : displayAttribute.Name;
                        if (display != null)
                        {
                            if (display.ToLower().Contains(inValue))
                            {
                                field.GetValue(_enumType);
                                equalValues.Add((int)Enum.Parse(_enumType, field.Name));
                            }
                        }
                    }

                    info.EqualValue = equalValues;
                }
            }
        }
        public override void Parse(string inValue, FilterHelper.ColumnFilterInfo info)
        {
            if (string.IsNullOrEmpty(inValue)) return;
            var value = DateTimeHelper.ParseDateTimeForSearch(inValue.Trim(), new CultureInfo("vi-VN"));
            if (!value.HasValue) return;

            info.GreaterThanOrEqualValue = value.Value;
            info.LessThanValue = value.Value.AddDays(1);
        }
 public override void Parse(string inValue, FilterHelper.ColumnFilterInfo info)
 {
     DateTime value;
     if (DateTime.TryParse(inValue, out value))
     {
         info.GreaterThanOrEqualValue = value.Date;
         info.LessThanValue = value.Date.AddDays(1);
     }
 }
 public override void Parse(string inValue, FilterHelper.ColumnFilterInfo info)
 {
     try
     {
         if (toType == typeof(string))
         {
             info.ContainValue = new List<string>() { inValue.Trim() };
         }
         else
         {
             var outValue = Convert.ChangeType(inValue, toType);
             info.EqualValue = new List<object>() { outValue };
         }
     }
     catch (Exception)
     {
     }
 }
Exemple #5
0
        /// <summary>
        /// 根据条件获取模版数据集
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> List()
        {
            GridRequest request = new GridRequest(Request);
            Expression <Func <Template, bool> > predicate = FilterHelper.GetExpression <Template>(request.FilterGroup);
            var data = await Task.Run(() =>
            {
                IQueryable <Template> listTemplate = _templateContract.Templates.Where(m => m.TemplateType == (int)TemplateFlag.ProductList);
                var list = listTemplate.Where(predicate).Select(m => new
                {
                    m.Id,
                    m.TemplateName,
                    m.TemplatePath,
                    m.IsDeleted,
                    m.IsEnabled,
                    m.IsDefault,
                    m.UpdatedTime,
                    RealName = m.Operator == null ? string.Empty : m.Operator.Member.RealName,
                }).ToList();
                return(new GridData <object>(list, list.Count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
        public ActionResult GetAddMemInfo()
        {
            GridRequest req     = new GridRequest(Request);
            var         pred    = FilterHelper.GetExpression <Member>(req.FilterGroup);
            var         alldata = _memberContract.Members.Where(pred);
            var         data    = alldata.OrderByDescending(c => c.CreatedTime)
                                  .Skip(req.PageCondition.PageIndex)
                                  .Take(req.PageCondition.PageSize)
                                  .Select(c => new
            {
                c.Id,
                c.MemberName,
                c.Gender,
                c.CreatedTime,
                c.Store.StoreName,
                c.UserPhoto,
                c.MobilePhone,
                AdminName = c.Operator.Member.MemberName,
            }).ToList();
            GridData <object> grdata = new GridData <object>(data, alldata.Count(), Request);

            return(Json(grdata));
        }
        public void OnActionExecuting(ActionExecutingContext context, object filter)
        {
            if (context.ModelState.IsValid || FilterHelper.ShouldSkip(filter, context))
            {
                return;
            }

            var resultProvider  = context.HttpContext.RequestServices.GetRequiredService <IValidationResultProvider>();
            var resultLocalizer = context.HttpContext.RequestServices.GetRequiredService <IStringLocalizer <ResultCode> >();

            var results = resultProvider.Results
                          .Where(o => !o.IsValid).SelectMany(o => o.Errors).MapTo <AppResult>().ToArray();

            var validationData = new ValidationData(resultLocalizer);

            validationData.Fail(results);

            var appResult = AppResult.FailValidation(resultLocalizer, validationData, validationData.Message);

            context.Result = new BadRequestObjectResult(appResult);

            context.HttpContext.Items[nameof(AutoValidateFilterHandler)] = true;
        }
Exemple #8
0
        /// <summary>
        /// 根据条件获取模版数据集
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> List()
        {
            GridRequest request = new GridRequest(Request);
            Expression <Func <Template, bool> > predicate = FilterHelper.GetExpression <Template>(request.FilterGroup);
            int count = 0;
            var data  = await Task.Run(() =>
            {
                var list = _templateContract.Templates.Where <Template, int>(predicate, request.PageCondition, out count).Select(m => new
                {
                    m.Id,
                    m.TemplateName,
                    m.UpdatedTime,
                    m.TemplatePath,
                    m.IsDeleted,
                    m.IsEnabled,
                    m.IsDefault,
                    RealName = m.Operator == null ? string.Empty : m.Operator.Member.RealName,
                }).ToList();
                return(new GridData <object>(list, count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
Exemple #9
0
        public ActionResult Read()
        {
            GridRequest request = new GridRequest(Request);
            Expression <Func <Shop, bool> > predicate = FilterHelper.GetExpression <Shop>(request.FilterGroup);
            var page = ShopContract.Shops.ToPage(predicate,
                                                 request.PageCondition,
                                                 m => new
            {
                m.Id,
                m.Name,
                UserId   = m.User.Id,
                UserName = m.User.UserName,
                m.LinkMan,
                m.LinkManPhone,
                m.CreatedTime,
                m.AddrDetail,
                m.HCoinLimit,
                m.BusinessState,
                m.State
            });

            return(Json(page.ToGridData()));
        }
        /// <summary>
        /// 获取数据列表
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> List()
        {
            GridRequest request = new GridRequest(Request);
            Expression <Func <Product, bool> > predicate = FilterHelper.GetExpression <Product>(request.FilterGroup);
            var count      = 0;
            var OperatorId = AuthorityHelper.OperatorId.Value;
            var data       = await Task.Run(() =>
            {
                var listpons = _productOrigNumberContract.OrigNumbs.Where(w => w.IsEnabled && !w.IsDeleted && w.DesignerId.HasValue).Select(s => s.BigProdNum).ToList();

                var list = _productContract.Products.Where(x => listpons.Contains(x.BigProdNum)).DistinctQueryBy(x => x.BigProdNum).Where <Product, int>(predicate, request.PageCondition, out count).ToList().Select(m => new
                {
                    m.Id,
                    m.ProductOriginNumber.Designer.FactoryId,
                    ThumbnailPath = (m.ThumbnailPath.IsNullOrEmpty() ? m.ProductOriginNumber.ThumbnailPath : m.ThumbnailPath),
                    ProductName   = m.ProductOriginNumber?.ProductName ?? m.ProductName,
                    m.BigProdNum,
                }).ToList();
                return(new GridData <object>(list, count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
Exemple #11
0
        public async Task <JsonResult> GetFilters([FromQuery(Name = "$skip")] int skip            = 0, [FromQuery(Name = "$top")] int top = 20,
                                                  [FromQuery(Name = "$orderby")] string sortfield = "name")
        {
            var filters = FilterHelper.BuildAOTFilterFilters(this.HttpContext);
            var count   = await _dm.AOTFilterAccessor.GetAOTFiltersCount();

            var list = await _dm.AOTFilterAccessor.GetAOTFilters(filters, skip, top, sortfield);



            if (list.Count > 0)
            {
                var usersPagedData = list.Select(e => new
                {
                    id              = e.Id,
                    name            = e.Name,
                    intensityvalue  = e.IntensityValue,
                    descriptionFORM = e.Description,
                }).ToList();

                var result = new
                {
                    Count = count,
                    Items = usersPagedData
                };
                return(Json(result));
            }
            else
            {
                var result = new
                {
                    Count = 0,
                    Items = new List <AOTFilterEntity>()
                };
                return(Json(result));
            }
        }
        public async Task <JsonResult> GetMicroscopes([FromQuery(Name = "$skip")] int skip            = 0, [FromQuery(Name = "$top")] int top = 20,
                                                      [FromQuery(Name = "$orderby")] string sortfield = "name")
        {
            var filters = FilterHelper.BuildMicroscopeFilters(this.HttpContext);
            var count   = await _dm.MicroscopeAccessor.GetMicroscopesCount();

            var list = await _dm.MicroscopeAccessor.GetMicroscopes(filters, skip, top, sortfield);



            if (list.Count > 0)
            {
                var usersPagedData = list.Select(e => new
                {
                    id       = e.Id,
                    model    = e.Model,
                    type     = e.Type,
                    producer = e.Producer,
                }).ToList();

                var result = new
                {
                    Count = count,
                    Items = usersPagedData
                };
                return(Json(result));
            }
            else
            {
                var result = new
                {
                    Count = 0,
                    Items = new List <MicroscopeEntity>()
                };
                return(Json(result));
            }
        }
Exemple #13
0
        public async Task <ActionResult> CouponList()
        {
            GridRequest request      = new GridRequest(Request);
            var         rule         = request.FilterGroup.Rules.Where(x => x.Field == "PartnerId").FirstOrDefault();
            string      strPartnerId = rule.Value.ToString();
            int         partnerId    = int.Parse(strPartnerId);

            request.FilterGroup.Rules.Remove(rule);

            Expression <Func <Coupon, bool> > predicate = FilterHelper.GetExpression <Coupon>(request.FilterGroup);
            IEnumerable <Coupon> listCoupon             = _partnerContract.Partners.Where(x => x.Id == partnerId).FirstOrDefault().Coupons;
            var data = await Task.Run(() =>
            {
                var count = 0;
                var list  = listCoupon.AsQueryable().Where <Coupon, int>(predicate, request.PageCondition, out count).Select(m => new
                {
                    m.Id,
                    m.CouponName,
                    m.CouponPrice,
                    m.Quantity,
                    SendQuantity = m.CouponItems.Where(x => x.MemberId != null).Count(),
                    UsedQuantity = m.CouponItems.Where(x => x.IsUsed == true).Count(),
                    m.IsDeleted,
                    m.IsEnabled,
                    m.Sequence,
                    m.UpdatedTime,
                    m.CreatedTime,
                    m.StartDate,
                    m.EndDate,
                    m.Operator.Member.MemberName,
                    m.IsPartner,
                }).ToList();
                return(new GridData <object>(list, count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
Exemple #14
0
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> List()
        {
            GridRequest request = new GridRequest(Request);
            Expression <Func <ArticleAttribute, bool> > predicate = FilterHelper.GetExpression <ArticleAttribute>(request.FilterGroup);
            var data = await Task.Run(() =>
            {
                Func <ICollection <ArticleAttribute>, List <ArticleAttribute> > getTree = null;
                getTree = (source) =>
                {
                    var children = source.OrderBy(o => o.Sequence).ThenBy(o => o.Id);
                    List <ArticleAttribute> tree = new List <ArticleAttribute>();
                    foreach (var child in children)
                    {
                        tree.Add(child);
                        tree.AddRange(getTree(child.Children));
                    }
                    return(tree);
                };
                var parents = _ArticleAttributeContract.ArticleAttributes.Where(m => m.ParentId == null).ToList();
                var list    = getTree(parents).AsQueryable().Where(predicate).Select(m => new
                {
                    m.ParentId,
                    m.AttributeName,
                    m.Description,
                    m.Id,
                    m.IsDeleted,
                    m.IsEnabled,
                    m.Sequence,
                    m.UpdatedTime,
                    m.CreatedTime,
                    m.Operator.Member.MemberName,
                });
                return(new GridData <object>(list, list.Count(), request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
        public ActionResult DetailList()
        {
            GridRequest request = new GridRequest(Request);
            Expression <Func <EarningsDetail, bool> > predicate = FilterHelper.GetExpression <EarningsDetail>(request.FilterGroup);

            string        idstr = Request.Params["Id"];
            List <object> li    = new List <object>();
            int           cou   = 0;

            if (!string.IsNullOrEmpty(idstr))
            {
                int id = Convert.ToInt32(idstr);

                var collc = _collocationContract.Collocations.Where(c => c.IsDeleted == false && c.IsEnabled == true && c.Id == id).FirstOrDefault();
                if (collc != null && collc.EarningsDetail != null)
                {
                    cou = collc.EarningsDetail.Where(predicate.Compile()).Count();
                    li.AddRange(collc.EarningsDetail.Where(predicate.Compile()).Select(c => new
                    {
                        c.Id,
                        c.IsCloseAnAccount,
                        c.CloseAnAccountTime,
                        ConsumeDateTime = c.ConsumeOrder.CreatedTime,
                        c.ConsumeOrder.Member.MemberName,
                        c.Totalexpendamount,
                        c.EarningsType,
                        collc.Numb,
                        collc.Admini.Member.RealName,
                        c.EarningsPercent,
                        c.EarningsNotes
                    }).Skip(request.PageCondition.PageIndex).Take(request.PageCondition.PageSize).ToList());
                }
            }
            GridData <object> redat = new GridData <object>(li, cou, request.RequestInfo);

            return(Json(redat));
        }
Exemple #16
0
        public DoorPortalComponentEx.DoorSettings GetDoorSettings(ObjectGuid door, bool create)
        {
            DoorPortalComponentEx.DoorSettings settings;
            if (mDoorSettings.TryGetValue(door, out settings))
            {
                List <string> remove = new List <string>();
                foreach (string filter in settings.ActiveFilters)
                {
                    if (!FilterHelper.IsValidFilter(filter))
                    {
                        remove.Add(filter);
                    }
                }

                foreach (string invalid in remove)
                {
                    Common.DebugNotify("Removed invalid door filter: " + invalid);
                    settings.RemoveFilter(invalid);
                }

                if (remove.Count > 0)
                {
                    AddOrUpdateDoorSettings(door, settings, false);
                }

                return(settings);
            }

            if (create)
            {
                return(new DoorPortalComponentEx.DoorSettings(door));
            }
            else
            {
                return(null);
            }
        }
        public override void Parse(string inValue, FilterHelper.ColumnFilterInfo info)
        {
            if (!string.IsNullOrEmpty(inValue))
            {
                inValue = inValue.ToLower().Trim();

                /*if (_dictionary != null)
                {
                    var enumValues = _dictionary.Where(x => x.Value.ToLower().Contains(inValue)).ToList();
                    if (!enumValues.Any()) return;

                    var equalValues = enumValues.Select(value => value.Key).Cast<object>().ToList();
                    info.EqualValue = equalValues;
                }*/

                if (_enumType != null)
                {
                    var equalValues = new List<object>();
                    foreach (var field in _enumType.GetFields(BindingFlags.Static | BindingFlags.Public))
                    {
                        var displayAttribute = field.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
                        var display = displayAttribute == null ? field.Name : displayAttribute.Name;
                        if (display != null)
                        {
                            if (display.ToLower().Contains(inValue))
                            {
                                field.GetValue(_enumType);
                                equalValues.Add(Enum.Parse(_enumType, field.Name));
                            }
                        }
                    }

                    info.EqualValue = equalValues;
                }
            }
        }
        public PageData <EntityRoleOutputDto> Read()
        {
            PageRequest request = new PageRequest(Request);
            Expression <Func <EntityRole, bool> > predicate = FilterHelper.GetExpression <EntityRole>(request.FilterGroup);
            RoleManager <Role> roleManager = ServiceLocator.Instance.GetService <RoleManager <Role> >();
            var page = _securityManager.EntityRoles.ToPage(predicate,
                                                           request.PageCondition,
                                                           m => new
            {
                m.Id,
                m.RoleId,
                m.EntityId,
                m.FilterGroupJson,
                m.IsLocked,
                m.CreatedTime,
                RoleName = roleManager.Roles.First(n => n.Id == m.RoleId).Name,
                Entity   = _securityManager.EntityInfos.Where(n => n.Id == m.EntityId).Select(n => new
                {
                    n.Name,
                    n.TypeName
                }).FirstOrDefault()
            }).ToPageResult(data => data.Select(n => new EntityRoleOutputDto()
            {
                Id          = n.Id,
                RoleId      = n.RoleId,
                EntityId    = n.EntityId,
                RoleName    = n.RoleName,
                EntityName  = n.Entity.Name,
                EntityType  = n.Entity.TypeName,
                FilterGroup = n.FilterGroupJson.FromJsonString <FilterGroup>(),
                IsLocked    = n.IsLocked,
                CreatedTime = n.CreatedTime
            }).ToArray());

            return(page.ToPageData());
        }
 protected async Task <IViewModel> GetViewModelAsync(IEnumerable <TModel> model)
 {
     return(await Task.Factory.StartNew(() =>
     {
         IViewModel vm;
         List <TModel> itemsList = new List <TModel>();
         using (var mgr = GetManager())
         {
             var filterList = FilterHelper.GetArrayFilterIn(typeof(TModel), model.Cast <object>());
             foreach (var filter in filterList)
             {
                 var res = mgr.GetFiltered(filter, GetModeEnum.Partial);
                 if (res.Any())
                 {
                     itemsList.AddRange(res);
                 }
             }
         }
         if (model.Count() != itemsList.Count())
         {
             var diff =
                 model.Where(
                     p =>
                     itemsList.Cast <IKeyHandler>()
                     .FirstOrDefault(i => i.GetKey().Equals(((IKeyHandler)p).GetKey())) == null)
                 .ToList();
             if (diff.Any())
             {
                 throw new OperationException("Объекты были удалены: {0}",
                                              string.Join(",", diff.Cast <IKeyHandler>().Select(i => i.GetKey())));
             }
         }
         vm = WrappModelIntoVM(itemsList.ToArray());
         return vm;
     }));
 }
Exemple #20
0
        public async Task <ActionResult> List()
        {
            OperationResult resul   = new OperationResult(OperationResultType.Error);
            GridRequest     request = new GridRequest(Request);
            Expression <Func <SalesCampaign, bool> > predicate = FilterHelper.GetExpression <SalesCampaign>(request.FilterGroup);

            var data = await Task.Run(() =>
            {
                var lisall = _saleCampaignContract.SalesCampaigns
                             .Where(predicate)
                             .OrderByDescending(c => c.CreatedTime)
                             .ThenByDescending(c => c.Id);
                var li = lisall.Skip(request.PageCondition.PageIndex).Take(request.PageCondition.PageSize).Select(c => new
                {
                    Id                = c.Id,
                    CampaignNumber    = c.CampaignNumber,
                    CampaignName      = c.CampaignName,
                    Descript          = c.Descript,
                    CampaignStartTime = c.CampaignStartTime,
                    CampaignEndTime   = c.CampaignEndTime,
                    CreatedTime       = c.CreatedTime,
                    IsPass            = DateTime.Now.CompareTo(c.CampaignEndTime) > 0,
                    StoresIds         = c.StoresIds,
                    IsDeleted         = c.IsDeleted,
                    IsEnabled         = c.IsEnabled,
                    SalesCampaignType = c.SalesCampaignType,
                    MemberDiscount    = c.MemberDiscount,
                    NoMmebDiscount    = c.NoMmebDiscount,
                    BigProdNumCount   = c.ProductOriginNumbers.Count
                }).ToList();
                // new GridData
                return(new GridData <object>(li, lisall.Count(), request.RequestInfo));
            });

            return(Json(data));
        }
        public override void Run()
        {
            //Log.DebugFormat("{0}: Start scan {1} BC in {2} sec with pause {3} sec", clientName, barcodeCount, scanTime.TotalSeconds, pauseTime.TotalSeconds);
            var rnd = new Random();
            var sw  = new Stopwatch();

            sw.Start();
            using (var mgr = IoC.Instance.Resolve <IBaseManager <SKU> >())
            {
                for (int i = 0; i < _barcodeCount; i++)
                {
                    var itemStart = sw.Elapsed;
                    var barcode   = _barcodes[rnd.Next(_barcodes.Length - 1)];
                    //var filter = string.Format("BARCODEL.BARCODEVALUE = '{0}'", barcode);
                    var filter   = string.Format("skuid in (select barcodekey from wmsbarcode where barcode2entity = 'SKU' and barcodevalue='{0}')", barcode);
                    var attr     = FilterHelper.GetAttrEntity <SKU>(SKU.SKUIDPropertyName, SKU.ArtCodePropertyName);
                    var skuList  = mgr.GetFiltered(filter, attr).ToArray();
                    var itemTime = sw.Elapsed - itemStart;
                    //Log.DebugFormat("{0}: scan {1} by BC '{2}' - receive {3} sku per {4}", clientName, i, barcode, skuList.Length, itemTime);
                }
            }
            sw.Stop();
            //Log.DebugFormat("{0}: Stop scan. State '{1}' ({2}{3}{4})", clientName, sw.Elapsed < scanTime ? "OK" : "ERR", sw.Elapsed, sw.Elapsed < scanTime ? "<" : ">=", scanTime);
        }
        public async Task <ActionResult> List()
        {
            GridRequest request = new GridRequest(Request);
            Expression <Func <MemberHeat, bool> > predicate = FilterHelper.GetExpression <MemberHeat>(request.FilterGroup);
            var data = await Task.Run(() =>
            {
                var count = 0;
                var list  = _memberHeatContract.Entities.Where <MemberHeat, int>(predicate, request.PageCondition, out count)
                            .ToList()
                            .Select(m => new
                {
                    m.Id,
                    m.HeatName,
                    m.DayStart,
                    m.DayEnd,
                    m.IsDeleted,
                    m.IsEnabled,
                    m.IconPath,
                }).ToList();
                return(new GridData <object>(list, count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> List()
        {
            GridRequest request = new GridRequest(Request);
            Expression <Func <WorkOrderCategory, bool> > predicate = FilterHelper.GetExpression <WorkOrderCategory>(request.FilterGroup);
            var data = await Task.Run(() =>
            {
                var count = 0;

                var list = (from s in _workOrderCategoryContract.Entities.Where <WorkOrderCategory, int>(predicate, request.PageCondition, out count)
                            select new
                {
                    s.Id,
                    s.IsDeleted,
                    s.IsEnabled,
                    s.CreatedTime,
                    s.WorkOrderCategoryName,
                    s.OperatorId,
                    OperatorName = s.Operator != null && s.Operator.Member != null ? s.Operator.Member.RealName : ""
                }).ToList();
                return(new GridData <object>(list, count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
        public async Task <ActionResult> List()
        {
            GridRequest request     = new GridRequest(Request);
            string      strRealName = string.Empty;
            var         field       = request.FilterGroup.Rules.Where(x => x.Field == "RealName").FirstOrDefault();

            if (field != null)
            {
                strRealName = field.Value.ToString();
                request.FilterGroup.Rules.Remove(field);
            }
            Expression <Func <Holiday, bool> > predicate = FilterHelper.GetExpression <Holiday>(request.FilterGroup);
            var data = await Task.Run(() =>
            {
                var count = 0;
                IQueryable <Holiday> listHoliday = _holidayContract.Holidays;

                var list = listHoliday.Where <Holiday, int>(predicate, request.PageCondition, out count).Select(m => new
                {
                    m.HolidayName,
                    m.StartTime,
                    m.HolidayDays,
                    m.EndTime,
                    m.Id,
                    m.IsDeleted,
                    m.IsEnabled,
                    m.Sequence,
                    m.UpdatedTime,
                    m.CreatedTime,
                    m.Operator.Member.MemberName,
                }).ToList();
                return(new GridData <object>(list, count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
Exemple #25
0
        public ActionResult GetMoneyLog()
        {
            GridRequest request = new GridRequest(Request);

            Expression <Func <RmbCoinTransaction, bool> > predicate = FilterHelper.GetExpression <RmbCoinTransaction>(request.FilterGroup);
            var page = IdentityContract.RmbCoinTransactions.Where(t => t.User.Id == CurrentUser.Id).OrderByDescending(t => t.Id).ToPage(predicate,
                                                                                                                                        request.PageCondition,
                                                                                                                                        m => new
            {
                m.Id,
                m.StreamId,
                m.CreatedTime,
                m.Amount,
                m.Direction,
                m.Preferential,
                m.Fee,
                m.RealAmount,
                m.Type,
                m.State,
                m.Remark
            });

            return(Json(page.ToGridData(), JsonRequestBehavior.AllowGet));
        }
Exemple #26
0
        public ActionResult GetBakupLocalSadList()
        {
            var req       = new GridRequest(Request);
            var predicate = FilterHelper.GetExpression <ResultLocalSad>(req.FilterGroup);

            #region
            //var query = _BaseService.Repository.Entities.Where(predicate).OrderBy(t => t.Id).OrderBy(t => t.OrderNum);
            //List<BakupLocalSad> lstQuery = new List<BakupLocalSad>();
            //if (req.PageCondition.PageSize <= 0)
            //{
            //    lstQuery = query.ToList();
            //}
            //else
            //{
            //    lstQuery = query.Skip((req.PageCondition.PageIndex - 1) * req.PageCondition.PageSize).Take(req.PageCondition.PageSize).ToList();
            //}
            #endregion

            req.PageCondition.SortConditions.Add(new SortCondition("Id",
                                                                   System.ComponentModel.ListSortDirection.Ascending));

            var q = _BaseService.GetList <ResultLocalSadView>(predicate, req.PageCondition).ToList();
            return(GetPageResult(q, req));
        }
        public ActionResult GridData()
        {
            GridRequest request = new GridRequest(Request);

            if (request.PageCondition.SortConditions.Length == 0)
            {
                request.PageCondition.SortConditions = new[]
                {
                    new SortCondition("ClassName")
                };
            }
            Expression <Func <EntityInfo, bool> > predicate = FilterHelper.GetExpression <EntityInfo>(request.FilterGroup);
            var page = SecurityContract.EntityInfos.ToPageCache(predicate,
                                                                request.PageCondition,
                                                                m => new
            {
                m.Id,
                m.Name,
                m.ClassName,
                m.DataLogEnabled
            });

            return(Json(page.ToGridData(), JsonRequestBehavior.AllowGet));
        }
        protected override void BindGrid()
        {
            using (var cmd = new SqlCommand())
            {
                cmd.CommandText = SelectSql +
                                  @"
*
FROM Sales.FN_T_SalesOrderHeader_GetGroupByDate(@vat)
WHERE " + FilterStatusSql;

                cmd.Parameters.Add("@vat", SqlDbType.Bit).Value = GlobalVariable.VATPayerFlag;

                if (IsFiltered)
                {
                    var filter = string.Empty;


                    filter = FilterHelper.CreateFilter("OrderDate", cboxOrderDate.Text, ConvertHelper.ToDateTime(dateOrderDate1.EditValue), ConvertHelper.ToDateTime(dateOrderDate2.EditValue), RoundingFormat.d, cmd);
                    if (filter.Length > 0)
                    {
                        cmd.CommandText += " AND " + filter;
                    }

                    if (bbBranch.RecordValue != null)
                    {
                        cmd.CommandText += " AND BranchID = @BranchID";
                        cmd.Parameters.Add("@BranchID", SqlDbType.Int).Value = bbBranch.RecordValue;
                    }
                }

                cmd.CommandText += " ORDER BY OrderDate DESC, BranchID";

                ds.T_SalesOrderHeaderGroupByDate.Clear();
                ds.T_SalesOrderHeaderGroupByDate.Merge(DictionaryManager.GetDataTable(cmd));
            }
        }
Exemple #29
0
        public IActionResult Read()
        {
            PageRequest request = new PageRequest(Request);
            Expression <Func <User, bool> > predicate = FilterHelper.GetExpression <User>(request.FilterGroup);
            var page = _userManager.Users.ToPage(predicate,
                                                 request.PageCondition,
                                                 m => new
            {
                m.Id,
                m.UserName,
                m.Email,
                m.EmailConfirmed,
                m.PhoneNumber,
                m.PhoneNumberConfirmed,
                m.LockoutEnabled,
                m.LockoutEnd,
                m.AccessFailedCount,
                m.CreatedTime,
                Roles = _identityContract.UserRoles.Where(n => n.UserId == m.Id)
                        .SelectMany(n => _identityContract.Roles.Where(o => o.Id == n.RoleId).Select(o => o.Name))
            });

            return(Json(page.ToPageData()));
        }
        private void TestNullDeviceProperties(ClauseType filterType)
        {
            var device = DeviceCreatorHelper.BuildDeviceStructure(Guid.NewGuid().ToString(), true, null);

            device.DeviceProperties = null;

            var list = new List <DeviceModel> {
                device
            };

            var filters = new List <Clause>
            {
                new Clause
                {
                    ColumnName  = "DeviceID",
                    ClauseType  = filterType,
                    ClauseValue = "x"
                }
            };

            var filtered = FilterHelper.FilterDeviceList(list.AsQueryable(), filters);

            Assert.Equal(0, filtered.Count());
        }
        public ActionResult Export()
        {
            var path = Path.Combine(HttpRuntime.AppDomainAppPath, EnvironmentHelper.TemplatePath(this.RouteData));

            GridRequest request = new GridRequest(Request);
            Expression <Func <MemberDeposit, bool> > predicate = FilterHelper.GetExpression <MemberDeposit>(request.FilterGroup);

            var query = _memberdepositContract.MemberDeposits.Where(predicate);
            var list  = query.Select(m => new
            {
                OrderType = m.OrderType + "",
                m.RelatedOrderNumber,
                m.MemberId,
                m.Member.RealName,
                m.Member.MobilePhone,
                m.Quotiety,
                m.Price,
                m.Cash,
                m.Card,
                m.Coupon,
                m.Notes,
                m.Score,
                m.UpdatedTime,
                m.order_Uid,
                AdminName = m.Operator.Member.MemberName,
                m.Operator.Department.DepartmentName,
                StoreName      = m.Store.StoreName ?? string.Empty,
                DepositContext = m.DepositContext.HasValue ? m.DepositContext + "" : string.Empty
            }).ToList();

            var group = new StringTemplateGroup("all", path, typeof(TemplateLexer));
            var st    = group.GetInstanceOf("Exporter");

            st.SetAttribute("list", list);
            return(FileExcel(st, "充值记录管理"));
        }
Exemple #32
0
        /// <summary>
        /// 获取折扣列表
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> List()
        {
            GridRequest request = new GridRequest(Request);
            Expression <Func <ProductDiscount, bool> > predicate = FilterHelper.GetExpression <ProductDiscount>(request.FilterGroup);
            var data = await Task.Run(() => {
                var entitys = _productDiscountContract.ProductDiscounts.Where(predicate);
                var list    = entitys.OrderByDescending(c => c.UpdatedTime).Skip(request.PageCondition.PageIndex).Take(request.PageCondition.PageSize).Select(m => new {
                    m.Id,
                    m.DiscountName,
                    m.DiscountCode,
                    BrandCou = m.BrandCount,
                    m.RetailDiscount,
                    m.WholesaleDiscount,
                    m.PurchaseDiscount,
                    m.Sequence,
                    m.UpdatedTime,
                    m.Operator.Member.MemberName,
                }).ToList();

                return(new GridData <object>(list, list.Count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
        public override ActionResult GetList()
        {
            GridRequest req = new GridRequest(Request);
            Expression <Func <AppAccessReport, bool> > predicate = FilterHelper.GetExpression <AppAccessReport>(req.FilterGroup);

            string strStartTime = Request["StartTime"];
            string strEndTime   = Request["EndTime"];
            string appCate      = Request["appCate"];

            if (!CheckDate(strStartTime, strEndTime))
            {
                return(Json(GetErrorJson(), JsonRequestBehavior.AllowGet));
            }

            if (!string.IsNullOrEmpty(appCate))
            {
                var appId = int.Parse(appCate);
                predicate = predicate.AndAlso(a => a.AppId == appId);//实现按AppId过滤
            }

            var list = GetListPrivate(ref predicate, req.PageCondition, strStartTime, strEndTime);

            return(GetPageResult(list, req));
        }
        /// <summary>
        /// 获取数据列表
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> List()
        {
            GridRequest request = new GridRequest(Request);
            Expression <Func <Overtime, bool> > predicate = FilterHelper.GetExpression <Overtime>(request.FilterGroup);
            var data = await Task.Run(() =>
            {
                var count = 0;
                var list  = _overtimeContract.Overtimes.Where <Overtime, int>(predicate, request.PageCondition, out count).OrderByDescending(x => x.CreatedTime).Select(x => new
                {
                    x.Id,
                    x.Admin.Member.RealName,
                    StartTime = x.StartTime,
                    EndTime   = x.EndTime,
                    x.VerifyType,
                    x.OvertimeDays,
                    x.IsEnabled,
                    x.IsDeleted,
                    x.GetPoints
                });
                return(new GridData <object>(list, count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
        public async Task <ActionResult> List()
        {
            GridRequest request = new GridRequest(Request);
            Expression <Func <Designer, bool> > predicate = FilterHelper.GetExpression <Designer>(request.FilterGroup);

            var data = await Task.Run(() =>
            {
                var count = 0;
                var list  = _designerContract.SelectDesigner.Where <Designer, int>(predicate, request.PageCondition, out count).Select(m => new
                {
                    m.Id,
                    m.Factory.FactoryName,
                    m.Admin.Member.MemberName,
                    m.Admin.Member.RealName,
                    m.Factory.Brand.BrandName,
                    m.CreatedTime,
                    m.IsDeleted,
                    m.IsEnabled,
                }).ToList();
                return(new GridData <object>(list, count, request.RequestInfo));
            });

            return(Json(data, JsonRequestBehavior.AllowGet));
        }
 public TraverseHelper(IEngine engine, FilterHelper filter, Func<PathData> pathGetter)
 {
     this.engine = engine;
     this.filter = filter;
     this.pathGetter = pathGetter;
 }
 /// <summary>
 /// The function used to convert string value from DataTables to appropriate value for property or field
 /// </summary>
 public abstract void Parse(string inValue, FilterHelper.ColumnFilterInfo info);
Exemple #38
0
        /// <summary>
        /// Applies a patch (content file) to the destination
        /// </summary>
        /// <param name="destination">The destination that contains the previous version of the data</param>
        /// <param name="patch">The content file that the destination is patched with</param>
        public void Patch(string[] destination, Library.Interface.ICompression patch)
        {
            Snapshots.ISystemIO SystemIO = Utility.Utility.IsClientLinux ? (Snapshots.ISystemIO)new Snapshots.SystemIOLinux() : (Snapshots.ISystemIO)new Snapshots.SystemIOWindows();

            if (m_partialDeltas == null)
                m_partialDeltas = new Dictionary<string, XervBackup.Library.Utility.TempFile>();

            if (m_folderTimestamps == null)
                m_folderTimestamps = new Dictionary<string, DateTime>();

            for (int i = 0; i < destination.Length; i++)
                destination[i] = Utility.Utility.AppendDirSeparator(destination[i]);

            bool isUtc = patch.FileExists(UTC_TIME_MARKER);

            //Set up the filter system to avoid dealing with filtered items
            FilterHelper fh = new FilterHelper(this, destination, m_filter);

            //Delete all files that were removed
            if (patch.FileExists(DELETED_FILES))
                foreach (string s in fh.Filterlist(FilenamesFromPlatformIndependant(patch.ReadAllLines(DELETED_FILES)), false))
                {
                    if (SystemIO.FileExists(s))
                    {
                        try
                        {
                            //TODO: Perhaps read ahead in patches to prevent creation
                            long size = SystemIO.FileLength(s);

                            SystemIO.FileDelete(s);
                            if (m_stat as RestoreStatistics != null)
                            {
                                (m_stat as RestoreStatistics).FilesRestored--;
                                (m_stat as RestoreStatistics).SizeOfRestoredFiles -= size;
                                (m_stat as RestoreStatistics).FilesDeleted++;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (m_stat != null)
                                m_stat.LogError(string.Format(Strings.RSyncDir.DeleteFileError, s, ex.Message), ex);
                            Logging.Log.WriteMessage(string.Format(Strings.RSyncDir.DeleteFileError, s, ex.Message), XervBackup.Library.Logging.LogMessageType.Warning, ex);
                        }
                    }
                    else
                    {
                        Logging.Log.WriteMessage(string.Format(Strings.RSyncDir.FileToDeleteMissingError, s), XervBackup.Library.Logging.LogMessageType.Warning);
                    }
                }

            //Delete all folders that were removed
            if (patch.FileExists(DELETED_FOLDERS))
            {
                if (m_folders_to_delete == null)
                    m_folders_to_delete = new List<string>();
                List<string> deletedfolders = new List<string>(fh.Filterlist(FilenamesFromPlatformIndependant(patch.ReadAllLines(DELETED_FOLDERS)), true));
                //Make sure subfolders are deleted first
                deletedfolders.Sort();
                deletedfolders.Reverse();

                //Append to the list of folders to remove.
                //The folders are removed when the patch sequence is finalized,
                //because the deleted file list is not present until
                //the last content file has been applied.
                m_folders_to_delete.AddRange(deletedfolders);
            }

            //Add folders. This mainly applies to empty folders,
            //as non-empty folders will also be created when files are restored
            if (patch.FileExists(ADDED_FOLDERS))
            {
                List<string> addedfolders = new List<string>(fh.Filterlist(FilenamesFromPlatformIndependant(patch.ReadAllLines(ADDED_FOLDERS)), true));

                //Make sure topfolders are created first
                addedfolders.Sort();

                foreach (string s in addedfolders)
                {
                    if (!SystemIO.DirectoryExists(s))
                        try
                        {
                            SystemIO.DirectoryCreate(s);
                            if (m_stat as RestoreStatistics != null)
                                (m_stat as RestoreStatistics).FoldersRestored++;
                        }
                        catch (Exception ex)
                        {
                            if (m_stat != null)
                                m_stat.LogError(string.Format(Strings.RSyncDir.CreateFolderError, s, ex.Message), ex);
                            Logging.Log.WriteMessage(string.Format(Strings.RSyncDir.CreateFolderError, s, ex.Message), XervBackup.Library.Logging.LogMessageType.Warning, ex);
                        }
                }
            }

            if (patch.FileExists(ADDED_FOLDERS_TIMESTAMPS))
            {
                //These times are always utc
                string[] folders = FilenamesFromPlatformIndependant(patch.ReadAllLines(ADDED_FOLDERS));
                string[] timestamps = patch.ReadAllLines(ADDED_FOLDERS_TIMESTAMPS);

                for (int i = 0; i < folders.Length; i++)
                    m_folderTimestamps[RSyncDir.GetFullPathFromRelname(destination, folders[i])] = Utility.Utility.EPOCH.AddSeconds(long.Parse(timestamps[i]));
            }

            if (patch.FileExists(UPDATED_FOLDERS) && patch.FileExists(UPDATED_FOLDERS_TIMESTAMPS))
            {
                //These times are always utc
                string[] folders = FilenamesFromPlatformIndependant(patch.ReadAllLines(UPDATED_FOLDERS));
                string[] timestamps = patch.ReadAllLines(UPDATED_FOLDERS_TIMESTAMPS);
                long l;

                for (int i = 0; i < folders.Length; i++)
                    if (long.TryParse(timestamps[i], out l))
                        m_folderTimestamps[RSyncDir.GetFullPathFromRelname(destination, folders[i])] = Utility.Utility.EPOCH.AddSeconds(l);
            }

            PartialEntryRecord pe = null;
            if (patch.FileExists(INCOMPLETE_FILE))
                pe = new PartialEntryRecord(patch.ReadAllLines(INCOMPLETE_FILE));

            PartialEntryRecord fe = null;
            if (patch.FileExists(COMPLETED_FILE))
                fe = new PartialEntryRecord(patch.ReadAllLines(COMPLETED_FILE));

            int lastPg = -1;

            string contentprefix = Utility.Utility.AppendDirSeparator(CONTENT_ROOT);
            List<string> contentfiles = m_filter.FilterList(contentprefix, patch.ListFiles(contentprefix));

            string deltaprefix = Utility.Utility.AppendDirSeparator(DELTA_ROOT);
            List<string> deltafiles = m_filter.FilterList(deltaprefix, patch.ListFiles(deltaprefix));

            string symlinkprefix = Utility.Utility.AppendDirSeparator(SYMLINK_ROOT);
            List<string> symlinks = m_filter.FilterList(symlinkprefix, patch.ListFiles(symlinkprefix));

            long totalfiles = deltafiles.Count + contentfiles.Count;
            long fileindex = 0;

            //Restore new files
            foreach (string s in contentfiles)
            {
                string target = GetFullPathFromRelname(destination, s.Substring(contentprefix.Length));
                try
                {
                    if (!SystemIO.DirectoryExists(SystemIO.PathGetDirectoryName(target)))
                    {
                        Logging.Log.WriteMessage(string.Format(Strings.RSyncDir.RestoreFolderMissingError, target), XervBackup.Library.Logging.LogMessageType.Warning);
                        SystemIO.DirectoryCreate(SystemIO.PathGetDirectoryName(target));
                    }

                    //Update each 0.5%
                    int pg = (int)((fileindex / (double)totalfiles) * 200);
                    if (pg != lastPg)
                    {
                        ProgressEvent(pg / 2, target);
                        lastPg = pg;
                    }

                    using (System.IO.Stream s1 = patch.OpenRead(s))
                    {
                        PartialEntryRecord pex = null;
                        Utility.TempFile partialFile = null;

                        if (pe != null && string.Equals(pe.PlatformConvertedFilename, s))
                            pex = pe; //The file is incomplete
                        else if (fe != null && string.Equals(fe.PlatformConvertedFilename, s))
                            pex = fe; //The file has the final segment

                        if (pex != null && string.Equals(pex.PlatformConvertedFilename, s))
                        {
                            //Ensure that the partial file list is in the correct state
                            if (pex.StartOffset == 0 && m_partialDeltas.ContainsKey(s))
                                throw new Exception(string.Format(Strings.RSyncDir.InvalidPartialFileEntry, s));
                            else if (pex.StartOffset != 0 && !m_partialDeltas.ContainsKey(s))
                                throw new Exception(string.Format(Strings.RSyncDir.InvalidPartialFileEntry, s));
                            else if (pex.StartOffset == 0) //First entry, so create a temp file
                                m_partialDeltas.Add(s, new XervBackup.Library.Utility.TempFile());

                            partialFile = m_partialDeltas[s];
                        }
                        else if (m_partialDeltas.ContainsKey(s))
                            throw new Exception(string.Format(Strings.RSyncDir.FileShouldBePartialError, s));

                        long startOffset = pex == null ? 0 : pex.StartOffset;
                        using (System.IO.Stream s2 = SystemIO.FileOpenWrite(partialFile == null ? target : (string)partialFile))
                        {
                            if (s2.Length != startOffset)
                                throw new Exception(string.Format(Strings.RSyncDir.InvalidPartialFileEntry, s));

                            s2.Position = startOffset;
                            if (startOffset == 0)
                                s2.SetLength(0);

                            Utility.Utility.CopyStream(s1, s2);
                        }

                        if (pex != null && pex == fe)
                        {
                            if (SystemIO.FileExists(target))
                                SystemIO.FileDelete(target);
                            SystemIO.FileMove(partialFile, target);
                            partialFile.Dispose();
                            m_partialDeltas.Remove(s);
                        }

                        if (m_stat is RestoreStatistics && (partialFile == null || pex == fe))
                        {
                            (m_stat as RestoreStatistics).FilesRestored++;
                            (m_stat as RestoreStatistics).SizeOfRestoredFiles += SystemIO.FileLength(target);
                        }
                    }

                    if (File.Exists(target))
                    {
                        DateTime t = patch.GetLastWriteTime(s);
                        if (!isUtc)
                            t = t.ToUniversalTime();
                        try { SystemIO.FileSetLastWriteTimeUtc(target, t); }
                        catch (Exception ex)
                        {
                            if (m_stat != null)
                                m_stat.LogWarning(string.Format(Strings.RSyncDir.FailedToSetFileWriteTime, target, ex.Message), ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (m_stat != null)
                        m_stat.LogError(string.Format(Strings.RSyncDir.RestoreFileError, s, ex.Message), ex);
                    Logging.Log.WriteMessage(string.Format(Strings.RSyncDir.RestoreFileError, s, ex.Message), XervBackup.Library.Logging.LogMessageType.Error, ex);
                }
                fileindex++;
            }

            //Patch modfied files
            foreach (string s in deltafiles)
            {
                string target = GetFullPathFromRelname(destination, s.Substring(deltaprefix.Length));
                try
                {
                    //Update each 0.5%
                    int pg = (int)((fileindex / (double)totalfiles) * 200);
                    if (pg != lastPg)
                    {
                        ProgressEvent(pg / 2, target);
                        lastPg = pg;
                    }

                    if (!SystemIO.DirectoryExists(SystemIO.PathGetDirectoryName(target)))
                    {
                        Logging.Log.WriteMessage(string.Format(Strings.RSyncDir.RestoreFolderDeltaError, target), XervBackup.Library.Logging.LogMessageType.Warning);
                        SystemIO.DirectoryCreate(SystemIO.PathGetDirectoryName(target));
                    }

                    PartialEntryRecord pex = null;
                    if (pe != null && string.Equals(pe.PlatformConvertedFilename, s))
                        pex = pe; //The file is incomplete
                    else if (fe != null && string.Equals(fe.PlatformConvertedFilename, s))
                        pex = fe; //The file has the final segment

                    Utility.TempFile tempDelta = null;

                    if (pex != null && string.Equals(pex.PlatformConvertedFilename, s))
                    {
                        //Ensure that the partial file list is in the correct state
                        if (pex.StartOffset == 0 && m_partialDeltas.ContainsKey(s))
                            throw new Exception(string.Format(Strings.RSyncDir.InvalidPartialFileEntry, s));
                        else if (pex.StartOffset != 0 && !m_partialDeltas.ContainsKey(s))
                            throw new Exception(string.Format(Strings.RSyncDir.InvalidPartialFileEntry, s));
                        else if (pex.StartOffset == 0) //First entry, so create a temp file
                            m_partialDeltas.Add(s, new XervBackup.Library.Utility.TempFile());

                        //Dump the content in the temp file at the specified offset
                        using (System.IO.Stream st = SystemIO.FileOpenWrite(m_partialDeltas[s]))
                        {
                            if (st.Length != pex.StartOffset)
                                throw new Exception(string.Format(Strings.RSyncDir.InvalidPartialFileEntry, s));
                            st.Position = pex.StartOffset;
                            using (System.IO.Stream s2 = patch.OpenRead(s))
                                Utility.Utility.CopyStream(s2, st);
                        }

                        //We can't process it until it is received completely
                        if (pex != fe)
                            continue;

                        tempDelta = m_partialDeltas[s];
                        m_partialDeltas.Remove(s);
                    }
                    else if (m_partialDeltas.ContainsKey(s))
                        throw new Exception(string.Format(Strings.RSyncDir.FileShouldBePartialError, s));

                    using (Utility.TempFile tempfile = new Utility.TempFile())
                    using (tempDelta) //May be null, but the using directive does not care
                    {
                        //Use either the patch directly, or the partial temp file
                        System.IO.Stream deltaStream = tempDelta == null ? patch.OpenRead(s) : SystemIO.FileOpenRead(tempDelta);
                        using (System.IO.Stream s2 = deltaStream)
                        using (System.IO.Stream s1 = SystemIO.FileOpenRead(target))
                        using (System.IO.Stream s3 = SystemIO.FileCreate(tempfile))
                            SharpRSync.Interface.PatchFile(s1, s2, s3);

                        if (m_stat as RestoreStatistics != null)
                        {
                            (m_stat as RestoreStatistics).SizeOfRestoredFiles -= SystemIO.FileLength(target);
                            (m_stat as RestoreStatistics).SizeOfRestoredFiles += SystemIO.FileLength(tempfile);
                            (m_stat as RestoreStatistics).FilesPatched++;
                        }

                        SystemIO.FileDelete(target);

                        try { SystemIO.FileMove(tempfile, target); }
                        catch
                        {
                            //The OS sometimes reports the file as existing even after a delete
                            // this seems to be related to MS Security Essentials?
                            System.Threading.Thread.Sleep(500);
                            SystemIO.FileMove(tempfile, target);
                        }
                    }

                    if (File.Exists(target))
                    {
                        DateTime t = patch.GetLastWriteTime(s);
                        if (!isUtc)
                            t = t.ToUniversalTime();

                        try { SystemIO.FileSetLastWriteTimeUtc(target, t); }
                        catch (Exception ex)
                        {
                            if (m_stat != null)
                                m_stat.LogWarning(string.Format(Strings.RSyncDir.FailedToSetFileWriteTime, target, ex.Message), ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (m_stat != null)
                        m_stat.LogError(string.Format(Strings.RSyncDir.RestoreFileError, s, ex.Message), ex);
                    Logging.Log.WriteMessage(string.Format(Strings.RSyncDir.RestoreFileError, s, ex.Message), XervBackup.Library.Logging.LogMessageType.Error, ex);

                    try { SystemIO.FileDelete(target); }
                    catch { }
                }
                fileindex++;
            }

            //Re-create symlinks (no progress report here, should be really fast)
            foreach (string s in symlinks)
            {
                string target = GetFullPathFromRelname(destination, s.Substring(symlinkprefix.Length));
                string symlinktarget = "";
                try
                {
                    symlinktarget = FilenamesFromPlatformIndependant(new string[] { Encoding.UTF8.GetString(patch.ReadAllBytes(s)) })[0];
                    bool isDir = symlinktarget[symlinktarget.Length - 1] == Path.DirectorySeparatorChar;
                    if (isDir)
                        symlinktarget = symlinktarget.Substring(0, symlinktarget.Length - 1);

                    try
                    {
                        //In case another symlink is present, we "update" it
                        if (SystemIO.FileExists(target) && (SystemIO.GetFileAttributes(target) & FileAttributes.ReparsePoint) != 0)
                            SystemIO.FileDelete(target);
                    }
                    catch (Exception ex)
                    {
                        Logging.Log.WriteMessage(string.Format(Strings.RSyncDir.RestoreFileError, s, ex.Message), XervBackup.Library.Logging.LogMessageType.Error, ex);
                    }

                    SystemIO.CreateSymlink(target, symlinktarget, isDir);
                }
                catch (Exception ex)
                {
                    if (m_stat != null)
                        m_stat.LogError(string.Format(Strings.RSyncDir.RestoreFileError, s, ex.Message), ex);
                    Logging.Log.WriteMessage(string.Format(Strings.RSyncDir.RestoreFileError, s, ex.Message), XervBackup.Library.Logging.LogMessageType.Error, ex);

                    try { SystemIO.FileDelete(target); }
                    catch { }

                    try
                    {
                        if (!string.IsNullOrEmpty(symlinktarget))
                            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(SystemIO.FileOpenWrite(target)))
                                sw.Write(symlinktarget);
                    }
                    catch
                    {
                    }
                }
            }
        }