Example #1
0
        public void CheckPermission2()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Permission, Guid> perRepository = new Repository<Permission, Guid>(store);
                PermissionService service = new PermissionService(perRepository);

                IRepository<Employee, Guid> empRepository = new Repository<Employee, Guid>(store);
                IRepository<Entity, Guid> entRepository = new Repository<Entity, Guid>(store);

                //人資部門可以看見Admin
                var operations = service.GetOperationFor(empRepository.Query(s => s.Name == "Fred").First()
                    , entRepository.Query(q => q.Name == "Employees").First());

                Assert.AreEqual(1, operations.Count);
                Assert.AreEqual("View", operations.First().Comment);

                //業務部門看不見
                var operation2s = service.GetOperationFor(empRepository.Query(s => s.Name == "Kalad").First()
                   , entRepository.Query(q => q.Name == "Employees").First());

                Assert.AreEqual(0, operation2s.Count);

                //老板通常是有超多權限,但只留較上層的權限
                var operation3s = service.GetOperationFor(empRepository.Query(s => s.Name == "Allen").First()
                  , entRepository.Query(q => q.Name == "Employees").First());

                Assert.AreEqual(1, operation3s.Count);
            }
        }
Example #2
0
        public ActionResult Here(int locationId)
        {
            // Get the data
            IRepository repository = new Repository(new CheckInDatabaseContext());

            var location = repository.GetById<Location>(locationId);
            if (location == null)
            {
                return new HttpNotFoundResult();
            }

            var username = HttpContext.User.Identity.Name;

            var user = repository.Query<ApplicationUser>().SingleOrDefault(u => u.UserName == username);
            if (user == null)
            {
                return new HttpNotFoundResult();
            }

            // make a new check in
            var checkIn = new CheckIn();
            checkIn.User = user;
            checkIn.Location = location;
            checkIn.Time = DateTime.Now;
            repository.Insert(checkIn);

            // check to see if this user meets any achievements
            var allCheckins = repository.Query<CheckIn>().Where(c => c.User.Id == user.Id);
            var allAchievements = repository.Query<Achievement>();
            var allLocationIds = repository.Query<Location>().Select(l => l.Id);

            // two in one day?
            if (!allAchievements.Any(a => a.Type == AchievementType.TwoInOneDay) && allCheckins.Count(c => EntityFunctions.TruncateTime(c.Time) == DateTime.Today) > 2)
            {
                var twoInOneDay = new Achievement { Type = AchievementType.TwoInOneDay, User = user, TimeAwarded = DateTime.Now };
                repository.Insert(twoInOneDay);
            }

            // all locations?
            var hasAll = false;
            foreach (var testLocationId in allLocationIds)
            {
                hasAll = hasAll || allCheckins.Any(c => c.Location.Id == testLocationId);
            }

            if (!allAchievements.Any(a => a.Type == AchievementType.AllLocations) && hasAll)
            {
                var allLocations = new Achievement { Type = AchievementType.AllLocations, User = user, TimeAwarded = DateTime.Now };
                repository.Insert(allLocations);
            }

            // some day we'll have hundreds of achievements!

            repository.SaveChanges();

            return RedirectToAction("Index");
        }
        public void BasicCrud()
        {
            using (var trans = DataSource.BeginTransaction())
            {

                var repo = new Repository<Employee, int>(trans, EmployeeTableName);

                var emp1 = new Employee() { FirstName = "Tom", LastName = "Jones", Title = "President" };
                var echo1 = repo.Insert(emp1);

                Assert.AreNotEqual(0, echo1.EmployeeKey, "EmployeeKey was not set");
                Assert.AreEqual(emp1.FirstName, echo1.FirstName, "FirstName");
                Assert.AreEqual(emp1.LastName, echo1.LastName, "LastName");
                Assert.AreEqual(emp1.Title, echo1.Title, "Title");

                echo1.MiddleName = "G";
                repo.Update(echo1);

                var emp2 = new Employee() { FirstName = "Lisa", LastName = "Green", Title = "VP Transportation", ManagerKey = echo1.EmployeeKey };
                var echo2 = repo.Insert(emp2);
                Assert.AreNotEqual(0, echo2.EmployeeKey, "EmployeeKey was not set");
                Assert.AreEqual(emp2.FirstName, echo2.FirstName, "FirstName");
                Assert.AreEqual(emp2.LastName, echo2.LastName, "LastName");
                Assert.AreEqual(emp2.Title, echo2.Title, "Title");
                Assert.AreEqual(emp2.ManagerKey, echo2.ManagerKey, "ManagerKey");

                var list = repo.GetAll();
                Assert.IsTrue(list.Any(e => e.EmployeeKey == echo1.EmployeeKey), "Employee 1 is missing");
                Assert.IsTrue(list.Any(e => e.EmployeeKey == echo2.EmployeeKey), "Employee 2 is missing");

                var get1 = repo.Get(echo1.EmployeeKey.Value);
                Assert.AreEqual(echo1.EmployeeKey, get1.EmployeeKey);



                var whereSearch1 = repo.Query("FirstName = @FN", new { FN = "Tom" });
                Assert.IsTrue(whereSearch1.Any(x => x.EmployeeKey == echo1.EmployeeKey), "Emp1 should have been returned");
                Assert.IsTrue(whereSearch1.All(x => x.FirstName == "Tom"), "Checking for incorrect return values");

                var whereSearch2 = repo.Query(new { FirstName = "Tom" });
                Assert.IsTrue(whereSearch2.Any(x => x.EmployeeKey == echo1.EmployeeKey), "Emp1 should have been returned");
                Assert.IsTrue(whereSearch2.All(x => x.FirstName == "Tom"), "Checking for incorrect return values");


                repo.Delete(echo2.EmployeeKey.Value);
                repo.Delete(echo1.EmployeeKey.Value);

                var list2 = repo.GetAll();
                Assert.AreEqual(list.Count - 2, list2.Count);

                trans.Commit();
            }

        }
