Exemplo n.º 1
0
        public async Task <IActionResult> PutPark(long id, Park park)
        {
            if (id != park.Id)
            {
                return(BadRequest());
            }

            _context.Entry(park).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ParkExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Exemplo n.º 2
0
        public async Task <ActionResult <UserData> > Postuser()
        {
            var token = await HttpContext.GetTokenAsync("access_token");

            var securityTokenHandler = new JwtSecurityTokenHandler();
            var decriptedToken       = securityTokenHandler.ReadJwtToken(token);
            var claims = decriptedToken.Claims;
            var sub    = claims.First(c => c.Type == "sub").Value;
            var user   = await _context.UserData.Where(x => x.TokenSub == sub).FirstOrDefaultAsync();

            Console.WriteLine("---------------------sub-----------------------");
            Console.WriteLine(sub);
            Console.WriteLine("---------------------USER FROM POST-----------------------");
            Console.WriteLine(user);
            if (user != null)
            {
                return(StatusCode(403, $"User with auth0 sub, already exists: {sub} {user}"));
            }

            user = new UserData
            {
                TokenSub = sub,
                Name     = "Not Set Yet"
            };

            _context.UserData.Add(user);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("PostUserById", new { id = user.Id }, user));
        }
Exemplo n.º 3
0
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="db"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="registTime">内部测试使用的时间</param>
        /// <returns>如果用户名已存在,返回null,否则返回注册后的用户对象</returns>
        public async static Task <LoginOrRegisterResult> RegisterAsync(ParkContext db, string username, string password, DateTime registTime)
        {
            if (await db.CarOwners.AnyAsync(p => p.Username == username))
            {
                return(new LoginOrRegisterResult()
                {
                    Type = LoginOrRegisterResultType.Existed
                });
            }
            CarOwner carOwner = new CarOwner()
            {
                RegistTime    = registTime,
                LastLoginTime = registTime,
                Username      = username,
                Password      = CreateMD5(username + password),
                Enabled       = true,
            };

            db.Add(carOwner);
            await db.SaveChangesAsync();

            return(new LoginOrRegisterResult()
            {
                CarOwner = carOwner
            });
        }
Exemplo n.º 4
0
        internal async static Task <EnterResult> EnterAsync(ParkContext db, string licensePlate, ParkArea parkArea, DateTime time)
        {
            //检查是否有空位
            bool hasEmpty = await db.ParkingSpaces.AnyAsync(p => p.ParkArea == parkArea && !p.HasCar);

            //select from parkingspace join parkarea on parkingspace.parkareaid=parkarea.id and not parkingspace.hascar
            if (!hasEmpty)
            {
                return(new EnterResult(false, "停车场已满"));
            }
            //获取汽车
            Car car = await GetCarAsync(db, licensePlate, true);

            if (car != null && !car.Enabled)//是否被禁止进入
            {
                return(new EnterResult(false, "该车辆禁止进入"));
            }
            //新增进出记录
            ParkRecord parkRecord = new ParkRecord()
            {
                Car       = car,
                EnterTime = time,
                ParkArea  = parkArea
            };

            db.ParkRecords.Add(parkRecord);
            await db.SaveChangesAsync();

            return(new EnterResult(true));;
        }
Exemplo n.º 5
0
        public static async Task <List <ParkArea> > ImportFromJsonAsync(ParkContext db, string json)
        {
            List <ParkArea> parkAreas    = JsonConvert.DeserializeObject <List <ParkArea> >(json);
            var             existedParks = db.ParkAreas.Where(p => parkAreas.Select(q => q.Name).Contains(p.Name));

            (await existedParks.ToListAsync()).ForEach(p => db.ParkAreas.Remove(p));
            foreach (var parkArea in parkAreas)
            {
                foreach (var ps in parkArea.ParkingSpaces)
                {
                    ps.ParkArea = parkArea;
                    ps.Class ??= "";
                    ps.ID = 0;
                }
                foreach (var a in parkArea.Aisles)
                {
                    a.ParkArea = parkArea;
                    a.Class ??= "";
                    a.ID = 0;
                }
                foreach (var w in parkArea.Walls)
                {
                    w.ParkArea = parkArea;
                    w.Class ??= "";
                    w.ID = 0;
                }

                db.Add(parkArea);
            }
            await db.SaveChangesAsync();

            return(parkAreas);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="db"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async static Task <LoginOrRegisterResult> Login(ParkContext db, string username, string password)
        {
            //判断参数是否为空
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                return(new LoginOrRegisterResult()
                {
                    Type = LoginOrRegisterResultType.Empty
                });
            }
            //寻找用户名与密码都匹配的用户
            CarOwner carOwner = await db.CarOwners
                                .FirstOrDefaultAsync(p => p.Username == username && p.Password == CreateMD5(password));

            if (carOwner == null)
            {
                //返回用户名或密码错误
                return(new LoginOrRegisterResult()
                {
                    Type = LoginOrRegisterResultType.Wrong
                });
            }
            carOwner.LastLoginTime   = DateTime.Now;
            db.Entry(carOwner).State = EntityState.Modified;
            //修改并保存用户信息
            await db.SaveChangesAsync();

            return(new LoginOrRegisterResult()
            {
                CarOwner = carOwner
            });
        }
