예제 #1
0
        public ActionResult <BaseServiceResponse <Auction> > FindById([FromRoute] int id)
        {
            BaseServiceResponse <Auction> response = new BaseServiceResponse <Auction>();

            try
            {
                Expression <Func <Auction, bool> > filter = auction => auction.DeletedOn == null;

                Auction auction = _repository.Find(id);

                if (auction == null)
                {
                    response.Status = Enum.GetName(typeof(ResponseStatus), ResponseStatus.NotFound);
                    response.Errors = "The requested resource was not found.";
                    return(NotFound(response));
                }
                else
                {
                    response.Status = Enum.GetName(typeof(ResponseStatus), ResponseStatus.Success);
                    response.Result = auction;
                    return(Ok(response));
                }
            }
            catch (Exception ex)
            {
                response.Status = Enum.GetName(typeof(ResponseStatus), ResponseStatus.Failure);
                response.Errors = ex.ToString();
                return(StatusCode(StatusCodes.Status500InternalServerError, response));
            }
        }
        public BaseServiceResponse DeleteUser(UserRequest userRequest)
        {
            var response = new BaseServiceResponse();

            try
            {
                var user = UserManager.FindByIdAsync(userRequest.UserId);
                var res  = UserManager.DeleteAsync(user.Result);
                if (res.Result.Errors.Count() > 0)
                {
                    response.ResponseStatus = ResponseStatus.BadRequest;
                }
                else
                {
                    response.ResponseStatus = ResponseStatus.Ok;
                }
                return(response);
            }
            catch (Exception ex)
            {
                Logger.ErrorException(ex.Message, ex);

                response.ResponseStatus = ResponseStatus.BadRequest;
            }

            return(response);
        }
 public void OnServiceCallback(object sender, BaseServiceResponse eventArgs)
 {
     _l.info("Callback from one of the service, checking services statuses...");
     if (!ReferenceEquals(Services, null) && Services.Count > 0)
     {
         var checkList = new List <BaseServicesStatuses>();
         foreach (var Service in Services)
         {
             checkList.Add(Service.GetServiceStatus());
         }
         if (checkList.All(e => e.Equals(BaseServicesStatuses.ServiceLaunched)))
         {
             if (InstanceStatus.Equals(WebScrapperBaseStatuses.InstanceNotLaunched))
             {
                 Akeneo.OnProductListeningFinished   -= OnServiceCallback;
                 Shopify.OnShopifyIndexationFinished -= OnServiceCallback;
                 if (_ps.GetServiceStatus().Equals(BaseServicesStatuses.ServiceLaunched))
                 {
                     LinksScrapperInstance();
                     InstanceStatus       = WebScrapperBaseStatuses.InstanceLaunching;
                     _ps.OnProxyCallback -= OnProxyServiceCallback;
                 }
             }
         }
     }
     else
     {
         _l.info("Cancel, not all service are in finished state!");
     }
 }
예제 #4
0
 /// <summary>
 /// ValidateRequest
 /// </summary>
 /// <param name="request"></param>
 /// <param name="response"></param>
 protected void ValidateRequest(BaseServiceRequest request, BaseServiceResponse response)
 {
     if (request == null)
     {
         response.ResponseMessage.Errors.Add(new ErrorDC {
             ErrorCode = CoreValidationMessagesConstants.InvalidArguments, ErrorMessage = string.Format(_coreValidationResourceManager.GetString(CoreValidationMessagesConstants.InvalidArguments), "[Request user context]")
         });
     }
     else if (request.UserContext.Language == null)
     {
         response.ResponseMessage.Errors.Add(new ErrorDC {
             ErrorCode = CoreValidationMessagesConstants.InvalidArguments, ErrorMessage = string.Format(_coreValidationResourceManager.GetString(CoreValidationMessagesConstants.InvalidArguments), "[Request user context language]")
         });
     }
     if (response.ResponseMessage.Errors.Count > 0)
     {
         response.ResponseMessage.MessageCode = CoreValidationMessagesConstants.InvalidArguments;
         response.ResponseMessage.Message     = _coreValidationResourceManager.GetString(CoreValidationMessagesConstants.InvalidArguments);
         response.Status = ResponseStatus.BusinessException;
     }
     if (!response.Status.Equals(ResponseStatus.BusinessException))
     {
         SetLanguage(request.UserContext.Language);
         SetContext();
     }
 }
