public IdentityManagementController(IIdentityManagementService identityManagementService) { if (identityManagementService == null) { throw new ArgumentNullException("identityManagementService"); } this.identityManagementService = identityManagementService; mapperFactory = new MapperFactory(); }
/// <summary> /// gets an expression tree which recursively call the constructors of this node subNodes to build an object /// </summary> /// <param name="sourceParameter">the parameter containing the flat object which will be usde as source</param> /// <param name="namesMismatch">whether to allow names mismatches or not when searching for an appropriate default constructor</param> /// <returns>san expression tree which recursively call the constructors of this node subNodes to build an object</returns> public Expression GetExpression(ParameterExpression sourceParameter, MapperFactory.NamesMismatch namesMismatch) { var namesMismatchSubtypes = namesMismatch == MapperFactory.NamesMismatch.AllowInNestedTypesOnly ? MapperFactory.NamesMismatch.AlwaysAllow : namesMismatch; if (SourcePropertyName != null) { return GetCastedValue(sourceParameter); } else if (Nodes != null) { // does a default constructor exist? var defaultConstructor = TargetType.GetConstructor(Type.EmptyTypes); if (defaultConstructor != null) { // new object(); var newObjectExpression = Expression.New(defaultConstructor); var objectInitializerBindings = Nodes.Select( childNode => Expression.Bind(TargetType.GetProperty(childNode.TargetName), childNode.GetExpression(sourceParameter, namesMismatchSubtypes))) .Cast<MemberBinding>() .ToList(); var creationExpression = Expression.MemberInit(newObjectExpression, objectInitializerBindings); // (type)new object(); return Expression.Convert(creationExpression, TargetType); } else // let's see if there's a suitable non-default constructor { var constructor = FindConstructor(TargetType, Nodes.Select(x => new PropertyBasicInfo(x.TargetName, x.TargetType)).ToList(), true); if (constructor == null) { throw new InvalidOperationException("counldn't find a proper constructor to initialize " + TargetType); } var creationExpression = Expression.New(constructor, Nodes.Select(x => x.GetExpression(sourceParameter, namesMismatchSubtypes))); return Expression.Convert(creationExpression, TargetType); } } else // ignored field, set to null { return Expression.Convert(Expression.Constant(null), TargetType); } }
public static Node BuildTree(Type t, string name, Queue<PropertyBasicInfo> sourceObjectProperties, MapperFactory.NamesMismatch namesMismatch, List<Type> assumeNullWontBeMappedToThoseTypes, List<string> ignoredFields) { var props = t.GetProperties( BindingFlags.Public | BindingFlags.Instance) .Where(x => x.GetSetMethod() != null); var nodes = new List<Node>(); foreach (var prop in props) { if (ignoredFields.Contains(prop.Name)) { nodes.Add(new Node(prop.PropertyType, prop.Name)); continue; } if (sourceObjectProperties.Count == 0) { throw new InvalidOperationException("Not enough fields in the flat object, don't know how to set " + prop.Name); } var propToMap = sourceObjectProperties.Peek(); if ((propToMap.Type == null && !ListContainsType(assumeNullWontBeMappedToThoseTypes, prop.PropertyType)) || (propToMap.Type != null && AvailableCastChecker.CanCast(propToMap.Type, prop.PropertyType)) ) { if (namesMismatch == MapperFactory.NamesMismatch.AlwaysAllow || prop.Name == propToMap.Name) { nodes.Add(new Node(prop.PropertyType, prop.Name, propToMap.Name)); sourceObjectProperties.Dequeue(); } else { throw new InvalidOperationException("Name mismatch for property " + prop.Name); } } else if (prop.PropertyType.GetProperties(BindingFlags.Public | BindingFlags.Instance).All(x => x.GetSetMethod() == null)) { var path = name == null ? null : name + "."; // no sense recursing on this throw new InvalidOperationException( $"Type mismatch when mapping {propToMap.Name} ({propToMap.Type}) with {path}{prop.Name} ({prop.PropertyType})"); } else { nodes.Add(BuildTree(prop.PropertyType,prop.Name, sourceObjectProperties, namesMismatch== MapperFactory.NamesMismatch.AllowInNestedTypesOnly? MapperFactory.NamesMismatch.AlwaysAllow:namesMismatch, assumeNullWontBeMappedToThoseTypes, ignoredFields)); } } return new Node(t,name,nodes); }
public async Task <IActionResult> Create(StoreModel model, bool continueEditing) { if (ModelState.IsValid) { var store = await MapperFactory.MapAsync <StoreModel, Store>(model); // Ensure we have "/" at the end. store.Url = store.Url.EnsureEndsWith("/"); _db.Stores.Add(store); await _db.SaveChangesAsync(); NotifySuccess(T("Admin.Configuration.Stores.Added")); return(continueEditing ? RedirectToAction("Edit", new { id = store.Id }) : RedirectToAction("List")); } await PrepareStoreModelAsync(model, null); return(View(model)); }
public ActionResult <IEnumerable <ResRestaurantDTO> > GetReservationNotPay(int userId) //this method is not used to this preview { var getResNotPayByIdCommand = CommandFactory.GetResRestaurantNotPayByIdCommand(userId); try { Console.WriteLine(userId); //return ResRestaurantRepository.getReservationNotPay(userId); getResNotPayByIdCommand.Execute(); ResRestaurantMapper resRestMapper = MapperFactory.createResRestaurantMapper(); return(resRestMapper.CreateDTOList(getResNotPayByIdCommand.GetResult())); } catch (DatabaseException) { return(StatusCode(500)); } catch (InvalidStoredProcedureSignatureException) { return(StatusCode(500)); } }
public ActionResult <IEnumerable <ResRestaurantDTO> > Get(int id) { var getByIdCommand = CommandFactory.GetResRestaurantByIdCommand(id); try { Console.WriteLine(id); //return ResRestaurantRepository.getResRestaurant(id); getByIdCommand.Execute(); //return getByIdCommand.GetResult(); ResRestaurantMapper resRestMapper = MapperFactory.createResRestaurantMapper(); return(resRestMapper.CreateDTOList(getByIdCommand.GetResult())); } catch (DatabaseException) { return(StatusCode(500)); } catch (InvalidStoredProcedureSignatureException) { return(StatusCode(500)); } }
public IList <ClassDisciplineDetails> GetClassDisciplineDetails(int classId, DateTime date) { var mp = ServiceLocator.MarkingPeriodService.GetLastClassMarkingPeriod(classId, date); if (mp == null) { return(new List <ClassDisciplineDetails>()); } var disciplineRefferals = ConnectorLocator.DisciplineConnector.GetList(classId, date); var options = ServiceLocator.ClassroomOptionService.GetClassOption(classId); if (disciplineRefferals != null) { var students = ServiceLocator.StudentService.GetClassStudents(classId, mp.Id , options != null && options.IncludeWithdrawnStudents ? (bool?)null : true); var cClass = ServiceLocator.ClassService.GetClassDetailsById(classId); var res = new List <ClassDisciplineDetails>(); foreach (var student in students) { var discipline = new ClassDisciplineDetails { Class = cClass, Student = student, Infractions = new List <Infraction>() }; var discRefferal = disciplineRefferals.FirstOrDefault(x => x.StudentId == student.Id); if (discRefferal != null) { MapperFactory.GetMapper <ClassDiscipline, DisciplineReferral>().Map(discipline, discRefferal); } else { discipline.Date = date; discipline.ClassId = classId; discipline.StudentId = student.Id; } res.Add(discipline); } return(res); } return(null); }
public void ExerciseMapping_ErrorSubPropertyFromModelToViewModel() { //Arrange _model = new Exercise(); _model.Id = 100; _model.Muscle = new Muscle { Id = 342, Name = "Bicep" }; _model.Name = new LocalizedString(); _viewModel = _mapper.GetViewModel(_model); //Act var mapper = new MapperFactory(); var translated = mapper.GetMapper(_model, _viewModel).GetErrorPropertyMappedFor(d => d.Name.French); //Assert Assert.AreEqual("NameFrench", translated); }
public ActionResult Edit(MuscleViewModel viewModel) { if (ModelState.IsValid) { try { ServiceFactory.Muscle.Update(Model); } catch (ConcurrencyException e) { ModelState.AddModelError(string.Empty, e.Message); return(View("Edit", viewModel)); } } var x = ServiceFactory.Muscle.Get(Model); var vm = MapperFactory.GetMapper <Muscle, MuscleViewModel>().GetViewModel(x); return(View("Edit", vm)); }
/// <summary> /// <see cref="IConsumer{TSingle,TMultiple,TPrimaryKey}.Create(TMultiple, bool?, string, string, RequestParameter[])">Create</see> /// </summary> public virtual MultipleCreateResponse Create( TMultiple obj, bool?mustUseAdvisory = null, string zoneId = null, string contextId = null, params RequestParameter[] requestParameters) { if (!RegistrationService.Registered) { throw new InvalidOperationException("Consumer has not registered."); } var url = new StringBuilder(EnvironmentUtils.ParseServiceUrl(EnvironmentTemplate)) .Append($"/{TypeName}s") .Append(HttpUtils.MatrixParameters(zoneId, contextId)) .Append(GenerateQueryParameterString(requestParameters)) .ToString(); string requestBody = SerialiseMultiple(obj); string responseBody = HttpUtils.PostRequest( url, RegistrationService.AuthorisationToken, requestBody, ConsumerSettings.CompressPayload, contentTypeOverride: ContentType.ToDescription(), acceptOverride: Accept.ToDescription(), mustUseAdvisory: mustUseAdvisory); if (log.IsDebugEnabled) { log.Debug("Response from POST request ..."); } if (log.IsDebugEnabled) { log.Debug(responseBody); } createResponseType createResponseType = SerialiserFactory.GetSerialiser <createResponseType>(Accept).Deserialise(responseBody); MultipleCreateResponse createResponse = MapperFactory.CreateInstance <createResponseType, MultipleCreateResponse>(createResponseType); return(createResponse); }
public void SetUp() { //Instancia del mapper ResFlightMapper = MapperFactory.CreateReservationFlightMapper(); //Instancia el DTO flightDTO = new FlightResDTO("", "2019-7-6 23:00", 1, 1, 1); //Instancia el objeto reserva de vuelo entity = new FlightRes("", "2019-7-6 23:00", 1, 1, 1); //Instancia una lista de DTO dtos = new List <FlightResDTO>(); dtos.Add(flightDTO); //Instancia una lsita de entidades entities = new List <FlightRes>(); entities.Add(entity); }
public VardiyaType(MapperFactory factory) { Description = "Vardiyalar"; Field(i => i.VardiyaId); Field(i => i.Aciklama); Field(i => i.Baslangic); Field(i => i.Bitis); Field(i => i.Departman); Field <ListGraphType <PersonelType> >("Personeller", resolve: context => { return(from i in factory.CreateSession <PersonelVardiya>().Data join j in factory.CreateSession <Personel>().Data on i.Personel equals j.PersonelTC where i.Vardiya == context.Source.VardiyaId select new Personel { AdSoyad = j.AdSoyad, Departman = j.Departman, PersonelTC = j.PersonelTC, TurId = j.TurId }); }); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add(new ValidationExceptionFilter()); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSwaggerGen(configuration => { configuration.SwaggerDoc("v1", new Info { Title = "RepositoryExample Api", Version = "v1" }); }); IMapper mapper = MapperFactory.GetInstance(); services.ConfigureIoc(this.Configuration, mapper); }
public ActionResult <IEnumerable <HotelDTO> > Get([FromQuery] int location = -1) { GetHotelsCommand commandHotels = CommandFactory.GetHotelsCommand(); GetHotelsByCityCommand commandByCity = CommandFactory.GetHotelsByCityCommand(location); commandHotels.Execute(); commandByCity.Execute(); var resulthotel = commandHotels.GetResult(); _logger?.LogInformation($"Se obtuvieron los hoteles exitosamente"); var resultcity = commandByCity.GetResult(); _logger?.LogInformation($"Obtenida las ciudades exitosamente por: {location}"); HotelMapper hotelMapper = MapperFactory.createHotelMapper(); return(location == -1 ? hotelMapper.CreateDTOList(resulthotel) : hotelMapper.CreateDTOList(resultcity)); }
public async Task <IActionResult> Create(TopicModel model, bool continueEditing) { if (ModelState.IsValid) { if (!model.IsPasswordProtected) { model.Password = null; } // TODO: (mh) (core) Implement & use mapping extensions. var topic = await MapperFactory.MapAsync <TopicModel, Topic>(model); if (model.WidgetZone != null) { topic.WidgetZone = string.Join(',', model.WidgetZone); } topic.CookieType = (CookieType?)model.CookieType; _db.Topics.Add(topic); await _db.SaveChangesAsync(); var slugResult = await topic.ValidateSlugAsync(model.SeName, true); model.SeName = slugResult.Slug; await _urlService.ApplySlugAsync(slugResult, true); await SaveStoreMappingsAsync(topic, model.SelectedStoreIds); await SaveAclMappingsAsync(topic, model.SelectedCustomerRoleIds); await UpdateLocalesAsync(topic, model); AddCookieTypes(model, model.CookieType); await Services.EventPublisher.PublishAsync(new ModelBoundEvent(model, topic, Request.Form)); NotifySuccess(T("Admin.ContentManagement.Topics.Updated")); return(continueEditing ? RedirectToAction("Edit", new { id = topic.Id }) : RedirectToAction("List")); } // If we got this far something failed. Redisplay form. return(View(model)); }
public UserService(IUserRepository userRepository, IJwtService jwtService) { _userRepository = userRepository; _jwtService = jwtService; _requestMapper = MapperFactory.GetMapper <UserRequestModel, User>(); // kinda hairy, need better mapper _responseMapper = MapperFactory.GetMapper(new MapperConfiguration(cfg => { cfg.CreateMap <User, UserResponseModel>(); cfg.CreateMap <User, UserInfoResponseModel>(); cfg.CreateMap <Task, TaskResponseModel>().ForMember( t => t.User, opt => opt.Ignore() ); cfg.CreateMap <TaskHistory, TaskHistoryResponseModel>().ForMember( t => t.User, opt => opt.Ignore() ); })); }
public async Task <IActionResult> Edit(int id) { var email = await _db.QueuedEmails.FindByIdAsync(id); if (email == null) { return(RedirectToAction(nameof(List))); } var model = new QueuedEmailModel(); await MapperFactory.MapAsync(email, model); model.CreatedOn = _dateTimeHelper.ConvertToUserTime(email.CreatedOnUtc, DateTimeKind.Utc); if (email.SentOnUtc.HasValue) { model.SentOn = _dateTimeHelper.ConvertToUserTime(email.SentOnUtc.Value, DateTimeKind.Utc); } return(View(model)); }
public async Task <IActionResult> Catalog(CatalogSettings catalogSettings, CatalogSettingsModel model) { if (!ModelState.IsValid) { return(View(model)); } ModelState.Clear(); // We need to clear the sitemap cache if MaxItemsToDisplayInCatalogMenu has changed. if (catalogSettings.MaxItemsToDisplayInCatalogMenu != model.MaxItemsToDisplayInCatalogMenu) { // Clear cached navigation model. await _menuService.Value.ClearCacheAsync("Main"); } await MapperFactory.MapAsync(model, catalogSettings); return(NotifyAndRedirect("Catalog")); }
public static IServiceCollection InitializeAutoMapper(this IServiceCollection services) { #region AutoMapper Initialization var mapperFactory = new MapperFactory(); var config = new AutoMapper.MapperConfiguration(cfg => { var profileReg = (Profile)Activator.CreateInstance(typeof(RegistrationViewModelToApplicationUserDTO)); cfg.AddProfile(profileReg); var profileLogin = (Profile)Activator.CreateInstance(typeof(LoginViewModelToApplicationUserDTO)); cfg.AddProfile(profileLogin); }); var mapperBL = config.CreateMapper(); mapperFactory.Mappers.Add("BL", mapperBL); return(services.InitializeAutoMapper(mapperFactory)); #endregion }
public void Create_DtoUser_To_UserAppModel_Mappert_Test() { #region === ARRANGE === MapperFactory mapperFactory = new MapperFactory(); #endregion #region === ACT === var mapper = mapperFactory.Create <DtoUser, UserAppModel>(); #endregion #region === ASSERT === Assert.IsInstanceOfType(mapper, typeof(AbstractMapper <DtoUser, UserAppModel>)); #endregion }
public ActionResult <IEnumerable <LocationDTO> > GetCitiesByCountry([FromRoute] int countryId) { try { GetLocationByIdCommand commandId = CommandFactory.GetLocationByIdCommand(countryId); commandId.Execute(); LocationMapper locationMapper = MapperFactory.createLocationMapper(); GetCitiesByCountryCommand commandIByCountry = CommandFactory.GetCitiesByCountryCommand(countryId); commandIByCountry.Execute(); var result = commandIByCountry.GetResult(); _logger?.LogInformation($"Obtenida las ciudades por pais id {countryId} exitosamente"); return(locationMapper.CreateDTOList(result)); } catch (LocationNotFoundException ex) { _logger?.LogWarning($"Location con id {countryId} no encontrada"); return(NotFound($"Location with id {countryId} not found")); } }
public void DeleteReservationCommandTest() { FlightResDTO flightDTO = new FlightResDTO("", "2019-7-6 23:00", 1, 1, 1); //Crea la entidad por medio del mapper devuelvo del factory ReservationFlightMapper ResFlightMapper = MapperFactory.CreateReservationFlightMapper(); Entity entity = ResFlightMapper.CreateEntity(flightDTO); //Instancia el comando por medio del factory pasandole la entidad al constructor AddReservationFlightCommand command = CommandFactory.CreateAddReservationFlightCommand((FlightRes)entity); //Ejecuta y obtiene el resultado del comando command.Execute(); int id_res = command.GetResult(); //Obtiene comando para borrar DeleteReservationCommand command2 = CommandFactory.CreateDeleteReservationCommand(id_res); command2.Execute(); }
public void Index_Should_Allow_To_Update_Employee_Record() { // arrange var mock = new Mock <IEmployeeRepository>(); mock.Setup(er => er.Get("*****@*****.**")).Returns(MakeTestEmployee()); HomeController controller = new HomeController(mock.Object, null, MapperFactory.GetMapperInstance()); controller.ControllerContext = Helper.CreateControllerContextWithUserClaim("*****@*****.**"); HomeIndexViewModel vm = (controller.Index() as ViewResult).Model as HomeIndexViewModel; // act vm.Name = "UnitTest1"; controller.Index(vm); vm = (controller.Index() as ViewResult).Model as HomeIndexViewModel; //assert Assert.Same("UnitTest1", vm.Name); mock.Verify(er => er.Get(It.IsAny <string>()), Times.Exactly(3)); }
public virtual T Obtener(T entidad) { T entidadEncontrada = null; string sql = $"usp_Get{_nombreTabla}"; IDataParameter[] parameters = { UnitOfWork.CreateParameter("@Id", entidad.Id) }; DataTable table = UnitOfWork.Read(sql, parameters).Tables[0]; if (table.Rows.Count > 0) { MapperFactory.Crear <T>().Map(table.Rows[0]); } return(entidadEncontrada); }
public ActionResult <ModelDTO> GetModelById(int modelId) { _logger?.LogInformation($"Inicio del servicio: [GET] https://localhost:5001/api/models/modelId "); try { GetModelByIdCommand command = CommandFactory.CreateGetModelByIdCommand(modelId); _logger?.LogInformation($" Ejecución del comando "); command.Execute(); ModelMapper modelMapper = MapperFactory.CreateModelMapper(); return(Ok(modelMapper.CreateDTO(command.GetResult()))); } catch (ModelNotFoundException ex) { _logger?.LogWarning("Modelo con Id : " + ex.ModelId + "no encontrado"); return(StatusCode(404, ex.Message + ex.ModelId)); } catch (InternalServerErrorException ex) { _logger?.LogError("Error: " + ex.Ex.Message); return(StatusCode(500, ex.Message)); } catch (Exception) { _logger?.LogError("Error inesperado"); return(StatusCode(400)); } }
public AuditTrailService(IAuditTrailQueryService queryService, ICommandBus commandBus, IAuthenticatedUserContext userContext) { if (queryService == null) { throw new ArgumentException("queryService"); } if (commandBus == null) { throw new ArgumentNullException("commandBus"); } if (userContext == null) { throw new ArgumentNullException(nameof(userContext)); } this.queryService = queryService; this.commandBus = commandBus; this.userContext = userContext; mapperFactory = new MapperFactory(); }
/// <summary> /// Delete a series of Job objects /// </summary> /// <param name="jobs">The job objtect templates of the Jobs to delete, each must have name and id populated. tHe name of all jobs must be the same.</param> /// <param name="zoneId">The zone in which to perform the request.</param> /// <param name="contextId">The context in which to perform the request.</param> /// <returns>A response</returns> public virtual MultipleDeleteResponse Delete(List <Job> jobs, string zoneId = null, string contextId = null) { checkRegistered(); string jobName = checkJobs(jobs, RightType.DELETE, zoneId); List <deleteIdType> deleteIds = new List <deleteIdType>(); foreach (Job job in jobs) { deleteIds.Add(new deleteIdType { id = job.Id.ToString() }); } deleteRequestType request = new deleteRequestType { deletes = deleteIds.ToArray() }; string url = GetURLPrefix(jobName) + HttpUtils.MatrixParameters(zoneId, contextId); string body = SerialiserFactory.GetXmlSerialiser <deleteRequestType>().Serialise(request); string xml = HttpUtils.PutRequest( url, RegistrationService.AuthorisationToken, body, ConsumerSettings.CompressPayload, ServiceType.FUNCTIONAL, "DELETE"); if (log.IsDebugEnabled) { log.Debug("XML from PUT (DELETE) request ..."); } if (log.IsDebugEnabled) { log.Debug(xml); } deleteResponseType updateResponseType = SerialiserFactory.GetXmlSerialiser <deleteResponseType>().Deserialise(xml); MultipleDeleteResponse updateResponse = MapperFactory.CreateInstance <deleteResponseType, MultipleDeleteResponse>(updateResponseType); return(updateResponse); }
public void Setup() { _hotelsController = new HotelsController(null); _insertedHotels = new List <int>(); _hotelentity = HotelBuilder.Create() .WithName("Hotel Cagua") .WithAmountOfRooms(2000) .WithCapacityPerRoom(2) .WithPricePerRoom(200) .WithPhone("04243240208") .WithWebsite("HC.com") .WithStars(2) .LocatedAt(HotelTestSetup.LOCATION_ID) .WithStatus(true) .WithAddressDescription("Calle Los Almendrones") .WithPictureUrl("alguncodigoenbase64") .Build(); HotelMapper _HotelMapper = MapperFactory.createHotelMapper(); _hotel = _HotelMapper.CreateDTO(_hotelentity); }
private static object ConvertValue <TSource>(MemberInfo member, object value) { var values = new Dictionary <string, object>(); values.Add(member.Name, value); var mapper = MapperFactory.CreateMapper(); var instance = mapper.Map <TSource>(values); if (member.MemberType == MemberTypes.Property) { return((member as PropertyInfo).GetValue(instance)); } if (member.MemberType == MemberTypes.Field) { return((member as FieldInfo).GetValue(instance)); } throw new NotSupportedException(member.MemberType.ToString()); }
//TODO : needs testing public async Task <IList <StudentAnnouncementDetails> > GetStudentAnnouncementsForGradingPeriod(int schoolYearId, int studentId, int gradingPeriodId) { var gradingDetailsDashboardTask = ConnectorLocator.GradingConnector.GetStudentGradingDetails(schoolYearId, studentId, gradingPeriodId); var student = ServiceLocator.StudentService.GetById(studentId, schoolYearId); var scores = (await gradingDetailsDashboardTask).Scores; var mapper = MapperFactory.GetMapper <StudentAnnouncement, Score>(); var res = new List <StudentAnnouncementDetails>(); foreach (var score in scores) { var studentAnn = new StudentAnnouncementDetails { Student = student, StudentId = studentId }; mapper.Map(studentAnn, score); res.Add(studentAnn); } return(res); }
internal override IEnumerable <TResult> AdaptResult(string cql, RowSet rs) { IEnumerable <TResult> result; if (!_canCompile) { var mapper = MapperFactory.GetMapperWithProjection <TResult>(cql, rs, _projectionExpression); result = rs.Select(mapper); } else { IEnumerable <TSource> sourceData = _source.AdaptResult(cql, rs); var func = _projectionExpression.Compile(); result = sourceData.Select(func); } var enumerator = result.GetEnumerator(); // Eagerly evaluate the first one in order to fail fast var hasFirstItem = enumerator.MoveNext(); return(YieldFromFirst(enumerator, hasFirstItem)); }
public ActionResult <List <Vehicle> > GetVehicles() { _logger?.LogInformation($"Inicio del servicio: [GET] https://localhost:5001/api/vehicles "); try { GetVehiclesCommand command = CommandFactory.CreateGetVehiclesCommand(); _logger?.LogInformation($" Ejecución del comando "); command.Execute(); VehicleMapper vehicleMapper = MapperFactory.CreateVehicleMapper(); return(Ok(command.GetResult())); } catch (NotVehiclesAvailableException ex) { _logger?.LogWarning(ex.Message); return(StatusCode(404, ex.Message)); } catch (InternalServerErrorException ex) { _logger?.LogError("Error: " + ex.Ex.Message); return(StatusCode(500, ex.Message)); } catch (Exception) { _logger?.LogError("Error inesperado"); return(StatusCode(400)); } }
public async Task <IEnumerable <CarDto> > GetCars(IEnumerable <SearchAttributeDto> searchAttributes) { var carRepository = DataContextManager.CreateRepository <ICarRepository>(); var carQuery = carRepository.GetCars(); carQuery = carQuery.Filter <Car>(searchAttributes.Where(x => x.CarField >= Enums.CarField.RegistrationNumber && x.CarField <= Enums.CarField.Decommissioned).ToList()); var carSpecQuery = carQuery.Select(s => s.CarSpec).AsQueryable() .Filter <CarSpec>(searchAttributes.Where(x => x.CarField >= Enums.CarField.FuelId && x.CarField <= Enums.CarField.HybridDrive).ToList()); var carBusinessQuery = carQuery.Select(s => s.CarBusiness).AsQueryable() .Filter <CarBusiness>(searchAttributes.Where(x => x.CarField >= Enums.CarField.Location && x.CarField <= Enums.CarField.UpdateDate).ToList()); var cars = await carQuery .Where(x => carSpecQuery.Select(s => s.Id).Contains(x.Id) && carBusinessQuery.Select(s => s.Id).Contains(x.Id)) .ToListAsync(); return(MapperFactory.CreateMapper <ICarMapper>().MapCollectionToModel(cars)); }
internal CqlUpdate(Expression expression, ITable table, StatementFactory stmtFactory, PocoData pocoData, MapperFactory mapperFactory) : base(expression, table, stmtFactory, pocoData) { _mapperFactory = mapperFactory; }
public void Setup() { repository = Substitute.For<IFeedbackRepository>(); mapperFactory = Substitute.For<MapperFactory>(); sut = new FeedbackController(repository, mapperFactory); }
public AbstractService(IDataContextManager dataContextManager, IUnityContainer container) { DataContextManager = dataContextManager; MapperFactory = new MapperFactory(container); }
public MapperFactoryTests() { _sut = Setup.MapperFactory(); }