Exemplo n.º 7
0
        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="db"></param>
        /// <param name="ownerID"></param>
        /// <param name="amount"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        internal async static Task <TransactionRecord> RechargeMoneyAsync(ParkContext db, int ownerID, double amount, DateTime time)
        {
            Debug.Assert(amount > 0);
            double balance = await GetBalanceAsync(db, ownerID);//余额

            TransactionRecord transactionRecord = new TransactionRecord()
            {
                Balance    = balance + amount,//重新计算余额
                CarOwnerID = ownerID,
                Time       = time,
                Type       = TransactionType.RechargeMoney,
                Value      = amount
            };

            db.TransactionRecords.Add(transactionRecord);
            await db.SaveChangesAsync();

            return(transactionRecord);
        }
Exemplo n.º 8
0
        public async Task <ActionResult <Picture> > GetUploadURL(string name)
        {
            // await _pictureRepository.setupBucket();
            string GUID      = "{Guid.NewGuid()}";
            var    signedURL = await _pictureRepository.uploadImageURL(GUID, 12);

            var picture = new Picture();

            picture.GivenName = name;
            picture.FileName  = GUID;
            picture.URL       = signedURL;
            _context.Pictures.Add(picture);
            await _context.SaveChangesAsync();

            Console.WriteLine("---------------------Picture Created-----------------------");
            Console.WriteLine(signedURL);

            return(picture);
        }
Exemplo n.º 9
0
        /// <summary>
        /// 充时长(月租续费)
        /// </summary>
        /// <param name="db"></param>
        /// <param name="owner"></param>
        /// <param name="parkArea"></param>
        /// <param name="month"></param>
        /// <returns>返回交易记录,如果余额不足,则返回null</returns>
        public async static Task <TransactionRecord> RechargeTimeAsync(ParkContext db, int ownerID, int month)
        {
            int price = int.Parse(await Config.GetAsync(db, "MonthlyPrice", "120"));

            Debug.Assert(month > 0);
            double balance = await GetBalanceAsync(db, ownerID); //用户余额

            if (balance < price * month)                         //如果余额不足,充值随便
            {
                return(null);
            }
            DateTime?time = await GetExpireTimeAsync(db, ownerID); //获取到期时间

            DateTime target;

            if (time.HasValue && time.Value > DateTime.Now)//如果到期时间在当前时间之后
            {
                //那么直接到期时间加上几个月
                target = time.Value.AddMonths(month);
            }
            else
            {
                //否则从现在开始算,加上几个月
                target = DateTime.Now.AddMonths(month);
            }
            //生成交易信息
            TransactionRecord transactionRecord = new TransactionRecord()
            {
                Balance    = balance - price * month,
                CarOwnerID = ownerID,
                Time       = DateTime.Now,
                Type       = TransactionType.RechargeTime,
                Value      = -price * month,
                ExpireTime = target
            };

            db.TransactionRecords.Add(transactionRecord);
            await db.SaveChangesAsync();

            return(transactionRecord);
        }