Example #4
0
        public void MyCouponJsonSerializeAndDeserialize_Test()
        {
            IRepository repo = new Repository();

            var coupons = repo.Query<CouponView>(x => x.UserID == 443);

            if (coupons != null && coupons.Count > 0)
            {
                var couponDtos = coupons.MapToList<CouponView, CouponDto>().ToList();

                var jsonSerializer = new JavaScriptSerializer();

                var json = jsonSerializer.Serialize(couponDtos);

                if (!string.IsNullOrEmpty(json))
                {
                    couponDtos = jsonSerializer.Deserialize<List<CouponDto>>(json);

                    Assert.IsInstanceOfType(couponDtos[0], typeof(CouponDto));
                }

                var myCouponDto = new MyCouponDto
                {
                    Coupons = couponDtos
                };

                json = jsonSerializer.Serialize(myCouponDto);

                Assert.IsTrue(!string.IsNullOrEmpty(json));
            }
        }
        public void Integration_LogDataContext_URF_QueryFluent_CallInfo_Include_StationCallsign_Return_StationCallsign()
        {
            List<CallInfo> callis = null;

            using (IDataContextAsync context = new ContestqsoDataContext())
            using (IUnitOfWorkAsync unitOfWorkData = new UnitOfWork(context))
            {
                bool caught = false;
                IRepositoryAsync<CallInfo> _CallinfoRepository = new Repository<CallInfo>(context, unitOfWorkData);

                try
                {
                    TestContext.WriteLine("Integration_LogDataContext_URF_QueryFluent_CallInfo_Include_StationCallsign_Return_StationCallsign");
                    //tracked
                    callis = _CallinfoRepository.Query(x => x.UserName == "default")
                        .Include(x => x.Station).Include(x => x.CallSign)
                        .Select().OrderBy(t => t.SessionName).ThenBy(t => t.CallGroup)
                        .ToList();

                }
                catch (Exception ex)
                {
                    TestContext.WriteLine(string.Format("Integration_LogDataContext_URF_QueryFluent_CallInfo_Include_StationCallsign_Return_StationCallsign exception {0}", ex.Message));
                    caught = true;
                }
                Assert.IsFalse(caught);  //exception
                Assert.IsNotNull(callis);
                Assert.IsInstanceOfType(callis, typeof(List<CallInfo> ) );
                Assert.AreEqual(3, callis.Count );
                Assert.IsNotNull(callis[0].CallSign);
                Assert.IsNotNull(callis[0].Station);

            }
        }
        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            if (FormsAuthentication.CookiesSupported != true) return;
            if (Request.Cookies[FormsAuthentication.FormsCookieName] == null) return;

            //let us take out the username now
            var formsAuthenticationTicket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
            if (formsAuthenticationTicket == null) return;

            var username = formsAuthenticationTicket.Name;
            var roles = String.Empty;

            using (IDataContextAsync context = new OIDataContext())
            using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
            {
                IRepositoryAsync<Account> accountRepository = new Repository<Account>(context, unitOfWork);
                var user =
                    accountRepository.Query(u => u.Username == username).Include(r => r.Role).Select().SingleOrDefault();

                if (user != null) roles = user.Role.RoleType;
            }

            //Let us set the Pricipal with our user specific details
            HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
                new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
        }
Example #7
0
        public void TestCreateMoreParty()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Post, Guid> postRepository = new Repository<Post, Guid>(store);
                IRepository<Employee, Guid> employeeRepository = new Repository<Employee, Guid>(store);
                IRepository<PartyHierarchy, Guid> partyHierarchyRepository = new Repository<PartyHierarchy, Guid>(store);
                Employee employee = new Employee()
                {
                    Name = "Bob",
                };

                Post post = new Post()
                {
                    Name = "總經理室副主管",
                };

                Post parentPost = postRepository.Query(q => q.Name == "總經理室主管").First();
                employeeRepository.SaveOrUpdate(employee);
                postRepository.SaveOrUpdate(post);

                PartyService partyService = new PartyService(partyHierarchyRepository);
                partyService.AddAccountability(parentPost, post);
                unitwork.SaveChanges();
                partyService.AddEmployeeToPost(post, employee);
                unitwork.SaveChanges();
            }
        }
        //
        // GET: /Achievement/
        public ActionResult Index()
        {
            // Get the data
            var repository = new Repository(new CheckInDatabaseContext());
            var username = HttpContext.User.Identity.Name;

            ViewBag.Achievements = repository.Query<Achievement>().Where(c => c.User.UserName == username).OrderByDescending(c => c.TimeAwarded).ToList();

            return this.View();
        }
Example #9
0
        public void Init()
        {
            IRepository repo = new Repository();

            var list = repo.Query<OrderItem>(x => x.OrderID == ID)
                .FindAll(x => x.IsActive && Product.Cache.Load(x.ProductGuid) != null);

            if (list.Any())
            {
                var oiBase = list.Find(x => Product.Cache.Load(x.ProductGuid).ProductType.Equals(ProductType.MembershipCore));
                if (oiBase != null)
                {
                    var mapperMemShipCore = new MapperConfiguration(cfg =>
                        cfg.CreateMap<OrderItem, OrdrItmMemShipCore>().AfterMap((s, d) => d.Init()))
                        .CreateMapper();

                    OIMembershipCore = mapperMemShipCore.Map<OrdrItmMemShipCore>(oiBase);
                }

                oiBase =
                    list.Find(x => Product.Cache.Load(x.ProductGuid).ProductType.Equals(ProductType.MembershipPremier));
                if (oiBase != null)
                {
                    var mapperMemShipPremier = new MapperConfiguration(cfg =>
                        cfg.CreateMap<OrderItem, OrdrItmMemShipPremier>().AfterMap((s, d) => d.Init()))
                        .CreateMapper();

                    OIMembershipPremier = mapperMemShipPremier.Map<OrdrItmMemShipPremier>(oiBase);
                }

                if (OIMembershipCore != null || OIMembershipPremier != null)
                {
                    UrlOrderView = "iArsenalOrderView_Membership.aspx";
                }
                else
                {
                    throw new Exception("Unable to init Order_Membership.");
                }
            }

            #region Order Status Workflow Info

            var strWorkflow = "{{ \"StatusType\": \"{0}\", \"StatusInfo\": \"{1}\" }}";

            string[] workflowInfo =
            {
                string.Format(strWorkflow, ((int) OrderStatusType.Draft), "未提交"),
                string.Format(strWorkflow, ((int) OrderStatusType.Submitted), "审核中"),
                string.Format(strWorkflow, ((int) OrderStatusType.Confirmed), "已确认")
            };

            StatusWorkflowInfo = workflowInfo;

            #endregion
        }
        public void Execute(object state)
        {
            var logInfo = new LogInfo
            {
                MethodInstance = MethodBase.GetCurrentMethod(),
                ThreadInstance = Thread.CurrentThread
            };

            try
            {
                _log.Info("Scheduler Start: (AutoUpdateMonthlyRank)", logInfo);

                IRepository repo = new Repository();

                var iDay = DateTime.Today;

                var firstBetDate = repo.Single<Bet>(1).BetTime;

                while (!(iDay.Year <= firstBetDate.Year && iDay.Month < firstBetDate.Month))
                {
                    var winner = GamblerDW.GetTopGamblerMonthly(iDay, RankType.Winner);
                    var loser = GamblerDW.GetTopGamblerMonthly(iDay, RankType.Loser);
                    var rper = GamblerDW.GetTopGamblerMonthly(iDay, RankType.RP);

                    if (winner != null && loser != null)
                    {
                        var day = iDay;
                        var rank = repo.Query<Rank>(x => x.RankYear == day.Year && x.RankMonth == day.Month).FirstOrDefault();

                        if (rank != null)
                        {
                            //update
                            rank.Init(winner, loser, rper);

                            repo.Update(rank);
                        }
                        else
                        {
                            //insert
                            var instance = new Rank { RankYear = day.Year, RankMonth = day.Month };
                            instance.Init(winner, loser, rper);

                            repo.Insert(instance);
                        }
                    }
                    iDay = iDay.AddMonths(-1);
                }

                _log.Info("Scheduler End: (AutoUpdateMonthlyRank)", logInfo);
            }
            catch (Exception ex)
            {
                _log.Warn(ex, logInfo);
            }
        }