예제 #5
0
        public async Task <BaseServiceResponse> ResetValid(UserResetValidModel model)
        {
            var response = new BaseServiceResponse();

            var user = await db.FindByResetToken(model.Token);

            if (user == null)
            {
                return(response);
            }

            var hashed = hasher.Hash(model.NewPassword);

            user.Password = hashed.Hash;
            user.Salt     = hashed.Salt;

            try
            {
                await db.UpdateAsync(user);
            }
            catch (Exception e)
            {
                var sentry = new SentryEvent(e);
                await raven.CaptureNetCoreEventAsync(sentry);
            }

            return(response);
        }
        public async Task <BaseServiceResponse <bool> > EliminarAsync(int idAnuncio, int id)
        {
            BaseServiceResponse <bool> response = new BaseServiceResponse <bool>();
            var imagenEntity = await _imagenRepository.ConsultarAsync(id);

            if (imagenEntity is null)
            {
                response.Message = $"No se pudo encontrar la foto con id {id}";
                return(response);
            }

            var eliminado = await EliminarImagenCloudinary(imagenEntity);

            if (!eliminado)
            {
                response.Message = $"No se pudo eliminar la foto con id {id} en la nube";
                return(response);
            }

            response.Message = "Se eliminó exitosamente.";
            response.Success = eliminado;
            response.Data    = eliminado;

            return(response);
        }
        /// <summary>
        /// Deletes or inactivates a rocket (based on client needs)
        /// </summary>
        /// <param name="id">id to delete</param>
        public async Task <BaseServiceResponse <int> > DeleteRocket(int id)
        {
            var response = new BaseServiceResponse <int>(id);

            // make sure user has access to this
            if (!UserPermissionService.UserClaimModel.UserPolicies.UserAddEditDelete)
            {
                response.Message = "You are not authorized to add/edit a rocket.";
                response.Status  = System.Net.HttpStatusCode.Unauthorized;
                return(response);
            }

            // make sure logged in user has permission to the requested user
            var dbObj = await db.RoleRestrictedRockets(UserPermissionService, false).FirstOrDefaultAsync(w => w.RocketId == id);

            if (dbObj == null)
            {
                response.Status = System.Net.HttpStatusCode.BadRequest;
                return(response);
            }
            // delete (need to delete owned types and dependent tables)
            //db.Remove(dbObj);
            //db.Remove(dbObj.AuditFields);
            // inactivate
            dbObj.AuditFields.SetActiveInactive(false, UserPermissionService.UserClaimModel.UserId, DateTime.UtcNow);

            await db.SaveChangesAsync();

            return(response);
        }
예제 #8
0
        public async Task <BaseServiceResponse <List <CompanyDto> > > GetAll()
        {
            BaseServiceResponse <List <CompanyDto> > serviceResponse = new BaseServiceResponse <List <CompanyDto> >();

            try
            {
                var data = await _dbContext.Companies.ToListAsync();

                serviceResponse.Results = data.Select(e => new CompanyDto()
                {
                    Id        = e.Id,
                    Name      = e.Name,
                    Email     = e.Email,
                    Website   = e.Website,
                    Telephone = e.Telephone
                }).ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Company Service - Get All Companies threw exception.");
                serviceResponse.Success      = false;
                serviceResponse.ErrorMessage = ex.ToString();
            }

            return(serviceResponse);
        }
예제 #9
0
        public async Task <BaseServiceResponse <bool> > EliminarAsync(int id)
        {
            BaseServiceResponse <bool> response = new BaseServiceResponse <bool>();

            var anuncioResult = await _anuncioRepository.ConsultarAsync(id);

            if (anuncioResult == null)
            {
                response.Message = "No existe el anuncio.";
                return(response);
            }
            if (anuncioResult.Activo)
            {
                response.Message = "No se puedo eliminar el anuncio porque se encuentra activo.";
                return(response);
            }

            var deleted = await _anuncioRepository.EliminarAnuncioAsync(id);

            if (!deleted)
            {
                response.Message = "No se puedo editar el anuncio.";
                return(response);
            }

            response.Data    = deleted;
            response.Success = deleted;
            response.Message = "Se eliminó exitosamente";

            return(response);
        }
