private async Task <string> GetArgumentListWithLocalVariables(Document document, IInvocation invocation, bool generateNamedParameters, SemanticModel semanticModel) { var mappingSourceFinder = LocalScopeMappingSourceFinder.FromScope(semanticModel, invocation.SourceNode, AllowedSymbolsForCompletion); mappingSourceFinder.AllowMatchOnlyByTypeWhenSingleCandidate = true; var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var overloadParameterSets = invocation.GetOverloadParameterSets(semanticModel); if (overloadParameterSets != null) { var mappingEngine = new MappingEngine(semanticModel, syntaxGenerator); var mappingContext = new MappingContext(invocation.SourceNode, semanticModel); var parametersMatch = await MethodHelper.FindBestParametersMatch(mappingSourceFinder, overloadParameterSets, mappingContext).ConfigureAwait(false); if (parametersMatch != null) { var argumentList = await parametersMatch.ToArgumentListSyntaxAsync(mappingEngine, mappingContext, generateNamedParameters).ConfigureAwait(false); var chunks = argumentList.Arguments.Select(a => a.ToString()); return(string.Join(", ", chunks)); } } return(null); }
private void OnLoad(object sender, EventArgs e) { Lumberjack.Debug("Loading window state"); // Set up lighting GL.ShadeModel(ShadingModel.Smooth); GL.Enable(EnableCap.ColorMaterial); // Set up caps GL.Enable(EnableCap.DepthTest); GL.Enable(EnableCap.RescaleNormal); GL.Disable(EnableCap.Texture2D); GL.Disable(EnableCap.CullFace); // Set up blending GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha); // Set background color GL.ClearColor(Color.FromArgb(255, 13, 13, 13)); // Init keyboard to ensure first frame won't NPE _keyboard = Keyboard.GetState(); Lumberjack.Debug("Loading render engine"); _mappingEngine = new MappingEngine(); _renderEngine = new RenderEngine(this, _mappingEngine); _camera = new Camera(); Lumberjack.Debug("Loading world"); _structure = StructureLoader.Load(_args[0]); _renderEngine.LoadStructure(_structure); }
public static async Task <Document> FixInvocationWithParameters(Document document, IInvocation invocation, bool generateNamedParameters, SemanticModel semanticModel, IMappingSourceFinder mappingSourceFinder, CancellationToken cancellationToken) { var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var overloadParameterSets = invocation.GetOverloadParameterSets(semanticModel); if (overloadParameterSets != null) { var mappingContext = new MappingContext(invocation.SourceNode, semanticModel); var mappingEngine = new MappingEngine(semanticModel, syntaxGenerator); var parametersMatch = await MethodHelper.FindBestParametersMatch(mappingSourceFinder, overloadParameterSets, mappingContext).ConfigureAwait(false); if (parametersMatch != null) { var argumentList = await parametersMatch.ToArgumentListSyntaxAsync(mappingEngine, mappingContext, generateNamedParameters).ConfigureAwait(false); return(await document.ReplaceNodes(invocation.SourceNode, invocation.WithArgumentList(argumentList), cancellationToken).ConfigureAwait(false)); } } return(document); }
public RenderEngine(GameWindow window, MappingEngine mappingEngine) { _window = window; _mappingEngine = mappingEngine; _fgJobs = new ConcurrentQueue <IJob>(); _bgJobs = new ConcurrentQueue <IJob>(); _framebuffer = new Framebuffer(8); _framebuffer.Init(window.Width, window.Height); _framebufferUi = new Framebuffer(1); _framebufferUi.Init(window.Width, window.Height); _texRandom = LoadGlTexture(EmbeddedFiles.random); _shaderModel = new ShaderProgram(EmbeddedFiles.fs_terrain, EmbeddedFiles.vs_terrain); _shaderModel.Init(); _shaderScreen = new ShaderProgram(EmbeddedFiles.fs_screen, EmbeddedFiles.vs_screen); _shaderScreen.Init(); _workerHandle = new EventWaitHandle(false, EventResetMode.ManualReset); LightPosition = new Vector3(0.25f, 1, 0.25f); Chunks = new Chunk[0]; CreateScreenVao(); _texAtlas = new BlockAtlas(mappingEngine, 32); }
/// <summary> /// Used to setup AutoMapper /// </summary> /// <param name="additionalProfiles">These profiles will override any existing mappings in an additive manner. Base and ProjectTo are applied automatically.</param> /// <exception cref="AutoMapperConfigurationException">Thrown the mapping configuration is invalid - check the logs</exception> public static void InitializeMappers(params Profile[] additionalProfiles) { if (!hasInitialized) { hasInitialized = true; } else { throw new AutoMapperConfigurationException("InitializeMappers should only be called once during the lifetime of an application."); } // Setup Mapper Mapper.AddProfile(Api); if (additionalProfiles != null) { foreach (Profile additionalProfile in additionalProfiles) { Mapper.AddProfile(additionalProfile); } } // Verify Mapper configuration Mapper.AssertConfigurationIsValid(); // Setup ProjectToMapper ConfigurationStore getAllConfig = CreateConfiguration(); ApiProjectToMapper = CreateMapper(getAllConfig); getAllConfig.AddProfile(Api); getAllConfig.AddProfile(ApiProjectTo); }
public CollectionJsonMediaTypeFormatter(ICollectionSettings <T> collectionSettings, MappingEngine mappingEngine) { _collectionSettings = collectionSettings; _mappingEngine = mappingEngine; SupportedMediaTypes.Clear(); SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.collection+json")); }
protected override ParentDto ConvertCore(int childId) { ParentModel parentModel = _parentModels[childId]; MappingEngine mappingEngine = (MappingEngine)Mapper.Engine; return(mappingEngine.Map <ParentModel, ParentDto>(parentModel)); }
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)); }
public TDestination Map(TSource sourceItem) { using (var mappingEngine = new MappingEngine(_config)) { return(mappingEngine.Map <TSource, TDestination>(sourceItem)); } }
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()); }
/// <summary> /// Test to map to XML - needs to override in implemented class to assign TestMethod due to MSTest /// </summary> public virtual void ShouldMapToXml() { // Must go via the engine to get all the namespaces registered var candidate = MappingEngine.CreateDocument(ExpectedDto); CheckXml(ExpectedXml, candidate); }
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 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); } }
private static async Task <Document> CreateMappingLambda(Document document, InvocationExpressionSyntax invocation, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var methodInvocationSymbol = semanticModel.GetSymbolInfo(invocation.Expression); var mappingOverload = methodInvocationSymbol.CandidateSymbols.OfType <IMethodSymbol>().FirstOrDefault(IsMappingMethod); if (mappingOverload == null) { return(document); } var sourceElementType = ((INamedTypeSymbol)mappingOverload.Parameters[0].Type).TypeArguments[0]; var targetElementType = GetExpressionType(semanticModel, invocation); if (targetElementType == null) { return(document); } var contextAssembly = semanticModel.FindContextAssembly(invocation); var mappingEngine = new MappingEngine(semanticModel, syntaxGenerator, contextAssembly); var mappingLambda = mappingEngine.CreateMappingLambda("x", sourceElementType, targetElementType, new MappingPath()); return(await document.ReplaceNodes(invocation, invocation.WithArgumentList(SyntaxFactory.ArgumentList().AddArguments(SyntaxFactory.Argument((ExpressionSyntax)mappingLambda))), cancellationToken)); }
private static void RunMappingEngineNestedResultsBenchmark() { var mapping = JsonMappingBuilder.Root() .Property("Version", "2.0") .QueryWithNesting("Results", @"select c.id as cid, c.sname,'2017-03-01' as LastUpdate, c.fname, c.BDAY, c.ADR_STREET, c.ADR_CITY, i.id as iid, i.inv_date, i.amount, o.article, o.id as oid, oi.item_name,oi.price, oi.id as oiid from customer c left join invoices i on c.id = i.customer_id left join orders o on c.id = o.customer_id left join order_items oi on o.id = oi.order_id ", //where amount>${context:min_amount:Int32} // Id Column "cid" , cfg1 => cfg1 .Column("Id", "cid") .Column("SName") .Column("LastUpdate") .Column("Birthday", "BDAY") .Object("Address", cfg2 => cfg2 .Column("Street", "ADR_STREET") .Column("City", "ADR_CITY") ) .NestedResults("Invoices", "iid", cfg2 => cfg2 .Column("InvoiceId", "iid") .Column("Inv_Date") .Column("TotalAmount", "amount") ) .NestedResults("Orders", "oid", cfg2 => cfg2 .Column("OrderId", "oid") .Column("ArticleName", "article") .NestedResults("Items", "oiid", cfg3 => cfg3 .Column("id", "oiid") .Column("Item_Name") .Column("Price") ) ) ) //.Property("Last-Update", "2010-10-10") .Result; var sw = new Stopwatch(); sw.Start(); using (var engine = new MappingEngine(() => new NpgsqlConnection("Server=localhost;User Id=postgres;" + "Password=admin;Database=test;"), mapping)) { using (var ms = new FileStream("out-sql2json-nested.json", FileMode.Create)) { var context = new Dictionary <string, object>(); // context.Add("min_amount", 10); engine.ExecuteMapping(ms, context, false); } } sw.Stop(); Console.WriteLine("RunMappingEngineNestedResultsBenchmark time elapsed: " + sw.ElapsedMilliseconds); }
public IMappingEngine CreateMapper <TProfile>() where TProfile : Profile, new() { var config = new MapperConfiguration(cfg => cfg.AddProfile <TProfile>()); var engine = new MappingEngine(config, config.CreateMapper()); return(engine); }
public IEnumerable <SyntaxNode> GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator, SemanticModel semanticModel) { var mappingEngine = new MappingEngine(semanticModel, generator, methodSymbol.ContainingAssembly); var sourceFinder = new LocalScopeMappingSourceFinder(semanticModel, methodSymbol.Parameters); var targets = ObjectHelper.GetFieldsThaCanBeSetPrivately(methodSymbol.ContainingType); return(mappingEngine.MapUsingSimpleAssignment(targets, new SingleSourceMatcher(sourceFinder))); }
private static async Task <(MappingEngine, SemanticModel)> CreateMappingEngine(Document document, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var mappingEngine = await MappingEngine.Create(document, cancellationToken).ConfigureAwait(false); return(mappingEngine, semanticModel); }
private static async Task <(MappingEngine, SemanticModel)> CreateMappingEngine(Document document, SyntaxNode node, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken); var mappingEngine = await MappingEngine.Create(document, cancellationToken); return(mappingEngine, semanticModel); }
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 IEnumerable <SyntaxNode> GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator, SemanticModel semanticModel) { var mappingEngine = new MappingEngine(semanticModel, generator, methodSymbol.ContainingAssembly); var targetType = methodSymbol.ReturnType; var newExpression = mappingEngine.MapExpression((ExpressionSyntax)generator.ThisExpression(), methodSymbol.ContainingType, targetType); return(new[] { generator.ReturnStatement(newExpression).WithAdditionalAnnotations(Formatter.Annotation) }); }
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)); }
public UnitTestBase() { _map = new MappingEngine(BootStrapMapper.BootstrapMapper()); _context = new MockResidentDBContext(); _logger = new LoggerManager(); _repo = new ResidentRepository(_context, _map, _logger); _service = new ResidentService(_repo, _logger); }
protected override void Establish_context() { var configuration = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers); _mapper = new MappingEngine(configuration); var parentMapping = configuration.CreateMap <Source, Target>(); parentMapping.ForMember(dest => dest.Value, opt => opt.MapFrom(s => (TargetEnumValue)s.Value)); }
private static async Task <(MappingEngine, SemanticModel)> CreateMappingEngine(Document document, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var mappingEngine = new MappingEngine(semanticModel, syntaxGenerator); return(mappingEngine, semanticModel); }
public IEnumerable <SyntaxNode> GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator, SemanticModel semanticModel, MappingContext mappingContext) { var mappingEngine = new MappingEngine(semanticModel, generator); var sourceFinder = new LocalScopeMappingSourceFinder(semanticModel, methodSymbol.Parameters); var targets = MappingTargetHelper.GetFieldsThaCanBeSetFromConstructor(methodSymbol.ContainingType, mappingContext); return(mappingEngine.MapUsingSimpleAssignment(targets, new SingleSourceMatcher(sourceFinder), mappingContext)); }
public IEnumerable <SyntaxNode> GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator, SemanticModel semanticModel) { var mappingEngine = new MappingEngine(semanticModel, generator, methodSymbol.ContainingAssembly); var source = methodSymbol.Parameters[0]; var sourceFinder = new ObjectMembersMappingSourceFinder(source.Type, generator.IdentifierName(source.Name), generator); var targets = ObjectHelper.GetFieldsThaCanBeSetFromConstructor(methodSymbol.ContainingType); return(mappingEngine.MapUsingSimpleAssignment(targets, new SingleSourceMatcher(sourceFinder))); }
public ProjectRepository(string connectionString) { var store = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers); store.AssertConfigurationIsValid(); _engine = new MappingEngine(store); CreateMaps(store); _context = new DependencyGraphContext(connectionString); }
public JsonMapper() { var configurationStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers); this.mapper = new MappingEngine(configurationStore); configurationStore.CreateMap <Feature, JsonFeature>() .ForMember(t => t.FeatureElements, opt => opt.ResolveUsing(s => s.FeatureElements)) .AfterMap( (sourceFeature, targetFeature) => { foreach (var featureElement in targetFeature.FeatureElements.ToArray()) { featureElement.Feature = targetFeature; } }); configurationStore.CreateMap <Example, JsonExample>(); configurationStore.CreateMap <Keyword, JsonKeyword>(); configurationStore.CreateMap <Scenario, JsonScenario>() .ForMember(t => t.Feature, opt => opt.Ignore()); configurationStore.CreateMap <ScenarioOutline, JsonScenarioOutline>() .ForMember(t => t.Feature, opt => opt.Ignore()); configurationStore.CreateMap <Comment, JsonComment>(); configurationStore.CreateMap <Step, JsonStep>() .ForMember(t => t.StepComments, opt => opt.UseValue(new List <JsonComment>())) .ForMember(t => t.AfterLastStepComments, opt => opt.UseValue(new List <JsonComment>())) .AfterMap( (sourceStep, targetStep) => { this.mapper.Map(sourceStep.Comments.Where(o => o.Type == CommentType.StepComment), targetStep.StepComments); this.mapper.Map(sourceStep.Comments.Where(o => o.Type == CommentType.AfterLastStepComment), targetStep.AfterLastStepComments); } ); configurationStore.CreateMap <Table, JsonTable>(); configurationStore.CreateMap <TestResult, JsonTestResult>().ConstructUsing(ToJsonTestResult); configurationStore.CreateMap <TableRow, JsonTableRow>() .ConstructUsing(row => new JsonTableRow(row.Cells.ToArray())); configurationStore.CreateMap <IFeatureElement, IJsonFeatureElement>().ConvertUsing( sd => { var scenario = sd as Scenario; if (scenario != null) { return(this.mapper.Map <JsonScenario>(scenario)); } var scenarioOutline = sd as ScenarioOutline; if (scenarioOutline != null) { return(this.mapper.Map <JsonScenarioOutline>(scenarioOutline)); } throw new ArgumentException("Only arguments of type Scenario and ScenarioOutline are supported."); }); }
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 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); }