Example #11
0
        public void TestGetAllParentEntities()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Entity, Guid> repository = new Repository<Entity, Guid>(store);

                EntityService service = new EntityService();
                ICollection<Entity> entities = service.GetAllParentEntities(repository.Query(q => q.Name == "Section").First().Id);
                Assert.AreEqual(1, entities.Count);
            }
        }
        public void InsertProducts()
        {
            using (IDataContextAsync context = new NorthwindContext())
            using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
            {
                IRepositoryAsync<Product> productRepository = new Repository<Product>(context, unitOfWork);

                var newProducts = new[]
                {
                    new Product {ProductName = "One", Discontinued = false, ObjectState = ObjectState.Added},
                    new Product {ProductName = "12345678901234567890123456789012345678901234567890", Discontinued = true, ObjectState = ObjectState.Added},
                    new Product {ProductName = "Three", Discontinued = true, ObjectState = ObjectState.Added},
                    new Product {ProductName = "Four", Discontinued = true, ObjectState = ObjectState.Added},
                    new Product {ProductName = "Five", Discontinued = true, ObjectState = ObjectState.Added}
                };

                foreach (var product in newProducts)
                {
                    try
                    {
                        productRepository.Insert(product);
                        unitOfWork.SaveChanges();
                    }
                    catch (DbEntityValidationException ex)
                    {
                        var sb = new StringBuilder();

                        foreach (var failure in ex.EntityValidationErrors)
                        {
                            sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());

                            foreach (var error in failure.ValidationErrors)
                            {
                                sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                                sb.AppendLine();
                            }
                        }

                        Debug.WriteLine(sb.ToString());
                        TestContext.WriteLine(sb.ToString());
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                        TestContext.WriteLine(ex.Message);
                    }
                }

                var insertedProduct = productRepository.Query(x => x.ProductName == "One").Select().FirstOrDefault();
                Assert.IsTrue(insertedProduct.ProductName == "One");
            }
        }
        public void ResultIsMarshalled()
        {
            using (var repo = new Repository<Model>(new RepositoryConfiguration(),
                                                    new ModelFactory<Model>(() => new Model())))
            {
                var modelResult = new Entity {Name = "A"};
                var marshalledResult = repo.Query(m => modelResult);

                Assert.That(marshalledResult.Name, Is.EqualTo(modelResult.Name), "Inner values should equal");

                Assert.That(ReferenceEquals(modelResult, marshalledResult), Is.Not.True, "Instance should be another");
            }
        }
        public void ActivityConvertTest()
        {
            IRepository<string> repository = new Repository<string>();
            ProcessDefine processDefine = new ProcessDefine(repository.Query<ProcessDef>().First(o => o.Name == "PatchVirtualMachine").Content);

            //System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            //string ajson = javaScriptSerializer.Serialize(processDefine);
            string json = AgileEAP.Core.JsonConvert.SerializeObject(processDefine, new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = true });
            ProcessDefine processDefine2 = AgileEAP.Core.JsonConvert.DeserializeObject<ProcessDefine>(json, new ActivityConvert());

            Assert.AreEqual(processDefine.Name, processDefine2.Name);
        }
Example #15
0
        public void TestAddPartyToOrganization()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Organization, Guid> organRepository = new Repository<Organization, Guid>(store);
                IRepository<Party, Guid> partyRepository = new Repository<Party, Guid>(store);

                Organization org1 = new Organization()
                {
                    Name = "總經理室"
                };

                organRepository.SaveOrUpdate(org1);

                Party party1 = partyRepository.Query(q => q.Name == "總經理室主管").First();
                Party party2 = partyRepository.Query(q => q.Name == "總經理室副主管").First();
                org1.Parties.Add(party1);
                org1.Parties.Add(party2);

                unitwork.SaveChanges();

            }
        }
        public void AutoUpdateUserInfo_Test()
        {
            IRepository repo = new Repository();

            // 7天来未更新的微信会员 或 微信昵称为空的会员
            var usersWeChat = repo.Query<UserWeChat>(x => x.LastAuthorizeDate < DateTime.Now.AddDays(-7));

            var users = repo.Query<User>(x => x.WeChatOpenID != "")
                .FindAll(x => string.IsNullOrEmpty(x.WeChatNickName) || usersWeChat.Exists(y => y.ID == x.ID));

            if (users.Count > 0 && ConfigGlobal_Arsenal.WeChatActive)
            {
                // 根据users,生成输入参数
                //{"user_list": [
                //        { "openid": "otvxTs4dckWG7imySrJd6jSi0CWE", "lang": "zh-CN"},
                //        { "openid": "otvxTs_JZ6SEiP0imdhpi50fuSZg",  "lang": "zh-CN" }
                //    ]
                //}

                var mapper = UserWeChatRequestDto.ConfigMapper().CreateMapper();

                var userList = new { user_list = mapper.Map<IEnumerable<UserWeChatRequestDto>>(users.DistinctBy(x => x.WeChatOpenID)).ToList() };
                var openIds = JsonConvert.SerializeObject(userList);

                var client = new WeChatApiClient();
                var result = client.BatchGetUserInfo(openIds);

                var json = JToken.Parse(result);
                if (!string.IsNullOrEmpty(json["user_info_list"].ToString()))
                {
                    var list = JsonConvert.DeserializeObject<List<UserWeChatResponseDto>>(json["user_info_list"].ToString());

                    Assert.IsTrue(list.Count > 0);
                }
            }
        }
        public virtual void Dispose()
        {
            //Clean the database
            using (var context = new MainContext())
            {
                var myRepo = new Repository<Address>(context);

                //Get the Address to be removed.
                MyNewAddress = myRepo.Query(s => s.AddressLine1 == MyNewAddress.AddressLine1).FirstOrDefault();

                if (myRepo.GetAll().Any())
                {
                    myRepo.Remove(MyNewAddress);
                    myRepo.Save();
                }
            }
        }
 public void Test()
 {
     var modelIsCreated = false;
     using (var repo = new Repository<Model>(() =>
                                                 {
                                                     modelIsCreated = true;
                                                     return new Model();
                                                 }))
     {
         repo.Query(model =>
                        {
                            Assert.That(model, Is.Not.Null);
                            Assert.That(modelIsCreated, Is.True);
                            return 0;
                        });
     }
 }
