Beispiel #1
0
        /// <summary>
        /// Edit department
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public IActionResult Edit(CustomersDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(Json(new
                {
                    Result = "Faild",
                    Message = GetModelStateError()
                }));
            }

            try
            {
                if (dto.Id == Guid.Empty)
                {
                    dto.Id           = Guid.NewGuid();
                    dto.CreatedTime  = DateTime.Now;
                    dto.ModifiedTime = DateTime.Now;
                }
                else if (dto.Id != Guid.Empty)
                {
                    dto.ModifiedTime = DateTime.Now;
                }
                if (_service.InsertOrUpdate(dto))
                {
                    return(Json(new { Result = "Success" }));
                }
                return(Json(new { Result = "Faild" }));
            }
            catch (Exception ex)
            {
                return(Json(new { Result = "Faild", Message = ex.Message }));
            }
        }
Beispiel #2
0
        public async Task <ActionResult <Customers> > PostCustomers(CustomersDto customersDto)
        {
            await _genericRepository.CreateAsync(customersDto); //.UpdateAsync(x => x.CustomerId == customerdto.CustomerId, customerdto); //.GetAsync(request);

            return(StatusCode(201));


            //_context.Customers.Add(customers);
            //try
            //{
            //    await _context.SaveChangesAsync();
            //}
            //catch (DbUpdateException)
            //{
            //    if (CustomersExists(customers.CustomerId))
            //    {
            //        return Conflict();
            //    }
            //    else
            //    {
            //        throw;
            //    }
            //}

            //return CreatedAtAction("GetCustomers", new { id = customers.CustomerId }, customers);
        }
        public CustomersDto SaveCustomer(CustomersDto customer)
        {
            using (var db = new GapInsuranceDBModel())
            {
                if (!db.Clients.Any(x => x.Id == customer.ClientId))
                {
                    throw new KeyNotFoundException("Client not found");
                }

                Customers dbCustomer = null;

                if (customer.Id > 0)
                {
                    dbCustomer = db.Customers.FirstOrDefault(x => x.Id == customer.Id);
                }

                if (dbCustomer == null)
                {
                    dbCustomer = new Customers();
                    db.Customers.Add(dbCustomer);
                }

                dbCustomer.FirstName = customer.FirstName;
                dbCustomer.LastName  = customer.LastName;
                dbCustomer.ClientId  = db.Clients.FirstOrDefault(x => x.Id == customer.ClientId).Id;


                db.SaveChanges();

                return(Mapper.Map <Customers, CustomersDto>(dbCustomer));
            }
        }
