public async Task UpdateAsync(int Id, ClientUpdateDto model)
        {
            var entity = await _context.Clients.FirstOrDefaultAsync(c => c.Id == Id);

            entity.Name = model.Name;
            await _context.SaveChangesAsync();
        }
        public IActionResult UpdateClient(int clientId, ClientUpdateDto model)
        {
            if (!_clientRepository.IsClientExists(clientId))
            {
                return(NotFound());
            }

            var clientFromRepository = _clientRepository.GetClientById(clientId);

            _mapper.Map(model, clientFromRepository);

            bool result = _clientRepository.Save();

            if (result)
            {
                var eventReport = new ReportEventModel()
                {
                    UserFullName          = $"{clientFromRepository.User.LastName} {clientFromRepository.User.FirstName} {clientFromRepository.User.MiddleName}",
                    CreatedDT             = DateTime.Now,
                    ClientId              = clientFromRepository.Id,
                    OrganizationShortName = clientFromRepository.OrganizationShortName,
                    Comment         = "Запрос на изменение реквизитов клиента",
                    ReportEventType = ReportEventType.UpdateClient
                };
                _logger.LogInfo($"Client updated: {JsonConvert.SerializeObject(eventReport)}");
                _logger.LogInfo($"Updated data: {JsonConvert.SerializeObject(model)}");

                var message = "Зафиксировано измение реквизитов клиента";
                _mailService.Send(_notificationSubscribersRepository.GetSubscribersForClient(clientFromRepository.Id), message);
            }

            return(NoContent());
        }
Example #3
0
 public void Update(ClientUpdateDto dto)
 {
     if (ConnectionManager.PlayerExists(Context.ConnectionId, out var playerId))
     {
         _clientEventReceiver.Update(playerId, dto);
     }
 }
Example #4
0
        public async Task Update(ClientUpdateDto dto)
        {
            EnsureModelValid(dto);

            Client existClient = await FindByClientId(
                dto.ClientId,
                tracking : true,
                includeRelatedEntities : true,
                throwIfNotFound : true);

            existClient.ClientName        = dto.ClientName;
            existClient.ClientUri         = dto.ClientUri;
            existClient.AllowedGrantTypes = dto.GrantTypes?.Select(t => new ClientGrantType {
                GrantType = t
            }).ToList();
            existClient.AllowedScopes = dto.Scopes?.Select(s => new ClientScope {
                Scope = s
            }).ToList();
            existClient.PostLogoutRedirectUris = dto
                                                 .PostLogoutRedirectUris?
                                                 .Select(u => new ClientPostLogoutRedirectUri {
                PostLogoutRedirectUri = u
            })
                                                 .ToList();
            existClient.RedirectUris = dto.RedirectUris?.Select(u => new ClientRedirectUri {
                RedirectUri = u
            }).ToList();

            await _clientRepository.SaveChangesAsync();
        }
Example #5
0
        public async Task Should_Not_UpdateClient_When_Payload_Data_Is_Missing()
        {
            // Arrange
            var customHttpClient = new CustomWebApplicationFactory <Startup>(Guid.NewGuid().ToString()).CreateClient();
            var createdTenant    = await TenantsControllerTests.CreateTenant(customHttpClient);

            var createdClient = await CreateClient(customHttpClient, createdTenant.TenantId);

            var updatedClientDto = new ClientUpdateDto
            {
                FirstName     = "any",
                LastName      = "",
                ContactNumber = "any",
                EmailAddress  = "any",
                Country       = "new Country",
                ClientType    = ClientType.Subscriber.ToString()
            };
            var updatePayload = JsonConvert.SerializeObject(updatedClientDto);

            // Act
            var updateResponse = await customHttpClient.PutAsync($"/api/clients/{createdClient.ClientId}", new StringContent(updatePayload, Encoding.UTF8, "application/json"));

            // Assert
            updateResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest);
            var updateResponseBody = await updateResponse.Content.ReadAsStringAsync();

            updateResponseBody.Should().Contain("The LastName field is required");
        }