예제 #10
0
        public async Task <BaseServiceResponse <List <InstallerDto> > > GetInstallers()
        {
            BaseServiceResponse <List <InstallerDto> > response = new BaseServiceResponse <List <InstallerDto> >();

            try
            {
                var locations = await _dbContext.CompanyLocations.Where(e => e.Type == LocationType.Installer).Include(r => r.Company)
                                .ToListAsync();

                response.Results = locations.Select(e => new InstallerDto()
                {
                    LocationId = e.Id,
                    CompanyId  = e.CompanyId,
                    Name       = e.Company.Name,
                    Telephone  = e.Company.Telephone,
                    Email      = e.Company.Email,
                    Rating     = 5
                }).ToList();

                response.Success = true;
            }
            catch (Exception ex)
            {
                response.Success      = false;
                response.ErrorMessage = ex.ToString();
                _logger.LogError(ex, "Get Installers Method in Installer Service threw an exception.");
            }

            return(response);
        }
예제 #11
0
        public BaseServiceResponse <ShrinkResponseBody> Shrink([FromBody] ShrinkRequestBody request)
        {
            BaseServiceResponse <ShrinkResponseBody> response = new BaseServiceResponse <ShrinkResponseBody>();

            try
            {
                #region Validations

                // Request's body can't be null.
                if (request == null)
                {
                    throw new ArgumentNullException(nameof(request));
                }

                // Index prefix must be informed.
                if (string.IsNullOrWhiteSpace((request.IndexName)))
                {
                    throw new ArgumentNullException(nameof(request.IndexName));
                }

                #endregion

                // Performs the shrink operation on index.
                ElasticsearchResponse <VoidResponse> operationResponse = Processor.Shrink(request.IndexName);
            }
            catch (Exception ex) {
                response = new BaseServiceResponse <ShrinkResponseBody>(ex);
            }

            return(response);
        }
        /// <summary>
        /// Looks a the response from the service and creates the corresponding response.
        /// </summary>
        /// <typeparam name="T">Data object that would be passed back on OK</typeparam>
        /// <param name="response">BaseServiceResponse</param>
        protected IActionResult CreateResponse <T>(BaseServiceResponse <T> response)
        {
            // there are many status codes
            // add http status codes as needed
            switch (response.Status)
            {
            case System.Net.HttpStatusCode.BadRequest:
                // if message is empty then check ModelState
                if (string.IsNullOrEmpty(response.Message) && !ModelState.IsValid)
                {
                    response.Message = string.Join("<br/>", (from ms in ModelState
                                                             from e in ms.Value.Errors
                                                             select $"{e.ErrorMessage}"));
                }
                return(StatusCode((int)response.Status, response.Message));

            case System.Net.HttpStatusCode.Conflict:
            case System.Net.HttpStatusCode.NotImplemented:
            case System.Net.HttpStatusCode.Unauthorized:
                return(StatusCode((int)response.Status, response.Message));

            case System.Net.HttpStatusCode.OK:
                return(Ok(response.Data));
            }
            return(Problem("Unknown reponse type"));
        }
        public async Task <BaseServiceResponse <int> > GenerarPromocionAnuncioAsync()
        {
            BaseServiceResponse <int> response = new BaseServiceResponse <int>();
            var anuncioEntity = await _anuncioRepository.ConsultarAnuncioMasAntiguoAsync();

            if (anuncioEntity is null)
            {
                response.Message = "No se pudo obtener información.";
                return(response);
            }

            var idPromocionAnuncio = await _promocionAnuncioRepository.CrearPromocionAnuncioAsync(anuncioEntity.IdAnuncio);

            if (idPromocionAnuncio == default)
            {
                response.Message = "No se pudo obtener generar promoción.";
                return(response);
            }

            ThreadPromotion.GenerarPromocion(anuncioEntity.IdAnuncio);

            response.Message = "Se obtuvo la información exitosamente.";
            response.Success = true;
            response.Data    = idPromocionAnuncio;
            return(response);
        }
        public async Task <BaseServiceResponse <bool> > AgendarPromocionAnuncioAsync(string idUsuario, AgendarPromocionAnuncioRequest request)
        {
            BaseServiceResponse <bool> response = new BaseServiceResponse <bool>();

            var agendado = ThreadPromotion.AgendarPromocionParaUsuario(idUsuario, request.IdAnuncio.Value);

            if (!agendado)
            {
                response.Message = $"No se pudo agendar la promoción para el usuario {idUsuario} con el anuncio {request.IdAnuncio}.";
                return(response);
            }
            var usuario = await _usuarioRepository.ConsultarUsuarioAsync(idUsuario);

            var promocionEntity = _mapper.Map <PromocionAnuncioEntity>(request);

            promocionEntity.IdUsuario = usuario.IdUsuario;
            var result = await _promocionAnuncioRepository.AgendarPromocionAnuncioAsync(promocionEntity);

            if (result == default)
            {
                response.Message = "No se pudo registrar la agenda de la promoción.";
                return(response);
            }

            response.Message = "Se pudo agendar exitosamente.";
            response.Success = true;
            response.Data    = result;
            return(response);
        }