Beispiel #4
0
 public bool Create(CustomersDto customer)
 {
     using (var db = GetConnection())
     {
         db.Open();
         customer.LastActiveDate = DateTime.Now;
         var records = db.Execute(@"INSERT INTO [dbo].[Customer]
                                                ([FirstName]
                                                ,[LastName]
                                                ,[LastActiveDate]
                                                ,[StreetAddress]
                                                ,[City]
                                                ,[State]
                                                ,[ZipCode]
                                                ,[PhoneNumber])
                                          VALUES
                                                (@FirstName
                                                ,@LastName
                                                ,@LastActiveDate
                                                ,@StreetAddress
                                                ,@City
                                                ,@State
                                                ,@ZipCode
                                                ,@PhoneNumber)", customer);
         return(records == 1);
     }
 }
Beispiel #5
0
 /// <summary>
 /// 转换为客户实体
 /// </summary>
 /// <param name="dto">客户数据传输对象</param>
 public static Customer ToEntity(this CustomersDto dto)
 {
     if (dto == null)
     {
         return(new Customer());
     }
     return(dto.MapTo(new Customer(dto.Id)));
 }
Beispiel #6
0
        public void TestUpdateCustomer(CustomersDto customersDto)
        {
            IDatabaseConnectionHelper databaseConnectionHelper = new NorthwindDbConnectionHelper();
            CustomersRepository       customersRepository      = new CustomersRepository(databaseConnectionHelper);
            var result = customersRepository.UpdateCustomer(customersDto);

            Assert.True(result);
        }
Beispiel #7
0
        public HttpResponseMessage Put(int id, CustomersDto customer)
        {
            var repository = new CustomersRepository();
            var result     = repository.Edit(id, customer);

            return((result)
                ? Request.CreateResponse(HttpStatusCode.OK)
                : Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Could not update customer. Please try again."));
        }
        public IHttpActionResult Post([FromBody] CustomersDto customer)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var updatedCustomer = clientManager.SaveCustomer(customer);

            return(Ok(updatedCustomer));
        }
Beispiel #9
0
        public HttpResponseMessage AddCustomer(CustomersDto customer)
        {
            var repo   = new CustomersRepository();
            var result = repo.Create(customer);

            if (result)
            {
                return(Request.CreateResponse(HttpStatusCode.Created));
            }
            return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Could not create recipe, try again later..."));
        }
Beispiel #10
0
        /// <summary>
        /// Insert New Customer
        /// </summary>
        /// <param name="customersDto"></param>
        /// <returns></returns>
        public bool InsertNewCustomer(CustomersDto customersDto)
        {
            bool   result        = false;
            string sqlCommand    = @"INSERT INTO [dbo].[Customers]
                                       ([CustomerID]
                                       ,[CompanyName]
                                       ,[ContactName]
                                       ,[ContactTitle]
                                       ,[Address]
                                       ,[City]
                                       ,[Region]
                                       ,[PostalCode]
                                       ,[Country]
                                       ,[Phone]
                                       ,[Fax])
                                 VALUES
                                       (@CustomerID
                                       ,@CompanyName
                                       ,@ContactName
                                       ,@ContactTitle
                                       ,@Address
                                       ,@City
                                       ,@Region
                                       ,@PostalCode
                                       ,@Country
                                       ,@Phone
                                       ,@Fax
		                               )"        ;
            var    dynamicParams = new DynamicParameters();

            dynamicParams.Add("CustomerID", customersDto.CustomerID, DbType.String);
            dynamicParams.Add("CompanyName", customersDto.CompanyName, DbType.String);
            dynamicParams.Add("ContactName", customersDto.ContactName, DbType.String);
            dynamicParams.Add("ContactTitle", customersDto.ContactTitle, DbType.String);
            dynamicParams.Add("Address", customersDto.Address, DbType.String);
            dynamicParams.Add("City", customersDto.City, DbType.String);
            dynamicParams.Add("Region", customersDto.Region, DbType.String);
            dynamicParams.Add("PostalCode", customersDto.PostalCode, DbType.String);
            dynamicParams.Add("Country", customersDto.Country, DbType.String);
            dynamicParams.Add("Phone", customersDto.Phone, DbType.String);
            dynamicParams.Add("Fax", customersDto.Fax, DbType.String);
            var dbConnection = this.DatabaseConnection.Create();

            using (TransactionScope scope = new TransactionScope())
            {
                using (var conn = dbConnection)
                {
                    result = conn.Execute(sqlCommand, dynamicParams) > 0;
                }
                scope.Complete();
            }
            return(result);
        }
Beispiel #11
0
        public void createCustomer()
        {
            var cman = new ClientManager();

            var customer = new CustomersDto();

            customer.FirstName = "Rafael";
            customer.LastName  = "Mercado";
            customer.ClientId  = 1001;

            cman.SaveCustomer(customer);
        }
Beispiel #12
0
        public HttpResponseMessage UpdateCustomer(int customerId, CustomersDto customer)
        {
            var repository   = new CustomersRepository();
            var StatusResult = repository.UpdateCustomerStatus(customer.Status, customerId);

            if (StatusResult)
            {
                return(Request.CreateResponse(HttpStatusCode.Created));
            }

            return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Could not update"));
        }
        public IHttpActionResult CreateCustomers(CustomersDto customersDto)
        {
            var customer = Mapper.Map <CustomersDto, Customers>(customersDto);

            if (ModelState.IsValid)
            {
                db.Customers.Add(customer);
                db.SaveChanges();
            }

            return(Created(new Uri(Request.RequestUri + "/" + customer.Id), customersDto));
        }
Beispiel #14
0
        public IHttpActionResult CreateCustomers(CustomersDto customersDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var customers = Mapper.Map <CustomersDto, Customers>(customersDto);

            context.Customers.Add(customers);
            context.SaveChanges();
            customersDto.Id = customers.Id;

            return(Created(new Uri(Request.RequestUri + "/" + customers.Id), customersDto));
        }
 public CustomersDto GetCustomerById(int Id)
 {
     try
     {
         _logger.LogWarning("گرفتن کاستومر بر اساس ایدی");
         var          result   = _client.GetStringAsync(apiUrl + "/" + Id).Result;
         CustomersDto customer = JsonConvert.DeserializeObject <CustomersDto>(result);
         return(customer);
     }
     catch (Exception)
     {
         throw;
     }
 }
 public void UpdateCustomer(CustomersDto customersDto)
 {
     try
     {
         _logger.LogWarning("بروزرسانی کاستومر");
         string        jsonCustomer = JsonConvert.SerializeObject(customersDto);
         StringContent content      = new StringContent(jsonCustomer, Encoding.UTF8, "application/json");
         var           result       = _client.PutAsync(apiUrl + "/" + customersDto.Id, content).Result;
     }
     catch (Exception)
     {
         throw;
     }
 }
        public IActionResult Edit(CustomersDto customersDto)
        {
            try
            {
                _logger.LogWarning("اجرای متد ویرایش کاربر باcustomersDto ");
                _customer.UpdateCustomer(customersDto);
                _logger.LogInformation("با موفقیت ویرایش شد");
                return RedirectToAction("Index");
            }
            catch (Exception)
            {

                throw;
            }
        }
        public IHttpActionResult CreateCustomer(CustomersDto customerDto)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            var customer = Mapper.Map <CustomersDto, Customers>(customerDto);

            _context.Customers.Add(customer);
            _context.SaveChanges();

            customerDto.Id = customer.Id;

            return(Created(new Uri(Request.RequestUri + "/" + customer.Id), customerDto));
        }
        public void UpdateCustomers(int id, CustomersDto customersDto)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            var CustomerInDb = context.Customers.SingleOrDefault(c => c.Id == id);

            if (CustomerInDb == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            Mapper.Map(customersDto, CustomerInDb);

            context.SaveChanges();
        }
        public ActionResult New(CustomersDto customersDto)
        {
            var customer = new Customer();

            if (customersDto.Id != 0)
            {
                customer = _context.Customers.SingleOrDefault(c => c.Id == customersDto.Id);
            }

            var model = new CustomerViewModel
            {
                MemberShipTypes = _context.MemberShipTypes.ToList(),
                Customer        = customer
            };

            return(View("CustomerForm", model));
        }
 public bool AddCustomer(CustomersDto customersDto, bool res)
 {
     try
     {
         _logger.LogWarning("اضافه کردن کاستومر جدید");
         string        jsonCustomer        = JsonConvert.SerializeObject(customersDto);
         StringContent content             = new StringContent(jsonCustomer, Encoding.UTF8, "application/json");
         var           result              = _client.PostAsync(apiUrl, content).Result;
         var           isSuccessStatusCode = result.IsSuccessStatusCode;
         res = isSuccessStatusCode;
         return(res);
     }
     catch (Exception)
     {
         throw;
     }
 }