Example #6
0
        //TODO refactor this after tests writing
        private static void UpdateTariffs(ClientUpdateDto request, Client toUpdate)
        {
            var currentTariffIds = toUpdate.JoinTariffs
                                   .Select(x => x.TariffId)
                                   .ToList();

            var toAdd = request.TariffIds.Except(currentTariffIds)
                        .ToList();

            var toDel = currentTariffIds.Except(request.TariffIds)
                        .ToList();

            foreach (var i in toDel)
            {
                toUpdate.JoinTariffs = toUpdate.JoinTariffs.Where(x => x.TariffId != i)
                                       .ToList();
            }

            foreach (var i in toAdd)
            {
                toUpdate.JoinTariffs.Add(new JoinClientsTariffs
                {
                    ClientId = toUpdate.Id,
                    TariffId = i
                });
            }
        }
Example #7
0
        private static async Task WhiteAddressUpdate(ClientUpdateDto request, ApplicationDbContext db, Client toUpdate)
        {
            if (request.WhiteAddressId.HasValue)
            {
                var grey = await db.GreyAddresses.FindAsync(toUpdate.GreyAddressId);

                if (grey.White?.Id != request.WhiteAddressId)
                {
                    var white = await db.WhiteAddresses.FindAsync(request.WhiteAddressId);

                    grey.White = white;
                }
            }
            else
            {
                if (toUpdate.GreyAddressId != null)
                {
                    var grey = await db.GreyAddresses.FindAsync(toUpdate.GreyAddressId);

                    if (grey.White != null)
                    {
                        grey.White.GrayAddress = null;
                    }
                }
            }
        }
Example #8
0
        public void Update(int id, ClientUpdateDto model)
        {
            var entry = _context.Clients.Single(x => x.ClientId == id);

            entry.Name = model.Name;

            _context.SaveChanges();
        }
Example #9
0
        public async Task Update(int id, ClientUpdateDto model)
        {
            var entry = await _context.Clients.SingleAsync(x => x.ClientId == id);

            entry.Name = model.Name;

            await _context.SaveChangesAsync();
        }
Example #10
0
        public void UpdateClient_ValidObjectPassed_ReturnsNoContentResult()
        {
            int clientId = 100;
            var testItem = new ClientUpdateDto()
            {
                Firstname = "Fernando", Lastname = "Zabala", Document = "A1242"
            };
            var response = controller.UpdateClient(clientId, testItem);

            Assert.IsType <NoContentResult>(response);
        }
        public void Update(int id, ClientUpdateDto model)
        {
            var entry = _context.Clients.Single(x => x.ClientId == id);

            entry.Name        = model.Name;
            entry.Email       = model.Email;
            entry.PhoneNumber = model.PhoneNumber;
            entry.Username    = model.Username;
            entry.Password    = model.Password;

            _context.SaveChanges();
        }
Example #12
0
        public void UpdateClient_InvalidObjectPassed_ReturnsBadRequestResult()
        {
            int clientId = 100;
            var testItem = new ClientUpdateDto()
            {
                Firstname = "Fernando", Lastname = "", Document = ""
            };

            controller.ModelState.AddModelError("Lastname", "Required");
            var response = controller.UpdateClient(clientId, testItem);

            Assert.IsType <BadRequestResult>(response);
        }
Example #13
0
        public async Task Update(int id, ClientUpdateDto model)
        {
            var entry = await _context.Clients.SingleAsync(x => x.ClientId == id);

            entry.Name      = model.Name;
            entry.SurNames  = model.SurNames;
            entry.Telephone = model.Telephone;
            entry.Address   = model.Address;
            entry.Notes     = model.Notes;
            entry.CountryId = model.CountryId;

            await _context.SaveChangesAsync();
        }
Example #14
0
        public async Task <ActionResult> UpdateClient(string clientId, ClientUpdateDto model)
        {
            bool isSuper = User.IsSuperAdmin();
            IEnumerable <string> allowedClientIds = null;

            if (!isSuper)
            {
                allowedClientIds = User.FindAll(JwtClaimTypes.ClientId).Select(itm => itm.Value);
            }

            await _clientService.UpdateAsync(clientId, model, allowedClientIds);

            return(Ok());
        }
 public IActionResult UpdateClient(ClientUpdateDto updateClient, Guid id)
 {
     try
     {
         ClientServices.UpdateClient(updateClient, id);
         return(NoContent());
     }
     catch (KeyNotFoundException)
     {
         return(NotFound());
     }
     catch (ValidationException)
     {
         return(BadRequest());
     }
 }