예제 #15
0
        public async Task <BaseServiceResponse <List <CustomerDto> > > GetCustomers()
        {
            BaseServiceResponse <List <CustomerDto> > response = new BaseServiceResponse <List <CustomerDto> >();

            try
            {
                var customers = await _dbContext.Customers.ToListAsync();

                response.Results = customers.Select(e => new CustomerDto()
                {
                    Id           = e.Id,
                    MacAddress   = e.MacAddress,
                    Name         = e.Name ?? "",
                    Address      = e.Address ?? "",
                    EmailAddress = e.EmailAddress ?? ""
                }).ToList();

                response.Success = true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Customer Service exception - GetCustomers");
                response.Success      = false;
                response.ErrorMessage = ex.ToString();
            }

            return(response);
        }
        public async Task <BaseServiceResponse <int> > CrearImagenAsync(int idAnuncio, CreacionImagenRequest request)
        {
            BaseServiceResponse <int> response = new BaseServiceResponse <int>();
            var imagenEntity = UploadingToCloudinary(request);

            if (string.IsNullOrEmpty(imagenEntity.ImagenUrl))
            {
                response.Message = "La imagen no se pudo subir a la nube.";
                return(response);
            }

            imagenEntity.IdAnuncio = idAnuncio;
            var idImagen = await _imagenRepository.CrearImagenAsync(imagenEntity);

            if (idImagen == default)
            {
                response.Message = "La imagen no se pudo registrar.";
                return(response);
            }

            response.Message = "La imagen se registró exitosamente.";
            response.Success = true;
            response.Data    = idImagen;

            return(response);
        }
예제 #17
0
        public ActionResult <BaseServiceResponse <ArrayResponse <Make> > > FindAll()
        {
            BaseServiceResponse <ArrayResponse <Make> > response = new BaseServiceResponse <ArrayResponse <Make> >();

            try
            {
                Expression <Func <Make, bool> > filter = make => make.DeletedOn == null;

                List <Make> makes = _repository.FindAll(null, filter);

                response.Status = Enum.GetName(typeof(ResponseStatus), ResponseStatus.Success);
                response.Result = new ArrayResponse <Make>()
                {
                    Data = makes,
                };

                return(Ok(response));
            }
            catch (Exception ex)
            {
                response.Status = Enum.GetName(typeof(ResponseStatus), ResponseStatus.Failure);
                response.Errors = ex.ToString();
                return(StatusCode(StatusCodes.Status500InternalServerError, response));
            }
        }