Beispiel #22
0
        public IActionResult Login(CustomersDto login)
        {
            try
            {
                _logger.LogError("متد Login فراخوانی شد");
                if (!ModelState.IsValid)
                {
                    _logger.LogError("The Model is not valid");
                    return(View(login));
                }
                var _client  = _httpClientFactory.CreateClient("FastFoodClient");
                var jsonBody = JsonConvert.SerializeObject(login);
                var content  = new StringContent(jsonBody, Encoding.UTF8, "application/json");
                var response = _client.PostAsync("/Api/Authen", content).Result;
                if (response.IsSuccessStatusCode)
                {
                    var token  = response.Content.ReadAsAsync <TokenModel>().Result;
                    var claims = new List <Claim>()
                    {
                        new Claim(ClaimTypes.NameIdentifier, login.Mobile),
                        new Claim(ClaimTypes.Name, login.Mobile),
                        new Claim("AccessToken", token.Token)
                    };
                    var identity   = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    var prinsipal  = new ClaimsPrincipal(identity);
                    var properties = new AuthenticationProperties
                    {
                        IsPersistent = true,
                        AllowRefresh = true
                    };
                    HttpContext.SignInAsync(prinsipal, properties);
                    _logger.LogError("کاربر توکن را دریافت و وارد شد");

                    return(Redirect("/Customer/Index"));
                }
                else
                {
                    ModelState.AddModelError("Mobile", "User not valid or Wrong password");
                    return(View(login));
                }
            }
            catch (Exception)
            {
                throw new BadRequestException(" خطای ناشناخته در ورود به سیستم");
            }
        }