Example #16
0
        public async Task <IActionResult> UpdateClient(ClientUpdateDto clientReadDto)
        {
            Client client = mapper.Map <Client>(clientReadDto);

            if (client.CountryId == 0)
            {
                await countryService.Create(client.Country);

                client.CountryId = client.Country.Id;
            }
            client.Country = null;

            await clientService.Update(client);

            return(NoContent());
        }
Example #17
0
        private static async Task GreyAddressUpdate(ClientUpdateDto request, ApplicationDbContext db, Client toUpdate)
        {
            if (request.GreyAddressId.HasValue)
            {
                if (toUpdate.GreyAddress != null && toUpdate.GreyAddressId != request.GreyAddressId.Value && toUpdate.GreyAddress.White != null)
                {
                    var grey = await db.GreyAddresses.FindAsync(toUpdate.GreyAddressId);

                    if (grey.White != null)
                    {
                        grey.White.GrayAddress = null;
                    }
                }
            }

            toUpdate.GreyAddressId = request.GreyAddressId;
        }
Example #18
0
        public async Task <ClientDto> Update(ClientUpdateDto request)
        {
            //TODO need implement validator

            using (var db = new ApplicationDbContext())
            {
                var client = db.Clients
                             .AsQueryable();

                var toUpdate = client.FirstOrDefault(h => h.Id == request.Id);

                if (toUpdate == null)
                {
                    throw new InternalExceptions.NotFoundException($"{nameof(Client)} with id  {request.Id}");
                }

                toUpdate.FullName        = request.FullName;
                toUpdate.PassportData    = request.PassportData;
                toUpdate.PhoneNumber     = request.PhoneNumber;
                toUpdate.Login           = request.Login;
                toUpdate.Password        = request.Password;
                toUpdate.HwIpAddress     = request.HwIpAddress;
                toUpdate.HwPort          = request.HwPort;
                toUpdate.Comment         = request.Comment;
                toUpdate.Credit          = request.Credit;
                toUpdate.IsActive        = request.IsActive;
                toUpdate.HouseId         = request.HouseId;
                toUpdate.ApartmentNumber = request.ApartmentNumber;
                toUpdate.CreditValidFrom = request.CreditValidFrom;
                toUpdate.CreditValidTo   = request.CreditValidTo;
                toUpdate.MacAddress      = request.MacAddress;

                await GreyAddressUpdate(request, db, toUpdate);

                UpdateTariffs(request, toUpdate);
                await WhiteAddressUpdate(request, db, toUpdate);

                db.Clients.Update(toUpdate);

                await db.SaveChangesAsync();

                return(await ById(toUpdate.Id));
            }
        }
        public ClientUpdateDto GetForEdit(int id)
        {
            ClientUpdateDto clientDto = null;

            try
            {
                var client = _unitOfWork.GenericRepository <Client>().GetById(id);
                if (client != null)
                {
                    clientDto = Mapper.Map <Client, ClientUpdateDto>(client);
                }
            }
            catch (Exception ex)
            {
                Tracing.SaveException(ex);
            }

            return(clientDto);
        }
Example #20
0
        public virtual async Task <ClientDto> UpdateAsync(Guid id, ClientUpdateDto input)
        {
            var client = await _clientRepository.GetAsync(id);

            var clientExist = await _clientRepository.CheckClientIdExistAsync(input.ClientId, id);

            if (clientExist)
            {
                throw new UserFriendlyException(L["EntityExisted", nameof(Client), nameof(Client.ClientId),
                                                  input.ClientId]);
            }

            client = ObjectMapper.Map(input, client);

            client.RemoveAllIdentityProviderRestrictions();
            input.IdentityProviderRestrictions
            .ForEach(x => client.AddIdentityProviderRestriction(x));

            client.RemoveAllPostLogoutRedirectUris();
            input.PostLogoutRedirectUris
            .ForEach(x => client.AddPostLogoutRedirectUri(x));

            client.RemoveAllRedirectUris();
            input.RedirectUris
            .ForEach(x => client.AddRedirectUri(x));

            client.RemoveAllCorsOrigins();
            input.AllowedCorsOrigins
            .ForEach(x => client.AddCorsOrigin(x));

            client.RemoveAllAllowedGrantTypes();
            input.AllowedGrantTypes
            .ForEach(x => client.AddGrantType(x));

            client.RemoveAllScopes();
            input.AllowedScopes
            .ForEach(x => client.AddScope(x));

            client = await _clientRepository.UpdateAsync(client);

            return(ObjectMapper.Map <Client, ClientDto>(client));
        }