예제 #18
0
        public async Task <BaseServiceResponse <bool> > EditarAsync(string idUsuario, EdicionAnuncioRequest request)
        {
            BaseServiceResponse <bool> response = new BaseServiceResponse <bool>();
            var usuario = await _usuarioRepository.ConsultarUsuarioAsync(idUsuario);

            var anuncioResult = await _anuncioRepository.ConsultarAsync(request.IdAnuncio.Value);

            if (anuncioResult == null)
            {
                response.Message = "No existe el anuncio.";
                return(response);
            }
            if (anuncioResult.Activo)
            {
                response.Message = "No se puedo editar el anuncio porque se encuentra activo.";
                return(response);
            }

            var anuncio = _mapper.Map <AnuncioEntity>(request);

            anuncio.IdUsuario = usuario.IdUsuario;
            var anuncioUpdated = await _anuncioRepository.EditarAnuncioAsync(anuncio);

            if (!anuncioUpdated)
            {
                response.Message = "No se puedo editar el anuncio.";
                return(response);
            }

            var anuncioDetalle       = _mapper.Map <AnuncioDetalleEntity>(request);
            var anuncioDetalleEntity = await _anuncioDetalleRepository.ConsultarAnuncioDetallePorAnuncioAsync(request.IdAnuncio.Value);

            anuncioDetalle.IdAnuncioDetalle = anuncioDetalleEntity != default ? anuncioDetalleEntity.IdAnuncioDetalle : default;
            var anuncioDetalleUpdated = await _anuncioDetalleRepository.EditarAnuncioDetalleAsync(anuncioDetalle);

            if (!anuncioDetalleUpdated)
            {
                response.Message = "No se puedo editar el detalle del anuncio.";
                return(response);
            }

            var ubicacion       = _mapper.Map <UbicacionEntity>(request);
            var ubicacionEntity = await _ubicacionRepository.ConsultarPorAnuncioAsync(request.IdAnuncio.Value);

            ubicacion.IdUbicacion = ubicacionEntity != default ? ubicacionEntity.IdUbicacion : default;
            var ubicacionUpdated = await _ubicacionRepository.EditarUbicacionAsync(ubicacion);

            if (!ubicacionUpdated)
            {
                response.Message = "No se puedo editar la ubicación.";
                return(response);
            }

            response.Data    = anuncioUpdated;
            response.Success = anuncioUpdated;
            response.Message = "Se actualizó exitosamente";

            return(response);
        }
예제 #19
0
        public void ShrinkByDate_when_request_is_null()
        {
            BaseServiceResponse <ShrinkByDateResponseBody> response = Controller.ShrinkByDate(null);

            Assert.IsTrue(response.Operation.Failed);
            Assert.IsNull(response.Body);
            Assert.AreEqual(nameof(ArgumentNullException), response.Operation.Error.ClassName);
        }
예제 #20
0
        public void Shrink_when_index_name_is_null()
        {
            ShrinkRequestBody request = new ShrinkRequestBody();

            BaseServiceResponse <ShrinkResponseBody> response = Controller.Shrink(request);

            Assert.IsTrue(response.Operation.Failed);
            Assert.IsNull(response.Body);
            Assert.AreEqual(nameof(ArgumentNullException), response.Operation.Error.ClassName);
        }
예제 #21
0
        public ActionResult <BaseServiceResponse <ArrayResponse <Auction> > > FindAll(int?makeId, int?modelId, int?trimId,
                                                                                      int?year, int pageNumber = 1, int pageSize = 10)
        {
            BaseServiceResponse <ArrayResponse <Auction> > response = new BaseServiceResponse <ArrayResponse <Auction> >();

            try
            {
                Pagination pagination = new Pagination()
                {
                    PageNumber = pageNumber, PageSize = pageSize
                };

                #region Filter Data
                Expression <Func <Auction, bool> > filter = auction => auction.DeletedOn == null;
                if (makeId.HasValue && makeId.Value > 0)
                {
                    filter = filter.And(auction => auction.MakeId == makeId.Value);
                }

                if (modelId.HasValue && modelId.Value > 0)
                {
                    filter = filter.And(auction => auction.ModelId == modelId.Value);
                }

                if (trimId.HasValue && trimId.Value > 0)
                {
                    filter = filter.And(auction => auction.TrimId == trimId.Value);
                }

                if (year.HasValue && year.Value > 0)
                {
                    filter = filter.And(auction => auction.Year == year.Value);
                }
                #endregion

                List <Auction> auctions = _repository.FindAll(pagination, filter);

                response.Status     = Enum.GetName(typeof(ResponseStatus), ResponseStatus.Success);
                response.ServerTime = DateTime.Now.ToString("o");
                response.Result     = new ArrayResponse <Auction>()
                {
                    Data       = auctions,
                    Pagination = pagination
                };
                return(Ok(response));
            }
            catch (Exception ex)
            {
                response.Status = Enum.GetName(typeof(ResponseStatus), ResponseStatus.Failure);
                response.Errors = ex.ToString();
                return(StatusCode(StatusCodes.Status500InternalServerError, response));
            }
        }