Beispiel #23
0
        public IActionResult PostLogin(CustomersDto login)
        {
            _logger.LogInformation("متد Login فراخوانی شد");

            var mobile           = login.Mobile;
            var passwordCustomer = login.PasswordCustomer;

            if (!ModelState.IsValid)
            {
                _logger.LogError("The Model is not valid");
                return(BadRequest("The Model is not valid"));
            }

            var user = _authen.ListcustomersLogin(mobile, passwordCustomer);

            if (user == null)
            {
                _logger.LogError("نام کاربری یا رمز عبور اشتباه است یا کاربر وجود ندارد");
                return(BadRequest("Not exist user"));
            }
            if (login.Mobile != user.Mobile || login.PasswordCustomer != user.PasswordCustomer)
            {
                _logger.LogError("نام کاربری یا رمز اشتباه است");
                return(Unauthorized());
            }

            var secretKey          = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567890 OurVerifyDotin"));
            var signinCredintioals = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
            var tokenOption        = new JwtSecurityToken(
                issuer: "http://localhost:64467",
                claims: new List <Claim>
            {
                new Claim(ClaimTypes.Name, login.Mobile),
                //new Claim(ClaimTypes.Name,login.FName),
                new Claim(ClaimTypes.Role, "Admin")
            },
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: signinCredintioals
                );

            _logger.LogInformation("توکن ایجاد شد");
            var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOption);

            return(Ok(new { token = tokenString }));
        }
Beispiel #24
0
        public void UpdateCustomer(int id, CustomersDto customersDto)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            var DbCustomer = _context.Customers.SingleOrDefault(c => c.Id == customersDto.Id);

            if (DbCustomer == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            var _customer = Mapper.Map <CustomersDto, Customers>(customersDto, DbCustomer);

            _context.SaveChanges();
        }
        public IActionResult Create(CustomersDto customers, bool res)
        {
            try { 
            _logger.LogInformation("اجرای متد Create کاستومر");
            _customer.AddCustomer(customers, res);
            if (res == false)
            {
                _logger.LogError("موبایل تکراری است");
                return BadRequest("Mobile is Duplicate");
            }
            _logger.LogInformation("کاربر ایجاد شد");
            return RedirectToAction("Index");
            }
            catch (Exception)
            {

                throw;
            }
        }
