Exemple #1
0
        public string update(BusinessDto businessDto)
        {
            try
            {
                Business businessUpdate = _context.Business.Find(businessDto.Id);
                if (businessUpdate == null)
                {
                    return("1");
                }
                businessUpdate.Id          = businessDto.Id;
                businessUpdate.Name        = businessDto.Name;
                businessUpdate.Description = businessDto.Description;
                businessUpdate.Status      = businessDto.Status;
                businessUpdate.CreateDate  = businessDto.CreateDate;
                businessUpdate.CreateDate  = businessDto.CreateDate;

                _context.Business.Update(businessUpdate);
                _context.SaveChanges();
                return("");
            }
            catch (Exception)
            {
                return("1");
            }
        }
Exemple #2
0
        public ActionResult SignIn(BusinessDto input)
        {
            //string openid = GetLoginUser().OpenId;
            //if (string.IsNullOrEmpty(openid))
            //    throw new Exception("openid不存在");
            //var user = _context.Account.FirstOrDefault(_ => _.OpenId == openid);
            var user = GetLoginUser();

            if (user == null || string.IsNullOrWhiteSpace(user.AccountNo))
            {
                throw new Exception("请先完善工号等信息再签到");
            }
            var model = new Business
            {
                AccountId    = user.Id,
                From         = input.From,
                To           = input.To,
                CreateDate   = DateTime.Now,
                AMorPM       = input.AMorPM,
                BusinessType = input.BusinessType,
                SignDate     = DateTime.Now
            };

            _context.Business.Add(model);
            _context.SaveChanges();
            return(Ok(new
            {
                success = true,
                msg = "签到成功!",
            }));
        }
        public async Task <IActionResult> UpdateBusiness([FromRoute] int id, [FromBody] BusinessDto entityDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != entityDto.Id)
            {
                return(BadRequest());
            }

            var entity = await _repository.GetByIdAsync(entityDto.Id);

            if (entity == null)
            {
                return(NotFound("Business does not exist"));
            }

            _mapper.Map(entityDto, entity);

            try
            {
                _repository.Update(entity);
                await _unitOfWork.SaveAsync();
            }

            catch (Exception)
            {
                throw new Exception("An unexpected error occured. Could not update.");
            }

            return(Ok(_mapper.Map <BusinessDto>(entity)));
        }
 public async Task <int> AddBusiness(BusinessDto model)
 {
     return(await _service.AddAsync(new Business()
     {
         ProductId = model.ProductId,
         TotalPrice = model.TotalPrice,
         Number = model.Number,
         PayTypeId = model.PayTypeId
     }));
 }
        public async Task <BusinessDto> Get(int id)
        {
            var entity = await this._unitOfWork.Business.Get(id);

            if (!entity.IsVisible)
            {
                return(null);
            }
            BusinessDto businessDto = _mapper.Map <BusinessDto>(entity);

            return(businessDto);
        }
        public async Task <int> UpdateBusiness(BusinessDto model)
        {
            var business = await _service.QueryAsync(model.Id);

            business.ProductId  = model.ProductId;
            business.TotalPrice = model.TotalPrice;
            business.Number     = model.Number;
            business.PayTypeId  = model.PayTypeId;
            business.UpdateTime = DateTime.Now;

            return(await _service.EditAsync(business));
        }