Exemplo n.º 10
0
 public async Task <int> SaveChanges()
 {
     return(await Db.SaveChangesAsync());
 }
        /// <summary>
        /// 生成测试数据
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async static Task GenerateTestDatasAsync(ParkContext context)
        {
            List <ParkArea> parkAreas = new List <ParkArea>();
            Random          r         = new Random();
            await Config.SetAsync(context, "MonthlyPrice", "120");//设置月租120元/月

            PriceStrategy priceStrategy = new PriceStrategy()
            {
                StrategyJson = @"{
  ""type"": ""stepHourBase"", 
  ""prices"": [
    { 
      ""upper"": 5,
      ""price"": 2
    },
    {
      ""upper"": 12,
      ""price"": 1
    },
    {
      ""upper"": -1,
      ""price"": 0.5
    }
  ]
}",
                //MonthlyPrice = 120
            };

            context.PriceStrategys.Add(priceStrategy);

            //导入停车区信息
            parkAreas = await ParkingSpaceService.ImportFromJsonAsync(context, parkAreaJson);

            foreach (var parkArea in parkAreas)
            {
                parkArea.GateTokens = GenerateToken() + ";" + GenerateToken();
                parkArea.ParkingSpaces.ForEach(p => p.SensorToken = GenerateToken());
                parkArea.PriceStrategy = priceStrategy;
                //设置停车区的大门Token、生成每个停车位的Token、设置价格策略
            }
            //}
            //ParkArea parkArea = new ParkArea()
            //{
            //    Name = "停车场" + (i + 1),
            //    PriceStrategy = priceStrategy,
            //    Length = 100,
            //    Width = 50
            //};
            //    context.ParkAreas.Add(parkArea);
            //    for (int j = 0; j < r.Next(50, 100); j++)
            //    {
            //        context.ParkingSpaces.Add(new ParkingSpace()
            //        {
            //            ParkArea = parkArea,
            //            X = r.Next(0, 50),
            //            Y = r.Next(0, 50),
            //            Width = 5,
            //            Height = 2.5,
            //            RotateAngle = r.Next(0, 90)
            //        });
            //    }
            //}
            //context.SaveChanges();
            //var a = context.ParkAreas.First().ParkingSpaces;

            //parkAreas = await context.ParkAreas.ToListAsync();
            for (int i = 0; i < 20; i++)//车主
            {
                //注册一名车主
                var owner = (await CarOwnerService.Regist(context,
                                                          "user" + r.Next(0, short.MaxValue), "1234",
                                                          DateTime.Now.AddDays(-10).AddDays(-r.NextDouble() * 5))).CarOwner;//模拟用户在5天内注册的
                await context.SaveChangesAsync();

                //模拟为车主充值5次
                await TransactionService.RechargeMoneyAsync(context, owner.ID, r.Next(20, 200),
                                                            DateTime.Now.AddDays(-7).AddDays(-r.NextDouble()));

                await TransactionService.RechargeMoneyAsync(context, owner.ID, r.Next(10, 50),
                                                            DateTime.Now.AddDays(-6).AddDays(-r.NextDouble()));

                await TransactionService.RechargeMoneyAsync(context, owner.ID, r.Next(30, 200),
                                                            DateTime.Now.AddDays(-5).AddDays(-r.NextDouble()));

                int carCount = r.Next(2, 5);
                for (int j = 0; j < carCount; j++)//车辆
                {
                    //为车主加入几辆车
                    var car = new Car()
                    {
                        LicensePlate = "浙B" + r.Next(10000, 99999),
                        CarOwner     = owner
                    };
                    context.Cars.Add(car);
                    context.SaveChanges();

                    int parkCount = r.Next(2, 10);
                    //为每辆车模拟生成几次停车记录
                    for (int k = 0; k < parkCount; k++)//进出场信息
                    {
                        DateTime enterTime = DateTime.Now.AddDays(-parkCount + k - 1 - r.NextDouble());
                        DateTime leaveTime = enterTime.AddDays(r.NextDouble());
                        var      parkArea  = parkAreas[r.Next(0, 2)];
                        //模拟用户在5天内进入过停车场,然后出了停车场
                        await ParkService.EnterAsync(context, car.LicensePlate, parkArea, enterTime);

                        var result = await ParkService.LeaveAsync(context, car.LicensePlate, parkArea, leaveTime);

                        //这里非常奇怪,部分停车记录的停车时间会变成1-01-01 8:05,明明ParkRecord里的时间都是正确的
                        //已解决,时间问题
                    }
                }
            }

            context.SaveChanges();
        }