Beispiel #26
0
 public bool Edit(int id, CustomersDto customer)
 {
     customer.Id             = id;
     customer.LastActiveDate = DateTime.Now;
     using (var db = GetConnection())
     {
         var numberEdited = db.Execute(@"UPDATE [dbo].[Customer]
                            SET [FirstName] = @FirstName
                               ,[LastName] = @LastName
                               ,[LastActiveDate] = @LastActiveDate
                               ,[StreetAddress] = @StreetAddress
                               ,[City] = @City
                               ,[State] = @State
                               ,[ZipCode] = @ZipCode
                               ,[PhoneNumber] = @PhoneNumber
                                 WHERE [CustomerID] = @Id", customer);
         return(numberEdited == 1);
     }
 }
Beispiel #27
0
        public IHttpActionResult UpdateCustomer(int id, CustomersDto customersDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var customerInDB = _context.Customers.SingleOrDefault(c => c.Id == id);

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

            Mapper.Map(customersDto, customerInDB);

            _context.SaveChanges();

            return(Ok());
        }
Beispiel #28
0
        /// <summary>
        /// Update Customer
        /// </summary>
        /// <param name="customersDto"></param>
        /// <returns></returns>
        public bool UpdateCustomer(CustomersDto customersDto)
        {
            bool   result        = false;
            string sqlCommand    = @"UPDATE [dbo].[Customers]
                                                        SET [CompanyName] = @CompanyName
                                                          ,[ContactName] = @ContactName
                                                          ,[ContactTitle] = @ContactTitle
                                                          ,[Address] = @Address
                                                          ,[City] = @City
                                                          ,[Region] = @Region
                                                          ,[PostalCode] = @PostalCode
                                                          ,[Country] = @Country
                                                          ,[Phone] = @Phone
                                                          ,[Fax] = @Fax
                                                     WHERE [CustomerID]= @CustomerID";
            var    dynamicParams = new DynamicParameters();

            dynamicParams.Add("CustomerID", customersDto.CustomerID, DbType.String);
            dynamicParams.Add("CompanyName", customersDto.CompanyName, DbType.String);
            dynamicParams.Add("ContactName", customersDto.ContactName, DbType.String);
            dynamicParams.Add("ContactTitle", customersDto.ContactTitle, DbType.String);
            dynamicParams.Add("Address", customersDto.Address, DbType.String);
            dynamicParams.Add("City", customersDto.City, DbType.String);
            dynamicParams.Add("Region", customersDto.Region, DbType.String);
            dynamicParams.Add("PostalCode", customersDto.PostalCode, DbType.String);
            dynamicParams.Add("Country", customersDto.Country, DbType.String);
            dynamicParams.Add("Phone", customersDto.Phone, DbType.String);
            dynamicParams.Add("Fax", customersDto.Fax, DbType.String);
            var dbConnection = this.DatabaseConnection.Create();

            using (TransactionScope scope = new TransactionScope())
            {
                using (var conn = dbConnection)
                {
                    result = conn.Execute(sqlCommand, dynamicParams) > 0;
                }
                scope.Complete();
            }
            return(result);
        }
        public void UpdateCustomer(CustomersDto customersDto)
        {
            var custDtoDemo  = Mapper.Map <CustomersDto, Customers>(customersDto);//By this way we can create a customer object, access data from the DTO object and remaining is same
            var customerInDb = db.Customers.Find(custDtoDemo.Id);

            if (customerInDb == null)
            {
                throw new Exception(HttpStatusCode.NotFound.ToString());
            }
            else
            {
                if (ModelState.IsValid)
                {
                    customerInDb.BirthDate                = custDtoDemo.BirthDate;
                    customerInDb.CustomerName             = custDtoDemo.CustomerName;
                    customerInDb.MembershipTypeId         = custDtoDemo.MembershipTypeId;
                    customerInDb.IsSubscribedToNewsletter = custDtoDemo.IsSubscribedToNewsletter;

                    db.SaveChanges();
                }
            }
        }
Beispiel #30
0
        public async Task <ActionResult> Post(CustomersDto customersDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage)));
            }

            var client = _httpClientFactory.CreateClient("TEST");

            using (var content = new StringContent(JsonConvert.SerializeObject(customersDto), System.Text.Encoding.UTF8, "application/json"))
            {
                HttpResponseMessage result = await client.PostAsync("Customers", content);

                if (result.StatusCode == System.Net.HttpStatusCode.Created)
                {
                    return(Ok());
                }
                string returnvalue = result.Content.ReadAsStringAsync().Result;
                throw new Exception($"Failed to PUT data : ({result.StatusCode}): {returnvalue}");
            }


            //return new ObjectResult(new DataSourceResult { Data = new[] { product }, Total = 1 });
        }