Example #21
0
        public bool HandleClientUpdate(ClientUpdateDto data)
        {
            if (!data.IsValid())
            {
                return(false);
            }

            var player = _players.Values.FirstOrDefault(p => p.GetId() == data.PlayerId);

            if (player == null)
            {
                return(false);
            }

            var bike = player.GetBike();

            bike.SetDir(new Vector2(data.XDir.Value, data.YDir.Value));
            player.UpdateBike(bike);
            return(true);
        }
Example #22
0
        public async Task <int> Update(ClientUpdateDto dto, int id, string userId)
        {
            var oldClient = await _dbContext.Clients
                            .Include(x => x.Motors)
                            .Include(x => x.SparePartsSold)
                            .Include(x => x.MaintenanceContracts)
                            .Include(x => x.MaintenanceServices)
                            .Include(x => x.SaleContracts).SingleOrDefaultAsync(x => x.Id == id);

            var updatedClient = _mapper.Map(dto, oldClient);

            updatedClient.UpdateAt  = DateTime.Now;
            updatedClient.UpdatedBy = userId;

            _dbContext.Clients.Update(updatedClient);

            await _dbContext.SaveChangesAsync();

            return(updatedClient.Id);
        }
Example #23
0
        private ClientUpdateDto RandomDirectionDto()
        {
            var newVal    = _rand.Next(0, 2) == 0 ? -1 : 1;
            var updateDto = new ClientUpdateDto {
                PlayerId = _botId
            };

            if (_botBike.GetDir().X != 0)
            {
                updateDto.XDir = 0;
                updateDto.YDir = newVal;
            }
            else if (_botBike.GetDir().Y != 0)
            {
                updateDto.XDir = newVal;
                updateDto.YDir = 0;
            }

            return(updateDto);
        }
Example #24
0
        public Client MapToClientModel(Client client, ClientUpdateDto dto)
        {
            if (dto == null)
            {
                return(new Client());
            }
            if (client == null)
            {
                client = new Client();
            }

            client.ClientSecrets = dto.ClientSecrets?.Select(x => new Secret(x.Sha256())).ToList();
            client.AbsoluteRefreshTokenLifetime = dto.AbsoluteRefreshTokenLifetime == null ? Int32.MaxValue : (int)dto.AbsoluteRefreshTokenLifetime;
            client.AccessTokenLifetime          = dto.AccessTokenLifetime == null ? Int32.MaxValue : (int)dto.AccessTokenLifetime;
            client.AuthorizationCodeLifetime    = dto.AuthorizationCodeLifetime == null ? Int32.MaxValue : (int)dto.AuthorizationCodeLifetime;
            client.ConsentLifetime             = dto.ConsentLifetime == null ? Int32.MaxValue : (int)dto.ConsentLifetime;
            client.IdentityTokenLifetime       = dto.IdentityTokenLifetime == null ? Int32.MaxValue : (int)dto.IdentityTokenLifetime;
            client.SlidingRefreshTokenLifetime = dto.SlidingRefreshTokenLifetime == null ? Int32.MaxValue : (int)dto.SlidingRefreshTokenLifetime;

            return(client);
        }
        public async Task <bool> UpdateClientData(ClientUpdateDto client, int clientId)
        {
            var Client   = Guard.Argument(client, nameof(client)).NotNull().Value;
            var ClientId = Guard.Argument(clientId, nameof(clientId)).NotNegative();


            var clientDb = await _context.Clients.SingleOrDefaultAsync(x => x.ClientId == ClientId);

            clientDb.Name     = Client.Name ?? clientDb.Name;
            clientDb.Address  = Client.Address ?? clientDb.Address;
            clientDb.City     = Client.City ?? clientDb.City;
            clientDb.NIP      = Client.NIP == null && Client.NIP == "" ? clientDb.NIP : Client.NIP;
            clientDb.PostCode = Client.PostCode != null?int.Parse(Client.PostCode) : clientDb.PostCode;

            clientDb.State = Client.State ?? clientDb.State;

            _context.Clients.Update(clientDb);

            var isSaved = await _context.SaveChangesAsync();

            return(isSaved != 0);
        }