Exemplo n.º 12
0
        //public static Func<DateTime> Now = () => DateTime.Today.AddHours(20);//模拟的当前时间
        /// <summary>
        /// 生成测试数据
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async static Task GenerateTestDatasAsync(ParkContext context, int userCount, Func <DateTime> now)
        {
            Random          r         = new Random();
            List <ParkArea> parkAreas = new List <ParkArea>();

            if (string.IsNullOrEmpty(await Config.GetAsync(context, "HasData", "")))
            {
                await Config.SetAsync(context, "HasData", "True");     //设置月租120元/月

                await Config.SetAsync(context, "MonthlyPrice", "120"); //设置月租120元/月

                PriceStrategy priceStrategy = new PriceStrategy()
                {
                    StrategyJson = @"{
  ""type"": ""stepHourBase"", 
  ""prices"": [
    { 
      ""upper"": 5,
      ""price"": 2
    },
    {
      ""upper"": 12,
      ""price"": 1
    },
    {
      ""upper"": -1,
      ""price"": 0.5
    }
  ]
}",
                    //MonthlyPrice = 120
                };
                context.PriceStrategys.Add(priceStrategy);

                //导入停车区信息
                parkAreas = await ParkingSpaceService.ImportFromJsonAsync(context, parkAreaJson);

                foreach (var parkArea in parkAreas)
                {
                    parkArea.GateTokens = GenerateToken() + ";" + GenerateToken();
                    parkArea.ParkingSpaces.ForEach(p => p.SensorToken = GenerateToken());
                    parkArea.PriceStrategy = priceStrategy;
                    //设置停车区的大门Token、生成每个停车位的Token、设置价格策略
                }
                //}
                //ParkArea parkArea = new ParkArea()
                //{
                //    Name = "停车场" + (i + 1),
                //    PriceStrategy = priceStrategy,
                //    Length = 100,
                //    Width = 50
                //};
                //    context.ParkAreas.Add(parkArea);
                //    for (int j = 0; j < r.Next(50, 100); j++)
                //    {
                //        context.ParkingSpaces.Add(new ParkingSpace()
                //        {
                //            ParkArea = parkArea,
                //            X = r.Next(0, 50),
                //            Y = r.Next(0, 50),
                //            Width = 5,
                //            Height = 2.5,
                //            RotateAngle = r.Next(0, 90)
                //        });
                //    }
                //}
                //context.SaveChanges();
                //var a = context.ParkAreas.First().ParkingSpaces;

                //parkAreas = await context.ParkAreas.ToListAsync();
            }
            else
            {
                parkAreas = await context.ParkAreas.Include(p => p.ParkingSpaces).ToListAsync();
            }
            int i   = context.CarOwners.Any() ? context.CarOwners.Max(p => p.ID) + 1 : 0;
            int max = i + userCount;

            for (; i < max; i++)//车主
            {
                //注册一名车主
                var owner = (await CarOwnerService.RegisterAsync(context,
                                                                 "user" + (i + 1).ToString(), "1234",
                                                                 now().AddDays(-10).AddDays(-r.NextDouble() * 5))).CarOwner;//模拟用户在5天内注册的
                await context.SaveChangesAsync();

                //模拟为车主充值3次
                await TransactionService.RechargeMoneyAsync(context, owner.ID, r.Next(20, 200),
                                                            now().AddDays(-7).AddDays(-r.NextDouble()));

                await TransactionService.RechargeMoneyAsync(context, owner.ID, r.Next(10, 50),
                                                            now().AddDays(-6).AddDays(-r.NextDouble()));

                await TransactionService.RechargeMoneyAsync(context, owner.ID, r.Next(30, 200),
                                                            now().AddDays(-5).AddDays(-r.NextDouble()));

                int carCount = r.Next(2, 5);
                for (int j = 0; j < carCount; j++)//车辆
                {
                    //为车主加入几辆车
                    var car = new Car()
                    {
                        LicensePlate = "浙B" + r.Next(10000, 99999),
                        CarOwner     = owner
                    };
                    context.Cars.Add(car);
                    context.SaveChanges();

                    DateTime time = owner.RegistTime.AddDays(r.NextDouble());
                    //为每辆车模拟生成几次停车记录
                    while (true)//进出场信息
                    {
                        DateTime enterTime = time.AddDays(r.NextDouble());
                        if (enterTime.Hour > 23 || enterTime.Hour < 7)//模拟夜间没有车辆进入
                        {
                            enterTime = enterTime.AddHours(8);
                        }
                        DateTime leaveTime = enterTime.AddDays(r.NextDouble());
                        if (leaveTime.Hour > 23 || leaveTime.Hour < 7)
                        {
                            leaveTime = leaveTime.AddHours(8);
                        }
                        if (leaveTime > now())
                        {
                            break;
                        }
                        time = leaveTime;
                        var parkArea = parkAreas[r.Next(0, 3)];
                        //模拟用户在5天内进入过停车场,然后出了停车场
                        if ((await ParkService.EnterAsync(context, car.LicensePlate, parkArea, enterTime)).CanEnter)
                        {
                            ParkingSpace ps = parkArea.ParkingSpaces.First(p => !p.HasCar);
                            ps.HasCar = true;                     //切换停车位状态
                            if (leaveTime > now().AddHours(-0.5)) //设置时间差,这样可以让最后有一部分车留下来
                            {
                                break;
                            }

                            var result = await ParkService.LeaveAsync(context, car.LicensePlate, parkArea, leaveTime);

                            if (result.CanLeave)
                            {
                                ps.HasCar = false;//切换停车位状态
                            }
                        }

                        //这里非常奇怪,部分停车记录的停车时间会变成1-01-01 8:05,明明ParkRecord里的时间都是正确的
                        //已解决,时间问题
                    }
                }
            }

            context.SaveChanges();
        }