Example #19
0
        public void TestGetChild()
        {
            IStore store = new ThreadStaticStore();
            IDbContextFactory contextFactory = new DbContextFactory();

            using (UnitOfWork unitwork = new UnitOfWork(store, contextFactory))
            {
                IRepository<Demo, Guid> demoRepository = new Repository<Demo, Guid>(store);
                demoRepository.Include(i => i.Children); //這兩個做eager Load
                demoRepository.Include(i => i.Brothers);
                var demos = demoRepository.Query(q => q.Name == "C");

                Assert.AreEqual(1, demos.Count());
                Assert.AreEqual(1, demos.First().Children.Count());
                Assert.AreEqual(1, demos.First().Brothers.Count());
            }
        }
Example #20
0
        public static async Task UpdateRank()
        {
            using (var dataContext = new AppServiceDataContext())
            {
                var repository = new Repository(dataContext);

                var team = await repository.Query<Team>().FirstOrDefaultAsync();
                if (team != null)
                {
                    Console.WriteLine("Loaded team: {0}", team.Id);
                    var random = new Random();
                    var increment = random.Next(-5, 5);
                    team.Rank += increment;
                    await repository.SaveChangesAsync();
                    Console.WriteLine("Updated team rank to: {0}", team.Rank);
                }
            }
        }
Example #21
0
        /// <summary>
        /// 获取未发送邮件通知的待办任务列表
        /// </summary>
        /// <returns></returns>
        internal IList <TaskViewEntity> GetTaskListEMailUnSent()
        {
            //processState:2 -running 流程处于运行状态
            //activityType:4 -表示“任务”类型的节点
            //activityState: 1-ready(准备), 2-running(运行)
            //isEMailSent: 0-邮件未发送, 1-发送成功, -1-发送失败
            string sql      = @"SELECT * 
                         FROM vwWfActivityInstanceTasks 
                         WHERE ProcessState=2 
                            AND (ActivityType=4 OR WorkItemType=1)
                            AND ActivityState=1
                            AND IsEMailSent=0
							AND TaskState<>32
                        ";
            var    taskList = Repository.Query <TaskViewEntity>(sql).ToList <TaskViewEntity>();

            return(taskList);
        }
Example #22
0
        public void CheckPermission1()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Permission, Guid> perRepository = new Repository<Permission, Guid>(store);
                PermissionService service = new PermissionService(perRepository);

                IRepository<Employee, Guid> empRepository = new Repository<Employee, Guid>(store);
                IRepository<Entity,Guid> entRepository = new Repository<Entity,Guid>(store);

                var operations = service.GetOperationFor(empRepository.Query(s => s.Name == "Allen").First()
                    , entRepository.Query(q => q.Name == "Personal Information").First());

                Assert.AreEqual(1, operations.Count);
                Assert.AreEqual("Full Control", operations.First().Comment);

            }
        }
Example #23
0
        public ActionResult Index(long?domainID, int?page)
        {
            ViewData["DateTimeFormat"] = "M/d/yyyy h:mm:ss tt";

            Func <Anchor, bool> filter = anchor => true;

            if (domainID.HasValue)
            {
                var domain = Mapper.Map <Domain, DomainModel>(m_domainRepository.Get(domainID.Value));
                ViewData["Domain"] = domain;
                filter             = anchor => anchor.Owner.Equals(domain.Name, StringComparison.OrdinalIgnoreCase);
            }

            return(View(Repository.Query()
                        .Where(filter)
                        .Select(anchor => Mapper.Map <Anchor, AnchorModel>(anchor))
                        .AsPagination(page ?? 1, DefaultPageSize)));
        }
Example #24
0
        /// <summary>
        /// 面积占比
        /// </summary>
        /// <returns></returns>
        public JsonResult AreaPie(int step = 10)
        {
            DataTable dt = Repository <HouseInfo> .Query(@"SELECT MIN(cast(HouseArea as decimal)) AS minarea,MAX(cast(HouseArea as decimal)) AS maxarea  FROM HouseInfo;");

            List <DataModel> list = new List <DataModel>();

            if (dt != null)
            {
                decimal            start    = decimal.Parse(dt.Rows[0]["minarea"].ToString());
                decimal            end      = decimal.Parse(dt.Rows[0]["maxarea"].ToString());
                Step[]             steparr  = GetTitleByBlcok(start, end, step);
                Task <int>[]       tasklist = new Task <int> [step];
                Func <object, int> func     = (p_step) => {
                    Step      s      = (Step)p_step;
                    int       result = 0;
                    DataTable dtnum  = Repository <HouseInfo> .Query(string.Format(@"SELECT count(1) as num FROM HouseInfo WHERE cast(HouseArea as decimal) >{0} AND cast(HouseArea as decimal) <={1};", s.Start, s.End));

                    if (dtnum != null && dtnum.Rows.Count > 0)
                    {
                        result = int.Parse(dtnum.Rows[0]["num"].ToString());
                    }
                    else
                    {
                        result = 0;
                    }
                    return(result);
                };

                for (int i = 0; i < steparr.Length; i++)
                {
                    tasklist[i] = Task.Factory.StartNew(func, steparr[i]);
                }
                Task.WaitAll(tasklist);
                for (int i = 0; i < step; i++)
                {
                    list.Add(new DataModel()
                    {
                        Name = steparr[i].Start + "-" + steparr[i].End,
                        Num  = tasklist[i].Result,
                    });
                }
            }
            return(Json(list, JsonRequestBehavior.AllowGet));
        }
Example #25
0
        protected override List <Response> ExecuteResult()
        {
            if (string.IsNullOrWhiteSpace(ClientId))
            {
                ClientId = Guid.NewGuid().ToString();
                HttpContext.Current.Response.Cookies.Add(new HttpCookie(CookieManager.ClientId, ClientId));
            }

            return(Repository.Query(whereSpecification: new TodoByClientWhereSpec(ClientId)
                                    .And(new TodoByTypeWhereSpec(Type)),
                                    orderSpecification: new TodoByOrderSpec())
                   .Select(r => new Response
            {
                Id = r.Id.ToString(),
                Title = r.Title,
                Active = r.Active
            })
                   .ToList());
        }
Example #26
0
        public static void Clean(int dateDiff)
        {
            using (IRepository repo = new Repository())
            {
                var criteria = new Criteria
                {
                    WhereClause = $"CheckTime < '{DateTime.Today.AddDays(dateDiff).ToString("yyyy-MM-dd HH:mm:ss")}' AND IsActive = 0",
                    OrderClause = "CheckTime DESC",
                    PagingSize  = 0
                };

                var list = repo.Query <CheckList>(criteria);

                if (list != null && list.Count > 0)
                {
                    list.Delete();
                }
            }
        }