예제 #22
0
        public async Task <BaseServiceResponse <IEnumerable <AnuncioResponse> > > ConsultarPorUsuarioAsync(string idUsuario)
        {
            BaseServiceResponse <IEnumerable <AnuncioResponse> > response = new BaseServiceResponse <IEnumerable <AnuncioResponse> >();
            List <AnuncioResponse> anuncioResponses = new List <AnuncioResponse>();
            var anuncios = await _anuncioRepository.ConsultarAnunciosAsync(idUsuario);

            var usuario = await _usuarioRepository.ConsultarUsuarioAsync(idUsuario);

            if (anuncios is null)
            {
                response.Message = $"No se pudo obtener información de anuncios del usuario {idUsuario}";
                return(response);
            }

            foreach (var anuncio in anuncios)
            {
                var anuncioDetalle = await _anuncioDetalleRepository.ConsultarAnuncioDetallePorAnuncioAsync(anuncio.IdAnuncio);

                var tipoPropiedad = await _tipoPropiedadRepository.ConsultarTipoPropiedadAsync(anuncio.IdTipoPropiedad);

                var ubicacion = await _ubicacionRepository.ConsultarPorAnuncioAsync(anuncio.IdAnuncio);

                var evaluaciones = await _evaluacionRepository.ConsultarPorAnuncioAsync(anuncio.IdAnuncio);

                var imagenes = await _imagenRepository.ConsultarPorAnuncioAsync(anuncio.IdAnuncio);

                var anuncioResponse       = _mapper.Map <AnuncioResponse>(anuncio);
                var usuarioResponse       = usuario is null ? new UsuarioResponse() : _mapper.Map <UsuarioResponse>(usuario);
                var tipoPropiedadResponse = tipoPropiedad is null ? new TipoPropiedadResponse() : _mapper.Map <TipoPropiedadResponse>(tipoPropiedad);
                var evaluacionResponses   = _mapper.Map <IEnumerable <EvaluacionResponse> >(evaluaciones);
                var imagenResponses       = _mapper.Map <IEnumerable <ImagenResponse> >(imagenes);
                ubicacion      = ubicacion ?? new UbicacionEntity();
                anuncioDetalle = anuncioDetalle ?? new AnuncioDetalleEntity();

                anuncioResponse.Usuario              = usuarioResponse;
                anuncioResponse.TipoPropiedad        = tipoPropiedadResponse;
                anuncioResponse.Metros2              = anuncioDetalle.Metros2;
                anuncioResponse.CantidadHabitaciones = anuncioDetalle.CantidadHabitaciones;
                anuncioResponse.CantidadBaños        = anuncioDetalle.CantidadBaños;
                anuncioResponse.CantidadParqueos     = anuncioDetalle.CantidadParqueos;
                anuncioResponse.Plantas              = anuncioDetalle.Plantas;
                anuncioResponse.Direccion            = ubicacion.Direccion;
                anuncioResponse.Latitud              = ubicacion.Latitud;
                anuncioResponse.Longitud             = ubicacion.Longitud;
                anuncioResponse.Evaluaciones         = evaluacionResponses;
                anuncioResponse.Imagenes             = imagenResponses;
                anuncioResponses.Add(anuncioResponse);
            }
            response.Success = true;
            response.Message = "Se obtuvo información de anuncios exitosamente.";
            response.Data    = anuncioResponses;
            return(response);
        }