Exemple #7
0
        public async Task <IActionResult> CreateBusinessAsync(BusinessDto business)
        {
            // Create the DB Model form of the business
            Business newBusiness = Mapper.Map <Business>(business);

            // Add and save the changes
            await DbContext.Businesses.AddAsync(newBusiness);

            await DbContext.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetBusinessByIdAsync), new { id = newBusiness.Id }, newBusiness));
        }
        public IActionResult Register([FromBody] BusinessDto businessDto)
        {
            Business business = _mapper.Map <Business>(businessDto);

            try
            {
                _businessService.Create(business, businessDto.Password);
                return(Ok());
            }
            catch (ValidationException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
Exemple #9
0
        private static void addBusinessList()
        {
            var loop = 1000;

            var tw = new Stopwatch();

            Console.WriteLine($"============{DateTime.Now}============");
            tw.Start();
            using (HttpClient http = new HttpClient())
            {
                var dto = new List <BusinessDto>();
                for (var i = 0; i < loop; i++)
                {
                    var item = new BusinessDto();
                    item.Name    = "金康4";
                    item.Address = "中国武汉";
                    item.Tel     = "888888";
                    item.Email   = "*****@*****.**";
                    dto.Add(item);
                }
                var json    = JsonConvert.SerializeObject(dto);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var res     = http.PostAsync($"{RestApiHost}/api/business/addlist", content).Result.Content.ReadAsStringAsync().Result;
                Console.WriteLine($"call restapi:{res}");
            }
            tw.Stop();
            Console.WriteLine(DateTime.Now + "==>use time:" + tw.ElapsedMilliseconds + "ms");

            Console.WriteLine($"============{DateTime.Now}============");
            tw.Restart();
            var channel = new Channel(GrpcApiHost, ChannelCredentials.Insecure);
            var client  = new BusinessClient(channel);
            var data    = new BusinessListCreationData();

            for (var i = 0; i < loop; i++)
            {
                var item = new BusinessCreationData();
                item.Name    = "金康4g";
                item.Address = "中国武汉";
                item.Tel     = "888888";
                item.Email   = "*****@*****.**";
                data.BusinessesCreationData.Add(item);
            }
            var result = client.AddList(data);

            Console.WriteLine($"call grpcapi:{result.Message}");
            tw.Stop();
            Console.WriteLine(DateTime.Now + "==>use time::" + tw.ElapsedMilliseconds + "ms");
        }
Exemple #10
0
        public async Task <IActionResult> UpdateBusinessAsync(BusinessDto business)
        {
            // Get the business using the supplied id
            var existingBusiness = await DbContext.Businesses.FirstOrDefaultAsync(b => b.Id == business.Id);

            if (existingBusiness == null)
            {
                return(NotFound());
            }

            // Update the DB model
            Mapper.Map(business, existingBusiness);
            DbContext.SaveChanges();

            return(Ok());
        }
        public IActionResult Add(BusinessDto dto)
        {
            var entity = new Database.Entities.Business()
            {
                Id          = Guid.NewGuid().ToString(),
                Name        = dto.Name,
                Tel         = dto.Tel,
                Address     = dto.Address,
                Email       = dto.Email,
                CreatedTime = DateTime.Now
            };

            _db.Businesses.Add(entity);
            var res = _db.SaveChanges() == 1;

            return(Ok(res ? "Success" : "Fail"));
        }
        public IActionResult GetById(int id)
        {
            if (Convert.ToInt32(User.Identity.Name) != id)
            {
                return(Unauthorized());
            }

            try
            {
                BusinessDto businessDto = _businessService.Get(id);
                return(Ok(businessDto));
            }
            catch (ValidationException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
        public async Task <ActionResult <ApiResponse> > CreateBusinessRequest(BusinessDto businessDto)
        {
            Business business = _mapper.Map <BusinessDto, Business>(businessDto);
            User     user     = await _userManager.FindByIdAsync(business.OwnerId);

            if (!_businessService.IsHasMoneyForOpenBusiness(user, business.MaxCountOfWorker))
            {
                return(new BadRequestObjectResult(new ApiResponse(400, "You need more money, for open this business.")));
            }

            if (await _businessService.CreateBusinessRequest(business))
            {
                return(new OkObjectResult(new ApiResponse(200, "Request status is pending. Please waiting")));
            }

            return(new BadRequestObjectResult(new ApiResponse(400, "Somthing wrong. Try later")));
        }
Exemple #14
0
        public string create(BusinessDto businessDto)
        {
            try
            {
                Business businessNew = mapper.Map <BusinessDto, Business>(businessDto);
                businessNew.Id         = Guid.NewGuid().ToString();
                businessNew.CreateDate = DateTime.Now;

                _context.Business.Add(businessNew);
                _context.SaveChanges();
                return("0");
            }
            catch (Exception)
            {
                return("1");
            }
        }
        public void Get()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new AutoMapperProfile());
            });
            var mapper         = config.CreateMapper();
            var repositoryMock = new Mock <IBusinessRepository>();

            IBusinessService businessService = new BusinessService(repositoryMock.Object, mapper, null, null);

            Assert.Throws <ValidationException>(() => businessService.Get(1));

            repositoryMock.Setup(x => x.Get(1)).Returns(new Business());
            BusinessDto result = businessService.Get(1);

            Assert.NotNull(result);
        }
        public IActionResult Authenticate([FromBody] BusinessDto businesDto)
        {
            Business business = _businessService.Authenticate(businesDto.Email, businesDto.Password);

            if (business == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect!" }));
            }

            string token = _jwtProvider.GetJWT(business.Id, Role.Business);

            return(Ok(new
            {
                business.Id,
                business.CompanyName,
                business.Email,
                business.Address,
                token
            }));
        }
        public IActionResult Update(int id, [FromBody] BusinessDto businessDto)
        {
            if (Convert.ToInt32(User.Identity.Name) != id)
            {
                return(Unauthorized());
            }

            Business business = _mapper.Map <Business>(businessDto);

            business.Id = id;

            try
            {
                _businessService.Update(business, businessDto.Password);
                return(Ok());
            }
            catch (ValidationException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
Exemple #18
0
        private static void addBusiness()
        {
            var tw = new Stopwatch();

            Console.WriteLine($"============{DateTime.Now}============");
            tw.Start();
            using (HttpClient http = new HttpClient())
            {
                //var json = "{\"name\":\"金康3\",\"address\":\"中国武汉\",\"tel\":\"400888999\",\"email\":\"[email protected]\"}";
                var dto = new BusinessDto();
                dto.Name    = "jk";
                dto.Address = "中国武汉";
                dto.Tel     = "888888";
                dto.Email   = "*****@*****.**";
                var json    = JsonConvert.SerializeObject(dto);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var res     = http.PostAsync($"{RestApiHost}/api/business/add", content).Result.Content.ReadAsStringAsync().Result;
                Console.WriteLine($"call restapi:{res}");
            }
            tw.Stop();
            Console.WriteLine(DateTime.Now + "==>use time:" + tw.ElapsedMilliseconds + "ms");

            Console.WriteLine($"============{DateTime.Now}============");
            tw.Restart();
            var channel = new Channel(GrpcApiHost, ChannelCredentials.Insecure);
            var client  = new BusinessClient(channel);
            var data    = new BusinessCreationData();

            data.Name    = "金康3g";
            data.Address = "中国武汉";
            data.Tel     = "888888";
            data.Email   = "*****@*****.**";
            var result = client.Add(data);

            Console.WriteLine($"call grpcapi:{result.Message}");
            tw.Stop();
            Console.WriteLine(DateTime.Now + "==>use time::" + tw.ElapsedMilliseconds + "ms");
        }
        public async Task <IActionResult> CreateBusiness([FromBody] BusinessDto entityDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var entity = _mapper.Map <Business>(entityDto);

            try
            {
                _repository.Add(entity);
                await _unitOfWork.SaveAsync();

                var createdResult = CreatedAtAction("GetBusinessById", new { id = entity.Id }, entity.Id);
                createdResult.StatusCode = 201;
                return(createdResult);
            }
            catch (Exception e)
            {
                throw new Exception("An unexpected error occured. Could not be added.", e);
            }
        }
Exemple #20
0
        public IActionResult Create([FromBody] BusinessDto value)
        {
            string result = _bsService.create(value);

            return(new ObjectResult(result));
        }
Exemple #21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddAutoMapper();

            services.AddDbContext <BookingAppContext>(options => options.UseSqlite(Configuration.GetConnectionString("BookingAppDbContext")));

            // configure strongly typed settings objects
            IConfigurationSection appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);

            // configure jwt authentication
            AppSettings appSettings = appSettingsSection.Get <AppSettings>();

            byte[] key = Encoding.ASCII.GetBytes(appSettings.Secret);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        if (context.Principal.HasClaim(c => c.Value == Role.User))
                        {
                            IUserService userService = context.HttpContext.RequestServices.GetRequiredService <IUserService>();
                            int userId   = int.Parse(context.Principal.Identity.Name);
                            UserDto user = userService.Get(userId);
                            if (user == null)
                            {
                                context.Fail("Unauthorized");
                            }
                            return(Task.CompletedTask);
                        }
                        else
                        {
                            IBusinessService businessService = context.HttpContext.RequestServices.GetRequiredService <IBusinessService>();
                            int userId           = int.Parse(context.Principal.Identity.Name);
                            BusinessDto business = businessService.Get(userId);
                            if (business == null)
                            {
                                context.Fail("Unauthorized");
                            }
                            return(Task.CompletedTask);
                        }
                    }
                };
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            //DI for app services
            services.AddScoped <IUserService, UserService>();
            services.AddSingleton <IPasswordHandler, PasswordHandler>();
            services.AddSingleton <JWTProvider>();
            services.AddScoped(typeof(IAccountManager <>), typeof(AccountManager <>));
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <AddressValidator>();
            services.AddScoped <IBusinessRepository, BusinessRepository>();
            services.AddScoped <IBusinessService, BusinessService>();
            services.AddScoped <IScheduleRepository, ScheduleRepository>();
            services.AddScoped <IScheduleService, ScheduleService>();
            services.AddScoped <ScheduleValidator>();
            services.AddScoped <IReservationRepository, ReservationRepository>();
            services.AddScoped <IReservationService, ReservationService>();
            services.AddScoped <ISearchService, SearchService>();
        }
Exemple #22
0
 public async Task <ActionResult <ApiResponse> > CreateBusinessRequest(BusinessDto businessDto)
 {
     return(await _businessPresentation.CreateBusinessRequest(businessDto));
 }