Example #27
0
        public Result <IEnumerable <Product> > FindByBusinessId(int businessId)
        {
            Result <IEnumerable <Product> > result = new Result <IEnumerable <Product> >();

            try
            {
                var returnResult = repo.Query(b => b.businessId == businessId);
                if (result.Ststus == ResultStatus.Success)
                {
                    result.Data = returnResult;
                }
            }
            catch (Exception)
            {
                result.Ststus = ResultStatus.Error;
            }

            return(result);
        }
Example #28
0
            public UpdateStatusAsync()
            {
                _options = new DbContextOptionsBuilder <SimplDbContext>()
                           .UseInMemoryDatabase(databaseName: nameof(UpdateStatusAsync))
                           .Options;

                using (var context = new SimplDbContext(_options))
                {
                    var orderRepo = new Repository <Order>(context);
                    var order     = orderRepo.Query().FirstOrDefault();
                    if (order == null)
                    {
                        var products = new List <Product> {
                            new Product()
                            {
                                Stock = 10, Price = 11000, Cost = 10000
                            },
                            new Product()
                            {
                                Stock = 20, Price = 15400, Cost = 14000
                            },
                        };
                        order = new Order()
                        {
                            OrderStatus    = OrderStatus.Pending,
                            CustomerId     = 10,
                            ShippingAmount = 10000,
                            ShippingCost   = 5000,
                            Discount       = 2000,
                            OrderItems     = new List <OrderItem> {
                                new OrderItem {
                                    Product = products[0], Quantity = 5, ProductPrice = products[0].Price
                                },
                                new OrderItem {
                                    Product = products[1], Quantity = 3, ProductPrice = products[1].Price
                                },
                            }
                        };
                        orderRepo.Add(order);
                        orderRepo.SaveChanges();
                    }
                }
            }
        /// <summary>
        /// 查询属性字段是否已经存在
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="entity"></param>
        /// <param name="trans"></param>
        /// <returns></returns>
        private int IsExistKey(IDbConnection conn, EntityAttributeEntity entity, IDbTransaction trans)
        {
            int id   = -1;
            var sql  = @"SELECT ID FROM EavEntityAttribute 
                        WHERE EntityDefID=@entityDefID 
                            AND DivCtrlKey=@divCtrlKey";
            var list = Repository.Query <EntityAttributeEntity>(conn, sql,
                                                                new {
                entityDefID = entity.EntityDefID,
                divCtrlKey  = entity.DivCtrlKey
            }, trans).ToList();;

            if (list != null && list.Count() == 1)
            {
                id = list[0].ID;
            }

            return(id);
        }
        private void textBoxSearch_TextChanged(object sender, EventArgs e)
        {
            try
            {
                using (CuaHangTienLoiDbContext dbCxt = new CuaHangTienLoiDbContext(ClassKetnoi.contextOptions))
                {
                    Repository <HoaDon>        hdRepo   = new Repository <HoaDon>(dbCxt);
                    Repository <ChiTietHoaDon> cthdRepo = new Repository <ChiTietHoaDon>(dbCxt);
                    var searchText = textBoxSearch.Text;
                    var hoadons    = hdRepo.Query(hd =>
                                                  hd.Id.ToString().Contains(searchText) ||
                                                  hd.KhachHang.SoDienThoai.Contains(searchText) ||
                                                  hd.KhachHang.TenKhachHang.Contains(searchText)
                                                  ).Select(hd => new HienThiHoaDon
                    {
                        Id           = hd.Id,
                        NgayLap      = hd.NgayLap,
                        TenKhachHang = hd.KhachHang.TenKhachHang,
                        TenNhanVien  = hd.NhanVien.TenNhanVien
                    });
                    dataGridView1.DataSource = hoadons.ToList().ToDataTable <HienThiHoaDon>();
                }

                if (dataGridView1.Rows.Count > 0 && dataGridView1.Rows != null)
                {
                    labelSearch.Text = "Đã tìm thấy";
                }
                else
                {
                    labelSearch.Text = "Không tìm thấy...";
                }

                if (string.IsNullOrWhiteSpace(textBoxSearch.Text))
                {
                    labelSearch.Text = "Tìm kiếm theo: ID hóa đơn, SĐT khách hàng, Tên khách hàng";
                }
            }
            catch (Exception ex)
            {
                connect.Close();
                MessageBox.Show(ex.Message);
            }
        }
Example #31
0
        public void Query_WithValidEntity()
        {
            var fixture = new Fixture();

            fixture.Customize(new OmitOnRecursionCustomization());

            var obj = fixture.Create <DummyEntity>();

            var context = this.CreateDummyContext();

            var sut = new Repository <DummyEntity>(context);

            sut.Insert(obj);
            sut.Commit();

            var query = sut.Query(e => e.Id == obj.Id);

            Assert.AreEqual(1, query.Count());
        }
        public void MarshallerIsCalled()
        {
            using (var mocks = new Mocks())
            {
                var marshal = mocks.Create<IMarshal>();
                var configuration = new RepositoryConfiguration
                                        {
                                            Marshal = marshal.Object
                                        };
                using (var repo = new Repository<Model>(configuration, new ModelFactory<Model>(() => new Model())))
                {
                    marshal.Setup(m => m.MarshalQueryResult("result")).Returns("marshal result");

                    var marshalledResult = repo.Query(m => "result");

                    Assert.That(marshalledResult, Is.EqualTo("marshal result"));
                }
            }
        }
Example #33
0
        public Result <IEnumerable <Business> > FindByUserName(String email)
        {
            Result <IEnumerable <Business> > result = new Result <IEnumerable <Business> >();

            try
            {
                var returnResult = repo.Query(e => e.email.Trim() == email.Trim());
                if (result.Ststus == ResultStatus.Success)
                {
                    result.Data = returnResult;
                }
            }
            catch (Exception)
            {
                result.Ststus = ResultStatus.Error;
            }

            return(result);
        }
Example #34
0
        public MQuestion DailyQuestion(User user, AlternativeManager alternativeManager)
        {
            var question = Repository.Query()
                           .Where(c => c.User.Id == user.Id && c.Question.SentDate.Date == DateTime.Now.Date && !c.Answered)
                           .Select(c => c.Question).FirstOrDefault();

            if (question != null)
            {
                return new MQuestion()
                       {
                           Course       = question.Course,
                           Description  = question.Description,
                           Alternatives = alternativeManager.GetByQuestion(question)
                       }
            }
            ;

            return(null);
        }
Example #35
0
        public void Test_Query_Pager_Viewer()
        {
            IRepository repo = new Repository();

            IPager criteria = new Criteria {
                PagingSize = 20
            };

            Assert.IsFalse(criteria.TotalCount > 0);

            var query = repo.Query <BetView>(criteria, x => x.IsWin.HasValue && x.IsWin == true, "BetTime DESC");

            Assert.IsNotNull(query);
            Assert.IsInstanceOfType(query, typeof(List <BetView>));
            Assert.IsTrue(query.Any());

            Assert.IsTrue(criteria.TotalCount > 0);
            Assert.AreEqual(criteria.PagingSize.ToString(), query.Count.ToString());
        }