예제 #23
0
        public BaseServiceResponse DeleteUser(UserRequest userRequest)
        {
            var response = new BaseServiceResponse();

            try
            {
                var user = UserManager.FindById(userRequest.UserId);
                var res  = UserManager.Delete(user);
                if (res.Errors.Count() > 0)
                {
                    response.ResponseStatus = new ResponseStatus
                    {
                        StatusCode = (int)HttpStatusCode.BadRequest,
                        HttpStatus = HttpStatusCode.BadRequest.ToString(),
                        Message    = MessageDescription.TransactionFailed.GetDescription(),
                        Errors     = new List <ResponseError>()
                        {
                            new ResponseError()
                            {
                                Message = res.Errors.FirstOrDefault()
                            }
                        }
                    };
                }
                else
                {
                    response.ResponseStatus = new ResponseStatus
                    {
                        StatusCode = (int)HttpStatusCode.OK,
                        HttpStatus = HttpStatusCode.OK.ToString()
                    };
                }
                return(response);
            }
            catch (Exception ex)
            {
                response.ResponseStatus = new ResponseStatus
                {
                    StatusCode = (int)HttpStatusCode.ExpectationFailed,
                    HttpStatus = HttpStatusCode.ExpectationFailed.ToString(),
                    Message    = MessageDescription.TransactionFailed.GetDescription(),
                    Errors     = new List <ResponseError>()
                    {
                        new ResponseError()
                        {
                            Message = MessageDescription.TransactionFailed.GetDescription()
                        }
                    }
                };
                return(response);
            }
        }
 public BaseServiceResponse <Registro> RegistrarPonto(Registro registro)
 {
     try
     {
         _repository.Add(registro);
         return(new BaseServiceResponse <Registro>());
     }
     catch (Exception ex)
     {
         var response = new BaseServiceResponse <Registro>("Erro ao salvar registro.");
         return(response);
     }
 }
예제 #25
0
        /// <summary>
        /// Saves a user
        /// </summary>
        /// <param name="dto">dto to save</param>
        /// <returns>updated dto object</returns>
        public async Task <BaseServiceResponse <T> > SaveUserProfile <T>(T dto) where T : UserProfileDto
        {
            var response = new BaseServiceResponse <T>(dto);

            if (!UserPermissionService.UserClaimModel.UserPolicies !.UserProfileEdit)
            {
                response.Message = "You are not authorized to edit the user profile.";
                response.Status  = System.Net.HttpStatusCode.Unauthorized;
                return(response);
            }

            // nothing changed, return
            if (!dto.IsUpdated)
            {
                return(response);
            }

            var timestamp = DateTime.UtcNow;

            if (db.Users.Any(w => w.Email == dto.Email && w.UserId != UserPermissionService.UserClaimModel.UserId))
            {
                response.Message = "Email already in use.";
                response.Status  = System.Net.HttpStatusCode.Conflict;
                return(response);
            }

            var dbObj = await db.RoleRestrictedUsers(UserPermissionService, false).Include(i => i.UserRoles).SingleOrDefaultAsync(w => w.UserId == dto.UserId);

            if (dbObj == null)
            {
                response.Message = "You are not authorized to edit this user.";
                response.Status  = System.Net.HttpStatusCode.Unauthorized;
                return(response);
            }

            dbObj.Email                = dto.Email;
            dbObj.FirstName            = dto.FirstName;
            dbObj.LastName             = dto.LastName;
            dbObj.NormalizedEmail      = dto.Email !.ToUpper();
            dbObj.PhoneNumber          = dto.PhoneNumber?.RemoveNonNumerics();
            dbObj.PhoneNumberConfirmed = !string.IsNullOrWhiteSpace(dbObj.PhoneNumber);
            dbObj.TwoFactorEnabled     = dto.TwoFactorEnabled;

            dbObj.AuditFields !.SetUpdated(UserPermissionService.UserClaimModel.UserId, timestamp);

            await db.SaveChangesAsync();

            dto.IsUpdated = false;

            return(response);
        }