Exemplo n.º 13
0
 /// <summary>
 /// 设置密码
 /// </summary>
 /// <param name="db"></param>
 /// <param name="carOwner">车主</param>
 /// <param name="password">新密码</param>
 /// <returns></returns>
 public async static Task SetPasswordAsync(ParkContext db, CarOwner carOwner, string password)
 {
     carOwner.Password        = CreateMD5(carOwner.Username + password);
     db.Entry(carOwner).State = EntityState.Modified;
     await db.SaveChangesAsync();
 }
Exemplo n.º 14
0
        internal async static Task <LeaveResult> LeaveAsync(ParkContext db, string licensePlate, ParkArea parkArea, DateTime time)
        {
            ParkRecord parkRecord = null;

            try
            {
                LeaveResult leave = new LeaveResult()
                {
                    CanLeave = true
                };
                Car car = await GetCarAsync(db, licensePlate, false);

                if (car == null)
                {
                    //找不到车,就直接放行,省得麻烦
                    return(leave);
                }
                //获取停车记录
                parkRecord = await db.ParkRecords
                             .OrderByDescending(p => p.EnterTime)
                             .FirstOrDefaultAsync(p => p.Car == car);

                if (parkRecord == null)
                {
                    //找不到记录,就直接放行,省得麻烦
                    return(leave);
                }
                leave.ParkRecord = parkRecord;
                //补全进出记录
                parkRecord.LeaveTime       = time;
                db.Entry(parkRecord).State = EntityState.Modified;
                CarOwner owner = car.CarOwner;
                //获取价格策略
                var priceStrategy = parkArea.PriceStrategy;
                if (priceStrategy == null)
                {
                    //免费停车场
                    return(leave);
                }

                switch (owner)
                {
                case CarOwner _ when owner.IsFree:
                    //免费用户
                    break;

                case CarOwner _:
                    if (await IsMonthlyCardValidAsync(db, owner.ID))
                    {
                        //月租用户,放行
                        break;
                    }
                    else
                    {
                        goto needPay;
                    }

                case null:
                    //没有注册
needPay:
                    //非会员或普通用户
                    double price = GetPrice(priceStrategy, parkRecord.EnterTime, time);
                    double balance = owner == null ? 0 : await GetBalanceAsync(db, owner.ID);

                    //计算价格
                    if (balance - price < 0)
                    {
                        //拒绝驶离,要求付费
                        leave.CanLeave  = false;
                        leave.NeedToPay = balance - price;
                        return(leave);
                    }
                    //新增扣费记录
                    TransactionRecord transaction = new TransactionRecord()
                    {
                        Time     = time,
                        Type     = TransactionType.Park,
                        Balance  = balance - price,
                        Value    = -price,
                        CarOwner = owner,
                    };
                    db.TransactionRecords.Add(transaction);
                    parkRecord.TransactionRecord = transaction;    //停车记录绑定交易记录
                    break;
                }
                return(leave);
            }
            finally
            {
                await db.SaveChangesAsync();
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// 设置停车位占用装态
 /// </summary>
 /// <param name="db"></param>
 /// <param name="parkingSpace"></param>
 /// <param name="hasCar"></param>
 /// <returns></returns>
 public static async Task SetParkingSpaceStatus(ParkContext db, ParkingSpace parkingSpace, bool hasCar)
 {
     parkingSpace.HasCar          = hasCar;
     db.Entry(parkingSpace).State = EntityState.Modified;
     await db.SaveChangesAsync();
 }