Example #36
0
        /// <summary>
        /// 删除附件
        /// </summary>
        public AjaxResult Del(string menuTable, int id)
        {
            try
            {
                var fileModel = Repository <TbAttachment> .First(p => p.id == id);

                if (fileModel == null)
                {
                    return(AjaxResult.Warning("参数错误"));
                }
                //查找表单对应表名信息
                var menuTable1 = Db.Context.From <TbSysMenuTable>()
                                 .Select(TbSysMenuTable._.All)
                                 .Where(p => p.MenuCode == menuTable).First();
                if (menuTable1 != null)
                {
                    string    sql          = @"select ID from " + menuTable1.TableName + " where Enclosure like '%" + fileModel.FileID + "%'";
                    DataTable dt           = Db.Context.FromSql(sql).ToDataTable();
                    var       fileModelall = Repository <TbAttachment> .Query(p => p.FileID == fileModel.FileID && p.id != id).ToList();

                    if (fileModelall.Count() > 0)//改数据下还存在附件
                    {
                        Repository <TbAttachment> .Delete(t => t.id == id);
                    }
                    else
                    {
                        if (dt.Rows.Count > 0)
                        {
                            //修改业务表附件字段
                            string upatesql = @"update " + menuTable1.TableName + " set Enclosure='' where ID=" + Convert.ToInt32(dt.Rows[0]["ID"]) + "";
                            Db.Context.FromSql(upatesql).ExecuteNonQuery();
                        }
                        //删除附件
                        Repository <TbAttachment> .Delete(t => t.id == id);
                    }
                }
                return(AjaxResult.Success());
            }
            catch (Exception)
            {
                return(AjaxResult.Error());
            }
        }
Example #37
0
        public void Salvar(HotelDto hotelDto)
        {
            var hotel = new HotelEntity();

            hotel.Nome      = hotelDto.Nome;
            hotel.Descricao = hotelDto.Descricao;
            hotel.Avaliacao = hotelDto.Avaliacao;
            hotel.Endereco  = hotelDto.Endereco;

            hotelDto.Comodidades.ForEach((item) =>
            {
                hotel.Comodidades.Add(Repository.Query <ComodidadeEntity>().FirstOrDefault(c => c.Id == item.Id));
            });

            Transaction(() =>
            {
                Repository.Create(hotel);
            });
        }
Example #38
0
        /// <summary>
        /// 获取流程实例
        /// </summary>
        /// <param name="processGUID">流程GUID</param>
        /// <param name="version">版本</param>
        /// <returns>流程实例</returns>
        private ProcessInstanceEntity GetByVersion(string processGUID,
                                                   string version)
        {
            var sql = @"SELECT 
                            * 
                        FROM WfProcessInstance
                        WHERE ProcessGUID=@processGUID
                            AND Version=@version
                        ORDER BY ID DESC";
            var processInstanceList = Repository.Query <ProcessInstanceEntity>(sql,
                                                                               new
            {
                processGUID = processGUID,
                version     = version
            }).ToList();
            var entity = EnumHelper.GetFirst <ProcessInstanceEntity>(processInstanceList);

            return(entity);
        }
Example #39
0
        public List <RoleUserItem> GetRoleUserTree()
        {
            var strSQL = @"SELECT 
                                R.ID as RoleID,
                                R.RoleName as RoleName,
                                R.RoleCode as RoleCode,
                                U.ID as UserID,
                                U.UserName
                           FROM SysUser U
                           INNER JOIN SysRoleUser RU
                                ON U.ID = RU.UserID
                           INNER JOIN SysRole R
                                ON R.ID = RU.RoleID
                           ORDER BY R.ID,
                                U.ID";
            List <RoleUserItem> list = Repository.Query <RoleUserItem>(strSQL, null).ToList();

            return(list);
        }
Example #40
0
        public List <Tb_enum> FindKindAllInfo(string enumKind)
        {
            List <Model.Tb_enum> list = Repository
                                        .Query()
                                        .From <Model.Tb_enum>()
                                        .ToSelect()
                                        .EndSelect()
                                        .ToWhere()
                                        .And(Model.Tb_enum.Table.Enum_Kind, enumKind)
                                        .And(Model.Tb_enum.Table.Item_Flag, 0)
                                        .EndWhere()
                                        .ToOrderBy()
                                        .ASC(Model.Tb_enum.Table.Enum_Value)
                                        .EndOrderBy()
                                        .ToQuery()
                                        .ToList <Model.Tb_enum>();

            return(list);
        }
Example #41
0
        public async Task Query_ShouldFilterDocuments()
        {
            InsertBudget(new Budget {
                StartDate = new DateTime(2016, 5, 1)
            });
            InsertBudget(new Budget {
                StartDate = new DateTime(2015, 5, 1)
            });
            InsertBudget(new Budget {
                StartDate = new DateTime(2016, 6, 1)
            });
            InsertBudget(new Budget {
                StartDate = new DateTime(2015, 6, 1)
            });

            var actual = await _repository.Query(b => b.StartDate > new DateTime(2015, 7, 1));

            Assert.Equal(2, actual.Length);
        }
Example #42
0
        /// <summary>
        /// 获取数据列表
        /// </summary>
        public List <TbDepartment> GetDepartmentList(string code = "")
        {
            if (string.IsNullOrEmpty(code))
            {
                var list = Repository <TbDepartment> .GetAll();

                return(list);
            }
            else
            {
                var list = Repository <TbDepartment> .Query(p => p.CompanyCode == code);

                if (list.Count < 1)
                {
                    list = Repository <TbDepartment> .Query(p => p.ParentDepartmentCode == code || p.DepartmentCode == code);
                }
                return(list);
            }
        }
Example #43
0
        public static bool ValidateUser(string username, out Membership membership)
        {
            Contract.Requires(!string.IsNullOrEmpty(username));

            IRepository repo = new Repository();

            var query = repo.Query <Membership>(x => x.UserName == username);

            if (query.Any())
            {
                membership = query[0];
            }
            else
            {
                membership = null;
            }

            return(query.Any());
        }
Example #44
0
        /// <summary>
        /// 根据流程完成状态获取流程实例数据
        /// </summary>
        /// <param name="appName"></param>
        /// <param name="appInstanceID"></param>
        /// <param name="processGUID"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        internal IEnumerable <ProcessInstanceEntity> GetProcessInstance(String appName,
                                                                        String appInstanceID,
                                                                        String processGUID)
        {
            var sql = @"SELECT 
                            * 
                        FROM WfProcessInstance 
                        WHERE AppInstanceID=@appInstanceID 
                            AND ProcessGUID=@processGUID 
                            AND RecordStatusInvalid = 0
                        ORDER BY CreatedDateTime DESC";

            return(Repository.Query <ProcessInstanceEntity>(
                       sql,
                       new {
                appInstanceID = appInstanceID,
                processGUID = processGUID
            }));
        }