예제 #26
0
        public async Task <BaseServiceResponse <CustomerDto> > GetCustomerAccount(string macAddress)
        {
            BaseServiceResponse <CustomerDto> response = new BaseServiceResponse <CustomerDto>();

            try
            {
                var existing = await _dbContext.Customers.Where(e => e.MacAddress == macAddress).SingleOrDefaultAsync();

                if (existing != null)
                {
                    response.Results = new CustomerDto()
                    {
                        Id         = existing.Id,
                        Name       = existing.Name ?? "",
                        Address    = existing.Address ?? "",
                        MacAddress = existing.MacAddress
                    };

                    response.Success = true;
                }
                else
                {
                    //new customer
                    CustomerEntity entity = new CustomerEntity()
                    {
                        MacAddress = macAddress,
                        Created    = DateTime.Now
                    };

                    _dbContext.Customers.Add(entity);
                    await _dbContext.SaveChangesAsync();

                    response.Results = new CustomerDto()
                    {
                        MacAddress = entity.MacAddress,
                        Id         = entity.Id
                    };

                    response.Success = true;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Customer Service Exception - Get Customer Account");
                response.Success      = false;
                response.ErrorMessage = ex.ToString();
            }

            return(response);
        }
        private async Task <BaseServiceResponse <int> > GetCrearResponseAsync(bool isValid)
        {
            BaseServiceResponse <int> response = new BaseServiceResponse <int>();

            if (!isValid)
            {
                response.Message = "No se pudo registrar la información del anuncio";
                return(response);
            }
            response.Data    = 1;
            response.Message = "Se registró existomante";
            response.Success = true;
            return(await Task.FromResult(response));
        }
        private async Task <BaseServiceResponse <bool> > GetEliminarResponseAsync(bool isValid)
        {
            BaseServiceResponse <bool> response = new BaseServiceResponse <bool>();

            if (!isValid)
            {
                response.Message = "No se pudo eliminar la información del anuncio";
                return(response);
            }
            response.Data    = true;
            response.Message = "Se eliminó existomante";
            response.Success = true;
            return(await Task.FromResult(response));
        }
        private async Task <BaseServiceResponse <string> > ValidarPropietario(string idUsuario, int idAnuncio)
        {
            BaseServiceResponse <string> response = new BaseServiceResponse <string>();
            var usuario = await _usuarioService.ConsultarUsuarioPorAnuncioAsync(idAnuncio);

            if (usuario.Data?.Identifier == idUsuario)
            {
                response.Message = "El usuario no puede registrar una evaluación.";
                return(response);
            }
            response.Data    = idUsuario;
            response.Success = true;
            return(response);
        }
예제 #30
0
        /// <summary>
        /// saves the user's password change date/time
        /// </summary>
        /// <param name="userId">user's id to save</param>
        public async Task <BaseServiceResponse <string> > SaveLastPasswordChangeDateTime(int userId)
        {
            var response = new BaseServiceResponse <string>("");

            var result = await db.SaveLastPasswordChangeDateTime(userId);

            if (result == 0)
            {
                response.Status  = System.Net.HttpStatusCode.BadRequest;
                response.Message = "Last password change date/time could not be updated";
            }

            return(response);
        }
예제 #31
0
 /// <summary>
 /// ValidateRequest
 /// </summary>
 /// <param name="request"></param>
 /// <param name="response"></param>
 protected void ValidateRequest(BaseServiceRequest request, BaseServiceResponse response)
 {
     if (request == null)
         response.ResponseMessage.Errors.Add(new ErrorDC { ErrorCode = CoreValidationMessagesConstants.InvalidArguments ,ErrorMessage= string.Format(_coreValidationResourceManager.GetString(CoreValidationMessagesConstants.InvalidArguments), "[Request user context]")});
     else if (request.UserContext.Language == null)
         response.ResponseMessage.Errors.Add(new ErrorDC { ErrorCode = CoreValidationMessagesConstants.InvalidArguments, ErrorMessage = string.Format(_coreValidationResourceManager.GetString(CoreValidationMessagesConstants.InvalidArguments),"[Request user context language]") });
     if(response.ResponseMessage.Errors.Count>0)
     {
         response.ResponseMessage.MessageCode = CoreValidationMessagesConstants.InvalidArguments;
         response.ResponseMessage.Message = _coreValidationResourceManager.GetString(CoreValidationMessagesConstants.InvalidArguments);
         response.Status = ResponseStatus.BusinessException;
     }
     if (!response.Status.Equals(ResponseStatus.BusinessException))
     {
         SetLanguage(request.UserContext.Language);
         SetContext();
     }
 }