Example #26
0
        public async Task <IActionResult> UpdateClient(int id, [FromBody] ClientUpdateDto client)
        {
            if (client == null)
            {
                _logger.LogError("Client object sent from client is null");
                return(BadRequest("Client object is null"));
            }
            var clientEntity = await _repository.Client.GetClientByIdAsync(id);

            if (clientEntity == null)
            {
                _logger.LogError($"Client with id {id} does not exist");
                return(NotFound());
            }
            var status = clientEntity.Status;

            _mapper.Map(client, clientEntity);

            await _service.UpdateClient(clientEntity, status);

            return(NoContent());
        }
Example #27
0
        public ActionResult UpdateClient(int id, ClientUpdateDto clientUpdateDto)
        {
            if (clientUpdateDto.Firstname.Equals("") || clientUpdateDto.Lastname.Equals("") || clientUpdateDto.Document.Equals(""))
            {
                return(BadRequest());
            }

            var clientEntity = repository.GetClientById(id);

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

            mapper.Map(clientUpdateDto, clientEntity);

            repository.UpdateClient(clientEntity);

            repository.SaveChanges();

            return(NoContent());
        }
Example #28
0
        public ClientUpdateDto PredictCollision()
        {
            var dDist         = 20;
            var activePlayers = _players.Where(p => p.IsAlive()).ToList();

            var allTrails = new List <TrailSegment>();

            foreach (var p in activePlayers)
            {
                var isSelf = p.GetId() == _botId;
                allTrails.AddRange(p.GetBike().GetTrailSegmentList(!isSelf));
            }

            var incCollision = _botBike.Collides(allTrails, dDist, out _) || _arena.CheckCollision(_botBike, dDist);

            if (!incCollision)
            {
                return(null);
            }

            var newVal    = _rand.Next(0, 2) == 0 ? -1 : 1;
            var updateDto = new ClientUpdateDto {
                PlayerId = _botId
            };

            if (_botBike.GetDir().X != 0)
            {
                updateDto.XDir = 0;
                updateDto.YDir = newVal;
            }
            else if (_botBike.GetDir().Y != 0)
            {
                updateDto.XDir = newVal;
                updateDto.YDir = 0;
            }

            return(RandomDirectionDto());
        }
Example #29
0
        private void PredictCollision()
        {
            var dDist         = 20;
            var activePlayers = players.Where(p => p.IsAlive()).ToList();

            var allTrails = new List <TrailSegment>();

            foreach (var p in activePlayers)
            {
                var isSelf = p.GetId() == GetId();
                allTrails.AddRange(p.GetBike().GetTrailSegmentList(!isSelf));
            }

            var incCollision = GetBike().Collides(allTrails, dDist, out _) || arena.CheckCollision(GetBike(), dDist);

            if (!incCollision)
            {
                return;
            }

            var newVal    = _rand.Next(0, 2) == 0 ? -1 : 1;
            var updateDto = new ClientUpdateDto {
                PlayerId = GetId()
            };

            if (GetBike().GetDir().X != 0)
            {
                updateDto.XDir = 0;
                updateDto.YDir = newVal;
            }
            else if (GetBike().GetDir().Y != 0)
            {
                updateDto.XDir = newVal;
                updateDto.YDir = 0;
            }

            controller.SendUpdate(GetId(), updateDto);
        }
        public ClientDto Update(ClientUpdateDto dto)
        {
            ClientDto clientDto = null;

            try
            {
                var client = _unitOfWork.GenericRepository <Client>().GetById(dto.Id);
                Mapper.Map <ClientUpdateDto, Client>(dto, client);
                client.ModifiedBy = _appSession.GetUserName();
                _unitOfWork.CreateTransaction();

                _unitOfWork.GenericRepository <Client>().Update(client);
                _unitOfWork.Save();

                _unitOfWork.Commit();

                foreach (var clientCashDto in dto.ClientCashes)
                {
                    if (clientCashDto.Id == null || clientCashDto.Id == 0)
                    {
                        _clientCashAppService.Insert(clientCashDto);
                    }
                    else
                    {
                        _clientCashAppService.Update(clientCashDto);
                    }
                }

                CheckForDelete(dto.ClientPhones, client.ClientPhones);
                CheckForAdd(dto.ClientPhones);
                clientDto = Mapper.Map <Client, ClientDto>(client);
            }
            catch (Exception ex)
            {
                Tracing.SaveException(ex);
            }
            return(clientDto);
        }