public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { var mapper = _mappingEngine.ConfigurationProvider as ConfigurationStore; mapper.CreateMap <IList <Data>, T>().ConvertUsing(list => { var instance = Activator.CreateInstance <T>(); var properties = typeof(T).GetProperties(); foreach (var property in properties) { var data = list.First(d => String.Equals(d.Name, property.Name, StringComparison.InvariantCultureIgnoreCase)); var type1 = property.PropertyType; if (type1 == typeof(Int64)) { property.SetValue(instance, int.Parse(data.Value)); } else if (type1 == typeof(Int32)) { property.SetValue(instance, int.Parse(data.Value)); } else { property.SetValue(instance, data.Value); } } return(instance); }); var taskSource = new TaskCompletionSource <object>(); try { var result = base.ReadFromStreamAsync(typeof(ReadDocument), readStream, content, formatterLogger).Result as ReadDocument; if (typeof(TypedReadDocument <T>) == type) { var document = new TypedReadDocument <T>(); document.Collection.Links = result.Collection.Links; document.Collection.Items = result.Collection.Items.Select( item => { return(new Item <T>() { Data = _mappingEngine.Map <IList <Data>, T>(item.Data), Href = item.Href, Links = item.Links }); }) .ToList(); taskSource.SetResult(document); } } catch (Exception e) { taskSource.SetException(e); } return(taskSource.Task); }
// TODO: The problem is that projects and packages never get deleted // We can either truncate the tables or remove orphants before each run. public void SaveProject(Project project) { SqlStorage.Project sqlProject = _engine.Map <SqlStorage.Project>(project); sqlProject = GetOrAddEntity(_context.Projects, sqlProject, m => m.Name == project.Name); sqlProject.Packages.Clear(); // This project can have fewer nugets than project in db foreach (var nugetPackage in project.Packages) { SqlStorage.Package sqlPackage = _engine.Map <SqlStorage.Package>(nugetPackage); sqlPackage = GetOrAddEntity(_context.Packages, sqlPackage, m => m.Name == nugetPackage.Name && m.Version == nugetPackage.Version); // There can be more than one NuGet version sqlPackage.Projects.Add(sqlProject); } _context.SaveChanges(); }
// SaveState wipes out graph but keeps DatabaseObjects because: // TODO: We could try updating modified vertices only. public void SaveState(DatabaseObjectsGraph dg) { DatabaseObject[] symbolTable = dg.CreateMemento().State; int[][] jaggedArray = dg.Digraph.CreateMemento().State; // Save using (var ctx = new DependencyGraphContext(_connectionString)) { ctx.Database.ExecuteSqlCommand("TRUNCATE TABLE DatabaseObjectsGraph;"); foreach (var databaseObject in symbolTable) { switch (databaseObject.ObjectState) { case ObjectState.VertexAdded: var sqlStorageDatabaseObject = _engine.Map <SqlStorage.DatabaseObject>(databaseObject); ctx.DatabaseObjects.Add(sqlStorageDatabaseObject); break; case ObjectState.PropertiesModified: // Properties can be addedd, deleted or change values var objectInDatabase = ctx.DatabaseObjects.SingleOrDefault(f => f.FullyQualifiedName == databaseObject.FullyQualifiedName); if (objectInDatabase == null) { // We can't add a property to an object that hasn't been saved yet. throw new ArgumentException(nameof(objectInDatabase)); } objectInDatabase.Properties.Clear(); foreach (var property in databaseObject.Properties) { objectInDatabase.Properties.Add(DatabaseObjectConverter.Convert(property)); } ctx.Entry(objectInDatabase).State = EntityState.Modified; break; } } for (int i = 0; i < jaggedArray.Length; i++) { var json = JsonConvert.SerializeObject(jaggedArray[i]); ctx.DatabaseObjectVertices.Add(new DatabaseObjectVertex() { VertexId = i, AdjacencyListJson = json }); } ctx.SaveChanges(); } }
protected override List <ChildDto> ConvertCore(int childId) { List <ChildModel> childModels = _childModels.Where(x => x.Parent.ID == childId).ToList(); MappingEngine mappingEngine = (MappingEngine)Mapper.Engine; return(mappingEngine.Map <List <ChildModel>, List <ChildDto> >(childModels)); }
protected override ParentDto ConvertCore(int childId) { ParentModel parentModel = _parentModels[childId]; MappingEngine mappingEngine = (MappingEngine)Mapper.Engine; return(mappingEngine.Map <ParentModel, ParentDto>(parentModel)); }
public TDestination Map(TSource sourceItem) { using (var mappingEngine = new MappingEngine(_config)) { return(mappingEngine.Map <TSource, TDestination>(sourceItem)); } }
public override void Initialize() { base.Initialize(); if (!TestContext.Properties.Contains("cached")) { throw new ArgumentException("cached"); } bool cached = Boolean.Parse((string)TestContext.Properties["cached"]); if (!TestContext.Properties.Contains("jskrId")) { throw new ArgumentException("jskrId"); } jskrId = long.Parse((string)TestContext.Properties["jskrId"]); cachedModel = cached ? new TransitionJobseekerDetailsModel() : null; cacheService.Setup(c => c.TryGet(It.IsAny <KeyModel>(), out cachedModel)).Returns(cached); //setup wcf call if (!cached) { searchResponse = new TransitionJobseekerDetailsResponse(); responseModel = MappingEngine.Map <TransitionJobseekerDetailsModel>(searchResponse); mappings.Setup(m => m.Map <TransitionJobseekerDetailsResponse, TransitionJobseekerDetailsModel>(searchResponse)).Returns(responseModel); } }
public TDestination Map<TSource, TDestination>(TSource item) where TSource : class { return item == null ? default(TDestination) : _mappingEngine.Map<TSource, TDestination>(item); }
public void SearchTestWcfThrowsFaultExceptionThrowsServiceValidationException() { //Arrange var exception = new FaultException(new FaultReason("reason"), new FaultCode("code")); var inModel = new JobseekerModel { DateOfBirth = DateTime.Now, GivenName = "GLENN", Surname = "SUFONG", Gender = "M" }; var request = MappingEngine.Map <RegistrationSearchRequest>(inModel); var searchResultItem = new RegistrationSearchResultItem { JobSeekerId = 3187026003, CRN = "205882473X", Surname = "SUFONG", GivenName = "GLENN", Gender = "M", DateOfBirth = DateTime.Now }; var response = new RegistrationSearchResponse { RegistrationSearchResultItem = (new List <RegistrationSearchResultItem> { searchResultItem }).ToArray() }; var outModel = MappingEngine.Map <IEnumerable <JobseekerModel> >(response.RegistrationSearchResultItem); _mockMappingEngine.Setup(m => m.Map <RegistrationSearchRequest>(inModel)).Returns(request); _mockRegWcf.Setup(m => m.Search(request)).Throws(exception); _mockMappingEngine.Setup(m => m.Map <IEnumerable <JobseekerModel> >(response.RegistrationSearchResultItem)).Returns(outModel); //Act SystemUnderTest().Search(inModel); }
public void SearchTest() { // Arrange var inModel = new JobseekerModel { DateOfBirth = DateTime.Now, GivenName = "GLENN", Surname = "SUFONG", Gender = "M" }; var request = MappingEngine.Map <RegistrationSearchRequest>(inModel); var searchResultItem = new RegistrationSearchResultItem { JobSeekerId = 3187026003, CRN = "205882473X", Surname = "SUFONG", GivenName = "GLENN", Gender = "M", DateOfBirth = DateTime.Now }; var response = new RegistrationSearchResponse { RegistrationSearchResultItem = (new List <RegistrationSearchResultItem> { searchResultItem }).ToArray() }; var outModel = MappingEngine.Map <JobseekerModel>(response); _mockMappingEngine.Setup(m => m.Map <RegistrationSearchRequest>(inModel)).Returns(request); _mockRegWcf.Setup(m => m.Search(request)).Returns(response); _mockMappingEngine.Setup(m => m.Map <JobseekerModel>(response)).Returns(outModel); // Act var result = SystemUnderTest().Search(inModel); //Assert Assert.IsTrue(result.DuplicateJobseekers.Count() > 0); Assert.IsTrue(result.DuplicateJobseekers.ElementAt(0).JobSeekerId == 3187026003); _mockMappingEngine.Verify(m => m.Map <RegistrationSearchRequest>(inModel), Times.Once()); _mockRegWcf.Verify(m => m.Search(request), Times.Once()); _mockMappingEngine.Verify(m => m.Map <JobseekerModel>(response), Times.Once()); }
public void ShouldMapToNewISet() { new PlatformSpecificMapperRegistryOverride().Initialize(); var config = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers); config.CreateMap <SourceWithIEnumerable, TargetWithISet>() .ForMember(dest => dest.Stuff, opt => opt.MapFrom(src => src.Stuff.Select(s => s.Value))); config.AssertConfigurationIsValid(); var engine = new MappingEngine(config); var source = new SourceWithIEnumerable { Stuff = new[] { new TypeWithStringProperty { Value = "Microphone" }, new TypeWithStringProperty { Value = "Check" }, new TypeWithStringProperty { Value = "1, 2" }, new TypeWithStringProperty { Value = "What is this?" } } }; var target = engine.Map <SourceWithIEnumerable, TargetWithISet>(source); }
public ParentDto Convert(ResolutionContext resolutionContext) { int childId = (int)resolutionContext.SourceValue; ParentModel parentModel = _parentModels[childId]; MappingEngine mappingEngine = (MappingEngine)Mapper.Engine; return(mappingEngine.Map <ParentModel, ParentDto>(resolutionContext, parentModel)); }
public List <ChildDto> Convert(ResolutionContext resolutionContext) { int childId = (int)resolutionContext.SourceValue; List <ChildModel> childModels = _childModels.Where(x => x.Parent.ID == childId).ToList(); MappingEngine mappingEngine = (MappingEngine)Mapper.Engine; return(mappingEngine.Map <List <ChildModel>, List <ChildDto> >(resolutionContext, childModels)); }
private Database CollectDatabase(string databaseName) { if (!_server.Databases.Contains(databaseName)) { throw new ArgumentException(nameof(databaseName)); } var db = _server.Databases[databaseName]; var dbToReturn = _engine.Map <Database>(db); foreach (Microsoft.SqlServer.Management.Smo.StoredProcedure storedProcedure in db.StoredProcedures) { if (!storedProcedure.IsSystemObject) { dbToReturn.StoredProcedures.Add(_engine.Map <StoredProcedure>(storedProcedure)); } } return(dbToReturn); }
public async Task <ICalendarItemCreateResult> CreateAsync(string summary, DateTime startDateTime, DateTime endDateTime, List <PersonEvent> people, string description = "", double lattitude = 0.0, double longitude = 0.0, string locationText = "", string recurrenceRule = "", string range = null, bool isAllDay = false, string eventId = null, string activityId = null) { // Create json to post var jitem = new JCalendarItemCreate() { Summary = summary ?? "", ActivityId = activityId ?? "", StartDateTime = startDateTime.ToISO8601(), EndDateTime = endDateTime.ToISO8601(), Description = description, EventId = eventId, IsAllDay = isAllDay, Range = range, Location = new JLocation() { Lattitude = lattitude, Longitude = longitude }, RecurrenceRule = recurrenceRule, LocationText = "", People = people.Select(person => MappingEngine.Map <JEventPerson>(person)).ToList() }; // Post using (var client = Settings.HttpClientFactory.Create()) { HttpResponseMessage response = await client.PostAsJsonAsync(Endpoint, jitem); response.EnsureSuccessStatusCode(); // Read response var jresult = await response.Content.ReadAsAsync <JCalendarItemCreateResult>(); // Map return(MappingEngine.Map <CalendarItemCreateResult>(jresult)); } }
/// <summary> /// Transform an entity to data transfer object. /// </summary> /// <param name="entity">Entity used as source.</param> /// <param name="mapperMaker">Caller for function with customized mapping expression.</param> /// <returns>Data transfer object transformed by configured mapping expression.</returns> /// <typeparam name="TCustom">Tipo customizado para mapeamento.</typeparam> protected T CreateTransfer <TCustom>(TCustom entity, Func <IConfiguration, IMappingExpression <TCustom, T> > mapperMaker) { T result; var configuration = MapperUtil.CreateDefaultConfiguration(); mapperMaker(configuration); var mappingEngine = new MappingEngine(configuration); result = mappingEngine.Map <TCustom, T>(entity); return(result); }
/// <summary> /// Same as <seealso cref="CreateTransfer"/>, but for collection. /// </summary> /// <param name="entities">Collection used as source.</param> /// <param name="mapperMaker">Caller for function with customized mapping expression.</param> /// <returns>Transformed collection.</returns> /// <typeparam name="TCustom">Custom type for source.</typeparam> protected T[] CreateArrayTransfer <TCustom>(TCustom[] entities, Func <IConfiguration, IMappingExpression <TCustom, T> > mapperMaker) { T[] result; var configuration = MapperUtil.CreateDefaultConfiguration(); mapperMaker(configuration); var mappingEngine = new MappingEngine(configuration); result = mappingEngine.Map <TCustom[], T[]>(entities); return(result); }
public override void Initialize() { base.Initialize(); if (!TestContext.Properties.Contains("cached")) { throw new ArgumentException("cached"); } bool cached = Boolean.Parse((string)TestContext.Properties["cached"]); string siteCode = TestContext.Properties.Contains("siteCode") ? (string)TestContext.Properties["siteCode"] : String.Empty; searchModel = new ProviderInformationSearchModel() { SiteCode = siteCode }; searchRequest = MappingEngine.Map <ProviderInformationRequest>(searchModel); mappings.Setup(m => m.Map <ProviderInformationRequest>(searchModel)).Returns(searchRequest); mappings.Setup(m => m.Map <ProviderInformationModel>(It.IsAny <ProviderInformationModel>())).Returns <ProviderInformationModel>(m => m); cachedModel = cached ? new ProviderInformationModel() { NominalJobseekerList = new List <NominalJobseekerListItem>() } : null; var list = new List <ProviderInformationModel> { cachedModel }; cacheService.Setup(c => c.TryGet(It.IsAny <KeyModel>(), out list)).Returns(cached); //setup wcf call if (!cached) { searchResponse = new ProviderInformationResponse() { NominalJobseekers = new List <NominalJobseekerItem>().ToArray() }; responseModel = MappingEngine.Map <ProviderInformationModel>(searchResponse); mappings.Setup(m => m.Map <ProviderInformationResponse, ProviderInformationModel>(searchResponse)).Returns(responseModel); } }
public void should_inherit_base_beforemap() { // arrange var source = new Class{ Prop = "test" }; var configurationProvider = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers()); configurationProvider .CreateMap<BaseClass, BaseDto>() .BeforeMap((s, d) => d.DifferentProp = s.Prop) .Include<Class, Dto>(); configurationProvider.CreateMap<Class, Dto>(); var mappingEngine = new MappingEngine(configurationProvider); // act var dest = mappingEngine.Map<Class, Dto>(source); // assert Assert.AreEqual("test", dest.DifferentProp); }
public async Task <Activity> GetAsync(string id) { // Guard if (string.IsNullOrEmpty(id)) { throw new ApplicationException("id cannot be null or empty - use GetAll if getting collection"); } // Create the Url var url = Endpoint + "/" + id; // Get using (var client = Settings.HttpClientFactory.Create()) { // Read var response = await client.GetAsync(url); // Guard if (response.StatusCode == HttpStatusCode.NotFound) { return(null); } response.EnsureSuccessStatusCode(); // Convert var json = await response.Content.ReadAsStringAsync(); var jo = JObject.Parse(json); var jresult = jo.SelectToken("activity", false).ToObject <JActivity>(); // Map return(MappingEngine.Map <Activity>(jresult)); } }
protected override void Configure() { // T == IDto var store = _engine.ConfigurationProvider as ConfigurationStore; store.CreateMap <T, List <Data> >().ConstructUsing(MapDtoToListOfData <T>); store.CreateMap <T, Item>() // TODO: Self link is Href of Item //.ForMember(c=>c.Href,mapper=>mapper.ResolveUsing(arg => throw new NotImplementedException();)) .ForMember(c => c.Data, mapper => mapper.ResolveUsing(_engine.Map <T, List <Data> >)) .ForMember(c => c.Links, mapper => mapper.ResolveUsing <LinkResolver <T> >()).AfterMap((dto, item) => { item.Href = item.Links.FirstOrDefault(l => l.Rel == "Self").Href; item.Links.Remove(item.Links.FirstOrDefault(l => l.Rel == "Self")); }); store.CreateMap <T, Collection>() .ForMember(c => c.Items, mapper => mapper.ResolveUsing((T dto) => { var items = new List <Item> { _engine.Map <T, Item>(dto) }; return(items); })); // TODO: should be collection link resolver -> idea: query all controllers (cached) //.ForMember(c => c.Links, mapper => mapper.ResolveUsing<LinkResolver<T>>()); store.CreateMap <IEnumerable <T>, Collection>() .ForMember(c => c.Items, mapper => mapper.ResolveUsing(enumerable => enumerable.Select(_engine.Map <T, Item>))); }
public void should_inherit_base_aftermap() { // arrange var source = new Class { Prop = "test" }; var configurationProvider = new ConfigurationStore(new TypeMapFactory(), MapperRegistryOverride.AllMappers()); configurationProvider .CreateMap <BaseClass, BaseDto>() .AfterMap((s, d) => d.DifferentProp = s.Prop) .Include <Class, Dto>(); configurationProvider.CreateMap <Class, Dto>(); var mappingEngine = new MappingEngine(configurationProvider); // act var dest = mappingEngine.Map <Class, Dto>(source); // assert "test".ShouldEqual(dest.DifferentProp); }
public virtual BaseResponse <T> Get <S, T>(Func <S, bool> where, ConfigurationStore mapperConfig = null) where S : class where T : class { BaseResponse <T> response = new BaseResponse <T>(); var findItem = _unitOfWork.GetRepository <S>().dbSet.FirstOrDefault(where); if (findItem != null) { if (mapperConfig == null) { Mapper.CreateMap <S, T>(); response.Data = Mapper.Map <T>(findItem); } else { var engine = new MappingEngine(mapperConfig); response.Data = engine.Map <T>(findItem); engine.Dispose(); } } return(response); }
public void ShouldMapToNewISet() { var config = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers()); config.CreateMap<SourceWithIEnumerable, TargetWithISet>() .ForMember(dest => dest.Stuff, opt => opt.MapFrom(src => src.Stuff.Select(s => s.Value))); config.AssertConfigurationIsValid(); var engine = new MappingEngine(config); var source = new SourceWithIEnumerable { Stuff = new[] { new TypeWithStringProperty { Value = "Microphone" }, new TypeWithStringProperty { Value = "Check" }, new TypeWithStringProperty { Value = "1, 2" }, new TypeWithStringProperty { Value = "What is this?" } } }; var target = engine.Map<SourceWithIEnumerable, TargetWithISet>(source); }
public void ShouldMapOneToTwo() { var config = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers()); config.CreateMap <One, Two>(); config.CreateMap <IEnumerable <string>, IEnumerable <Item> >().ConvertUsing <StringToItemConverter>(); config.AssertConfigurationIsValid(); var engine = new MappingEngine(config); var one = new One { Stuff = new List <string> { "hi", "", "mom" } }; var two = engine.Map <One, Two>(one); two.ShouldNotBeNull(); two.Stuff.Count().ShouldEqual(2); }
public async Task <Activities> GetAllAsync(DateTime?since = null) { // Create the Url var url = Endpoint + "/"; if (since != null) { url = url + "?since=" + since.Value.ToISO8601(); } // Get using (var client = Settings.HttpClientFactory.Create()) { // Read var response = await client.GetAsync(url); // Guard if (response.StatusCode == HttpStatusCode.NotFound) { return(null); } response.EnsureSuccessStatusCode(); // Convert var jresult = await response.Content.ReadAsAsync <JActivities>(); // And we're out of here return(MappingEngine.Map <Activities>(jresult)); } }
public virtual BaseResponse <IList <T> > Query <S, T>(BaseRequest request, Func <IQueryable <S>, IQueryable <S> > whereAndOrderBy, ConfigurationStore mapperConfig = null) where S : class { BaseResponse <IList <T> > response = new BaseResponse <IList <T> >(); var q = from m in _unitOfWork.GetRepository <S>().dbSet select m; if (whereAndOrderBy != null) { q = whereAndOrderBy(q); } response.RecordsCount = q.Count(); List <S> list = null; if (request != null && request.PageSize > 0) { list = q.Skip((request.CurrentPage - 1) * request.PageSize).Take(request.PageSize).ToList(); response.PagesCount = GetPagesCount(request.PageSize, response.RecordsCount); } else { list = q.ToList(); } if (mapperConfig == null) { Mapper.CreateMap <S, T>(); response.Data = Mapper.Map <IList <T> >(list); } else { var engine = new MappingEngine(mapperConfig); response.Data = engine.Map <IList <T> >(list); engine.Dispose(); } return(response); }
protected override void Because_of() { _target = _mapper.Map <Target>(new Source { Value = SourceEnumValue.Mule }); }