Example #45
0
        public List <HRInfoEntity> GetSearchAll(string userType, Dictionary <string, string> para)
        {
            if (userType != "普通用户")
            {
                para["iCompany"]  = para["iCompany"] == "-" ? "" : para["iCompany"];
                para["iItemName"] = para["iItemName"] == "-" ? "" : para["iItemName"];
            }
            string searchKey = para["search"];

            para.Remove("search");
            StringBuilder commandsb = new StringBuilder("from HRInfo where iIsDeleted =0 and iStatus =1 ");

            foreach (KeyValuePair <string, string> item in para)
            {
                if (!string.IsNullOrEmpty(item.Value) && item.Value != "§")
                {
                    if (item.Key.EndsWith("[d]"))
                    {
                        commandsb.Append(" and " + item.Key.Replace("[d]", "") + " between '" + (string.IsNullOrEmpty(item.Value.Split('§')[0]) ? "1900-01-01" : item.Value.Split('§')[0]) + "' and '" + (string.IsNullOrEmpty(item.Value.Split('§')[1]) ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : item.Value.Split('§')[1]) + "' ");
                    }
                    else
                    {
                        commandsb.Append(" and " + item.Key + " like '%" + item.Value + "%'");
                    }
                }
            }
            if (!string.IsNullOrEmpty(searchKey))
            {
                commandsb.Append(" and (");
                foreach (var item in Common.ConvertHelper.DicConvert(hrFullDic))
                {
                    commandsb.Append(item.Key + " like '%" + searchKey + "%' or ");
                }
                commandsb.Remove(commandsb.Length - 3, 3);
                commandsb.Append(")");
            }

            string commonSql = commandsb.ToString();
            string querySql  = "select * " + commonSql + "order by iUpdatedOn desc";

            return(Repository.Query <HRInfoEntity>(querySql).ToList());
        }
Example #46
0
        /// <summary>
        /// 获取用户不分页数据列表
        /// </summary>
        /// <param name="code">编码</param>
        /// <param name="type">1:角色 2:岗位</param>
        public static List <TbUser> GetUserGridList(UserListRequset param)
        {
            var where = new Where <TbUser>();
            var userCode = new List <string>();

            if (param.type == 1)
            {
                userCode = TbUserRoleRepository.Query(p => p.RoleCode == param.code).Select(p => p.UserCode).Distinct().ToList();
            }
            else
            {
                userCode = Repository <TbPositionUser> .Query(p => p.PositionCode == param.code).Select(p => p.UserCode).Distinct().ToList();
            }
            if (userCode.Count > 0)
            {
                where.And(d => d.UserCode.NotIn(userCode));
            }

            if (!string.IsNullOrEmpty(param.keyword))
            {
                where.And(d => d.UserCode.Like(param.keyword));
                where.Or(d => d.UserName.Like(param.keyword));
            }


            param.records = Repository <TbUser> .Count(where);

            try
            {
                var orderBy = OrderByOperater.ASC;
                if (param.sord.Equals("desc"))
                {
                    orderBy = OrderByOperater.DESC;
                }
                var orderByClip = new OrderByClip(param.sidx, orderBy);//排序字段
                return(Repository <TbUser> .Query(where, orderByClip, param.sord, param.rows, param.page).ToList());
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        /// <summary>
        /// 根据去向节点类型选择转移数据
        /// </summary>
        /// <param name="appInstanceID">应用实例ID</param>
        /// <param name="processGUID">流程GUID</param>
        /// <param name="toActivityType">到的活动节点类型</param>
        /// <returns>转移实体列表</returns>
        internal IEnumerable <TransitionInstanceEntity> GetTransitonInstance(string appInstanceID,
                                                                             String processGUID,
                                                                             ActivityTypeEnum toActivityType)
        {
            var sql = @"SELECT * FROM WfTransitionInstance 
                        WHERE AppInstanceID=@appInstanceID 
                            AND ProcessGUID=@processGUID 
                            AND ToActivityType=@toActivityType 
                        ORDER BY CreatedDateTime DESC";

            var list = Repository.Query <TransitionInstanceEntity>(sql,
                                                                   new
            {
                appInstanceID  = appInstanceID,
                processGUID    = processGUID,
                toActivityType = (int)toActivityType
            });

            return(list);
        }
Example #48
0
        /// <summary>
        /// 根据角色ID获取用户列表
        /// </summary>
        /// <param name="roleID">角色ID</param>
        /// <returns>用户列表</returns>
        internal List <User> GetUserListByRole(string roleID)
        {
            var sql  = @"SELECT 
                            C.ID AS UserID,
                            C.UserName
                        FROM SysRole A
                        INNER JOIN SysRoleUser B 
                            ON A.ID = B.RoleID
                        INNER JOIN SysUser C
                            ON B.UserID = C.ID
                        WHERE A.ID = @roleID
                        ORDER BY A.ID, C.ID                        
                        ";
            var list = Repository.Query <User>(sql, new
            {
                roleID = roleID
            }).ToList <User>();

            return(list);
        }
Example #49
0
        static void Main(string[] args)
        {
            //user.Add("");
            //x.Add();
            Repository<User> repoUser = new Repository<User>();

            repoUser.Add(new User() { Id = 1, Name = "user1" });
            repoUser.Add(new User() { Id = repoUser.GetLastIn().Id+1, Name = "user2" });
            repoUser.Add(new User() { Id = repoUser.GetLastIn().Id+1, Name = "user3" });
            repoUser.Add(new User() { Id = repoUser.GetLastIn().Id+1, Name = "user4" });

            var list = repoUser.Query(item => item.Id % 2 != 0);

            foreach (var user in list)
            {
                Console.WriteLine(user.Id + ":" + user.Name);
            }

            Console.ReadKey();
        }
        /// <summary>
        /// 获取转移数据列表
        /// </summary>
        /// <param name="appInstanceID">应用实例ID</param>
        /// <param name="processGUID">流程GUID</param>
        /// <param name="processInstanceID">流程实例ID</param>
        /// <returns>转移实例列表</returns>
        internal IEnumerable <TransitionInstanceEntity> GetTransitionInstanceList(string appInstanceID,
                                                                                  string processGUID,
                                                                                  int processInstanceID)
        {
            var sql = @"SELECT * FROM WfTransitionInstance 
                        WHERE AppInstanceID=@appInstanceID 
                            AND ProcessGUID=@processGUID 
                            AND ProcessInstanceID=@processInstanceID
                        ORDER BY CreatedDateTime DESC";

            var list = Repository.Query <TransitionInstanceEntity>(sql,
                                                                   new
            {
                appInstanceID     = appInstanceID,
                processGUID       = processGUID.ToString(),
                processInstanceID = processInstanceID
            });

            return(list);
        }
Example #51
0
        /// <summary>
        /// 判断活动实例是否是某个用户的任务
        /// </summary>
        /// <param name="activityInstanceID"></param>
        /// <param name="userID"></param>
        /// <param name="session"></param>
        /// <returns></returns>
        internal bool IsMine(int activityInstanceID, int userID)
        {
            string whereSql = @"WHERE ActivityInstanceID=@activityInstanceID
                             AND AssignedToUserID=@assignedToUserID";

            var list = Repository.Query <TaskEntity>(whereSql,
                                                     new
            {
                activityInstanceID = activityInstanceID,
                assignedToUserID   = userID
            }).ToList <TaskEntity>();

            bool isMine = false;

            if (list != null && list.Count == 1)
            {
                isMine = true;
            }
            return(isMine);
        }
Example #52
0
        public void Init()
        {
            IRepository repo = new Repository();

            var list = repo.Query<OrderItem>(x => x.OrderID == ID).FindAll(x => x.IsActive);

            if (list.Any())
            {
                WishList_Existent = list.FindAll(x => !x.ProductGuid.Equals(Guid.Empty) &&
                    Product.Cache.Load(x.ProductGuid).ProductType.Equals(ProductType.Other));

                WishList_Nonexistent = list.FindAll(x => x.ProductGuid.Equals(Guid.Empty));

                if (WishList_Existent.Count > 0 || WishList_Nonexistent.Count > 0)
                {
                    UrlOrderView = "iArsenalOrderView_ArsenalDirect.aspx";
                }
                else
                {
                    throw new Exception("Unable to init Order_Wish.");
                }
            }

            #region Order Status Workflow Info

            var strWorkflow = "{{ \"StatusType\": \"{0}\", \"StatusInfo\": \"{1}\" }}";

            string[] workflowInfo =
            {
                string.Format(strWorkflow, ((int) OrderStatusType.Draft), "未提交"),
                string.Format(strWorkflow, ((int) OrderStatusType.Submitted), "后台审核"),
                string.Format(strWorkflow, ((int) OrderStatusType.Approved), "待会员确认"),
                string.Format(strWorkflow, ((int) OrderStatusType.Confirmed), "已确认"),
                string.Format(strWorkflow, ((int) OrderStatusType.Ordered), "已下单"),
                string.Format(strWorkflow, ((int) OrderStatusType.Delivered), "已发货")
            };

            StatusWorkflowInfo = workflowInfo;

            #endregion
        }
        private static void SyncUserMemberName()
        {
            IRepository repo = new Repository();

            var users = repo.Query<User>(x => x.AcnID.HasValue).FindAll(x => !x.MemberID.HasValue);

            if (users.Count > 0)
            {
                foreach (var u in users)
                {
                    try
                    {
                        u.SyncUserByMember();
                    }
                    catch
                    {
                        // ignored
                    }
                }
            }
        }
Example #54
0
        public IList<ProductUPHInfo> GetProductUPHInfoList(DateTime fromtime, DateTime totime)
        {
            string methodName = MethodBase.GetCurrentMethod().Name;
            BaseLog.LoggingBegin(logger, methodName);
            IList<ProductUPHInfo> ret = new List<ProductUPHInfo>();
            try
            {
                using (UnitOfWork uow = new UnitOfWork())
                {
                    IRepository<ProductUPH> ecoModelRep = new Repository<ProductUPH>("UPHDBServer");//连接字符串 查询ProductUPH 表的数据
                    ret = (from q in ecoModelRep.Query()
                           where q.Date >= fromtime
                               && q.Date <= totime
                           select new ProductUPHInfo
                           {
                               ID = q.ID,
                               Date = q.Date,
                               Line = q.Line,
                               Lesson = q.Lesson,
                               TimeRange = q.TimeRange,
                               Family = q.Family,
                               ProductRatio = q.ProductRatio
                           }).ToList();
                }

                return ret;

            }
            catch (Exception e)
            {
                BaseLog.LoggingError(logger, MethodBase.GetCurrentMethod(), e);
                throw;
            }
            finally
            {
                BaseLog.LoggingEnd(logger, methodName);
            }
        
        }
        static void Main()
        {
            PopulateDb();
            NHibernateProfiler.Initialize();

            Console.WriteLine("Get Belgian customers from the DB along with their total order price");
            Console.WriteLine("--------------------");

            IRepository<Customer> customerRepository = new Repository<Customer>();
            var customers = customerRepository.Query(c => c.BillingAddress.Country == "Belgie").ToList();
            foreach (var customer in customers)
            {
                Console.WriteLine("Customer: " + customer.Name + " total order price: " + customer.Orders.Sum(o => o.Price));
            }

            Console.WriteLine("--------------------");
            Console.WriteLine();
            Console.WriteLine("Create a new order for the first Belgian customer");
            Console.WriteLine("--------------------");

            var customer1 = customers.First();
            var order = new Order
            {
                Description = "A new order",
                Price = 20,
                Customer = customer1
            };

            customer1.Orders.Add(order);
            customerRepository.Save(customer1);

            Console.WriteLine("Done");
            Console.WriteLine("--------------------");
            Console.WriteLine();
            Console.ReadLine();
        }
Example #56
0
        public IList<AlarmInfo> GetAllAlarmInfo()
        {
            string methodName = MethodBase.GetCurrentMethod().Name;
            BaseLog.LoggingBegin(logger, methodName);
            IList<AlarmInfo> ret = new List<AlarmInfo>();
            try
            {
                using (UnitOfWork uow = new UnitOfWork())
                {
                    IRepository<Alarm> ecoModelRep = new Repository<Alarm>("UPHDBServer");//连接字符串 查询ProductUPH 表的数据
                    ret = (from q in ecoModelRep.Query()
                           select new AlarmInfo
                           {
                               ID = q.ID,
                               process = q.Process,
                               Class = q.Class,
                               PdLine = q.PdLine,
                               BeginTime = q.BeginTime,
                               EndTime = q.EndTime,
                               Status = q.Status,
                               Remark = q.Remark,
                               Editor = q.Editor,
                               Cdt = q.Cdt,
                               Udt = q.Udt
                           }).ToList();
                }

                return ret;

            }
            catch (Exception e)
            {
                BaseLog.LoggingError(logger, MethodBase.GetCurrentMethod(), e);
                throw;
            }
            finally
            {
                BaseLog.LoggingEnd(logger, methodName);
            }
        }
        public override Dictionary<string, string> GetAllEntriesFromHash(string key)
        {
            key.ThrowIfNull("key");

            using (var session = new Repository().Session) {
                var result = session.Query<RavenHash>().Where(t => t.Key == key)
                        .ToDictionary(x => x.Field, x => x.Value);

                return result.Count != 0 ? result : null;
            }
        }
Example #58
0
 public void Is_Prospect()
 {
     var repository = new Repository<Boxer>(_session);
     var boxersList = repository.Query().IsProspect().ToList();
 }