public void SuccessMatch()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new SourceSystemService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            // Domain details
            var start = new DateTime(1999, 12, 31);
            var finish = new DateTime(2020, 1, 1);
            var system = new SourceSystem { Name = "Endur" };
            var mapping = new SourceSystemMapping
            {
                System = system,
                MappingValue = "A"
            };
            var sourcesystem = new SourceSystem
            {
                Id = 1,
                Validity = new DateRange(start, finish)
            };
            //SourceSystem.AddDetails(details);
            sourcesystem.ProcessMapping(mapping);

            // Contract details
            var identifier = new EnergyTrading.Mdm.Contracts.MdmId
            {
                SystemName = "Endur",
                Identifier = "A"
            };
            var cDetails = new EnergyTrading.Mdm.Contracts.SourceSystemDetails();

            mappingEngine.Setup(x => x.Map<SourceSystemMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping)).Returns(identifier);
            mappingEngine.Setup(x => x.Map<SourceSystem, EnergyTrading.Mdm.Contracts.SourceSystemDetails>(sourcesystem)).Returns(cDetails);
            validatorFactory.Setup(x => x.IsValid(It.IsAny<MappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);

            var list = new List<SourceSystemMapping> { mapping };
            repository.Setup(x => x.Queryable<SourceSystemMapping>()).Returns(list.AsQueryable());

            var request = new MappingRequest { SystemName = "Endur", Identifier = "A", ValidAt = SystemTime.UtcNow(), Version = 1 };

            // Act
            var response = service.Map(request);
            var candidate = response.Contract;

            // Assert
            mappingEngine.Verify(x => x.Map<SourceSystemMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping));
            mappingEngine.Verify(x => x.Map<SourceSystem, EnergyTrading.Mdm.Contracts.SourceSystemDetails>(sourcesystem));
            repository.Verify(x => x.Queryable<SourceSystemMapping>());
            Assert.IsNotNull(candidate, "Contract null");
            Assert.AreEqual(2, candidate.Identifiers.Count, "Identifier count incorrect");
            // NB This is order dependent
            Assert.AreSame(identifier, candidate.Identifiers[1], "Different identifier assigned");
            Assert.AreSame(cDetails, candidate.Details, "Different details assigned");
            Assert.AreEqual(start, candidate.MdmSystemData.StartDate, "Start date differs");
            Assert.AreEqual(finish, candidate.MdmSystemData.EndDate, "End date differs");
        }
        public void UnsuccessfulMatchReturnsNotFound()
        {
            // Arrange
            var validatorFactory = new Mock <IValidatorEngine>();
            var mappingEngine    = new Mock <IMappingEngine>();
            var repository       = new Mock <IRepository>();
            var searchCache      = new Mock <ISearchCache>();
            var service          = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            var list = new List <LocationMapping>();

            repository.Setup(x => x.Queryable <LocationMapping>()).Returns(list.AsQueryable());
            validatorFactory.Setup(x => x.IsValid(It.IsAny <MappingRequest>(), It.IsAny <IList <IRule> >())).Returns(true);

            var request = new MappingRequest {
                SystemName = "Endur", Identifier = "A", ValidAt = SystemTime.UtcNow()
            };

            // Act
            var contract = service.Map(request);

            // Assert
            repository.Verify(x => x.Queryable <LocationMapping>());
            Assert.IsNotNull(contract, "Contract null");
            Assert.IsFalse(contract.IsValid, "Contract valid");
            Assert.AreEqual(ErrorType.NotFound, contract.Error.Type, "ErrorType difers");
        }
        public object Delete(MappingRequest request)
        {
            var configStore = GetConfigurationStorage();

            if (configStore == null)
            {
                return(ServerError("No Configuration is available"));
            }

            var config = configStore.Load();

            if (config == null)
            {
                return(ServerError("Error attempting to load configuration."));
            }

            var mapping = config.Mappings.FirstOrDefault(x => x.Identity.LeanKit == request.BoardId);

            if (mapping == null)
            {
                return(ServerError(string.Format("There is no mapping for board [{0}]", request.BoardId)));
            }

            try
            {
                config.Mappings.Remove(mapping);
                configStore.Save(config);
            }
            catch (Exception ex)
            {
                return(ServerError("An unexpected error occurred while attempting to remove the requested mapping: " + ex.Message));
            }

            return(OK());
        }
        /// <summary>
        /// C/U create mapping
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public BaseResponse Mapping(MappingRequest request)
        {
            string mappingUrl = RESTfulESUrlBuilder.Init().Mapping().Type(request.Type).Index(request.Indexes).Host(clusterName)
                                .Url();

            return(restServiceClient.Put <MappingRequest, BaseResponse>(mappingUrl, request));
        }
        /// <summary>
        /// G get mapping
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string GetMapping(MappingRequest request)
        {
            string mappingUrl = RESTfulESUrlBuilder.Init().Mapping().Type(request.Type).Index(request.Indexes).Host(clusterName)
                                .Url();

            return(restServiceClient.Get <string>(mappingUrl));
        }
        public object Put(MappingRequest request)
        {
            var model = (BoardMappingModel)request;

            var mapping = Mapper.Map <BoardMapping>(model);

            var localStorage = GetConfigurationStorage();
            var config       = localStorage.Load();

            // ensure the mapping collection exists
            if (config.Mappings == null)
            {
                config.Mappings = new List <BoardMapping>();
            }

            // if this mapping is already in the mapping collection, delete it
            var existingMapping = config.Mappings.FirstOrDefault(x => x.Identity.LeanKit == mapping.Identity.LeanKit);

            if (existingMapping != null)
            {
                config.Mappings.Remove(existingMapping);
            }

            // add the revised mapping and save
            config.Mappings.Add(mapping);

            localStorage.Save(config);

            return(OK());
        }
Esempio n. 7
0
        /// <summary>
        /// Delivery an MDM entity as a data contract for a mapping request
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ContractResponse <TContract> Map(MappingRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (request.IsNexusMappingRequest())
            {
                if (request.HasNumericIdentifier())
                {
                    return(this.Request(request.ToGetRequest()));
                }
                else
                {
                    var response = this.ContractResponse(null, request.ValidAt, request.Version);
                    response.Error.Reason = ErrorReason.Identifier;
                    return(response);
                }
            }

            this.Validate(request);

            var mapping = this.repository.FindAllMappings <TMapping>(request).FirstOrDefault(m => m.Entity is TEntity);

            if (mapping == null)
            {
                var response = ContractResponse(null, request.ValidAt, request.Version);
                response.Error.Reason = ErrorReason.Identifier;
                return(response);
            }
            return(ContractResponse(mapping.Entity as TEntity, request.ValidAt, request.Version));
        }
		public object Put(MappingRequest request)
		{
			var model = (BoardMappingModel) request;

			var mapping = Mapper.Map<BoardMapping>(model);

			var localStorage = GetConfigurationStorage();
			var config = localStorage.Load();

			// ensure the mapping collection exists
			if (config.Mappings == null)
				config.Mappings = new List<BoardMapping>();

			// if this mapping is already in the mapping collection, delete it
			var existingMapping = config.Mappings.FirstOrDefault(x => x.Identity.LeanKit == mapping.Identity.LeanKit);
			if (existingMapping != null)
				config.Mappings.Remove(existingMapping);

			// add the revised mapping and save
			config.Mappings.Add(mapping);

			localStorage.Save(config);

			return OK();
		}
        private void ProcessAll()
        {
            var typesToProcess = context.ModelDef.Types
                                 .Where(t => !t.IsGenericTypeDefinition && !t.IsAutoGenericInstance);

            foreach (var type in typesToProcess)
            {
                var underlyingType = type.UnderlyingType;
                if (verbose)
                {
                    BuildLog.Info(Strings.LogProcessingX, underlyingType.GetShortName());
                }
                var           request = new MappingRequest(underlyingType.Assembly, underlyingType.Namespace);
                MappingResult result;
                if (!mappingCache.TryGetValue(request, out result))
                {
                    result = Process(underlyingType);
                    mappingCache.Add(request, result);
                }
                else
                {
                    if (verbose)
                    {
                        BuildLog.Info(Strings.LogReusingCachedMappingInformationForX, underlyingType.GetShortName());
                    }
                }
                type.MappingDatabase = result.MappingDatabase;
                type.MappingSchema   = result.MappingSchema;
            }
        }
        public void HasNumericIdentifier_WithNaN_ReturnsTrue()
        {
            var mappingRequest = new MappingRequest {
                SystemName = SourceSystemNames.Nexus, Identifier = "string"
            };

            Assert.IsFalse(mappingRequest.HasNumericIdentifier());
        }
        public void HasNumericIdentifier_WithInteger_ReturnsTrue()
        {
            var mappingRequest = new MappingRequest {
                SystemName = SourceSystemNames.Nexus, Identifier = "999"
            };

            Assert.IsTrue(mappingRequest.HasNumericIdentifier());
        }
        public void IsNexusMappingRequest_NexusSourceSystem_ReturnsTrue()
        {
            var mappingRequest = new MappingRequest {
                SystemName = SourceSystemNames.Nexus, Identifier = "999"
            };

            Assert.IsTrue(mappingRequest.IsNexusMappingRequest());
        }
        public static bool IsNexusMappingRequest(this MappingRequest mappingRequest)
        {
            if (string.IsNullOrWhiteSpace(mappingRequest.SystemName))
            {
                return(false);
            }

            return(mappingRequest.SystemName.Trim().ToLower() == SourceSystemNames.Nexus.ToLower());
        }
Esempio n. 14
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            MappingRequest request = (MappingRequest)value;

            if (request == null)
            {
                return;
            }

            writer.WriteStartObject();
            writer.WritePropertyName(request.Type);
            serializer.Serialize(writer, request.Mapping);
            writer.WriteEndObject();
        }
        public static GetRequest ToGetRequest(this MappingRequest mappingRequest)
        {
            int id;

            if (int.TryParse(mappingRequest.Identifier, out id))
            {
                return(new GetRequest()
                {
                    EntityId = int.Parse(mappingRequest.Identifier),
                    ValidAt = mappingRequest.ValidAt,
                    ValidAtExists = mappingRequest.ValidAtExists,
                    Version = mappingRequest.Version
                });
            }
            else
            {
                throw new ArgumentException(string.Format("Invalid Nexus identifier: {0}", mappingRequest.Identifier));
            }
        }
        public void ShouldReturnNotFoundWhenMapRequestedWithInvalidNexusIdentifier()
        {
            // Given
            var mockValidationEngine = new Mock <IValidatorEngine>();
            var mockMappingEngine    = new Mock <IMappingEngine>();
            var mockRepository       = new Mock <IRepository>();
            var mockSearchCache      = new Mock <ISearchCache>();
            var abcService           = new AbcEntityTestService(mockValidationEngine.Object, mockMappingEngine.Object, mockRepository.Object, mockSearchCache.Object);

            // When
            var mappingRequest = new MappingRequest()
            {
                Identifier = "Three",
                SystemName = "Nexus",
                ValidAt    = DateTime.Now
            };

            var response = abcService.Map(mappingRequest);

            Assert.AreEqual(ErrorType.NotFound, response.Error.Type);
        }
        public void ShouldGetEntityByIdWhenMapRequestedForNexusSystem()
        {
            // Given
            var mockValidationEngine = new Mock <IValidatorEngine>();
            var mockMappingEngine    = new Mock <IMappingEngine>();
            var mockRepository       = new Mock <IRepository>();
            var mockSearchCache      = new Mock <ISearchCache>();
            var abcService           = new AbcEntityTestService(mockValidationEngine.Object, mockMappingEngine.Object, mockRepository.Object, mockSearchCache.Object);

            // When
            var mappingRequest = new MappingRequest()
            {
                Identifier = "3",
                SystemName = "Nexus",
                ValidAt    = DateTime.Now
            };

            abcService.Map(mappingRequest);

            // Then
            mockRepository.Verify(x => x.FindOne <AbcEntity>(int.Parse(mappingRequest.Identifier)));
        }
        public void ShouldFindMappingWhenMapRequestedForNonNexusSystems()
        {
            // Given
            var mockValidationEngine = new Mock <IValidatorEngine>();
            var mockMappingEngine    = new Mock <IMappingEngine>();
            var mockRepository       = new Mock <IRepository>();
            var mockSearchCache      = new Mock <ISearchCache>();
            IQueryable <AbcEntityMapping> abcEntityMappingQueryObject =
                (new List <AbcEntityMapping>
            {
                new AbcEntityMapping()
                {
                    System = new SourceSystem()
                    {
                        Name = "Endur"
                    },
                    MappingValue = "EndurId-3",
                    Validity = new DateRange(DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1))
                }
            }).AsQueryable();
            var abcService = new AbcEntityTestService(
                mockValidationEngine.Object, mockMappingEngine.Object, mockRepository.Object, mockSearchCache.Object);

            // When
            var mappingRequest = new MappingRequest()
            {
                Identifier = "EndurId-3",
                SystemName = "Endur",
                ValidAt    = DateTime.Now
            };

            mockValidationEngine.Setup(x => x.IsValid <MappingRequest>(mappingRequest, It.IsAny <IList <IRule> >())).Returns(true);
            mockRepository.Setup(x => x.Queryable <AbcEntityMapping>()).Returns(abcEntityMappingQueryObject);

            abcService.Map(mappingRequest);

            // Then
            mockRepository.Verify(x => x.Queryable <AbcEntityMapping>());
        }
        public void IsNexusMappingRequest_EmptySourceSystem_ReturnsFalse()
        {
            var mappingRequest = new MappingRequest();

            Assert.IsFalse(mappingRequest.IsNexusMappingRequest());
        }
 public static IList <TMapping> FindAllMappings <TMapping>(this IRepository repository, MappingRequest request)
     where TMapping : class, IEntityMapping
 {
     return(repository.FindAllMappings <TMapping>(request.SystemName, request.Identifier, request.ValidAt));
 }
Esempio n. 21
0
        static async Task Main(string[] args)
        {
            var settings = new OpenFigiSettings();
            var b        = new ConfigurationBuilder()
                           .AddEnvironmentVariables()
                           .Build();

            //set an environmental variable named OpenFigiSettings:ApiKey and give it the value
            //of the api key you create on the openfigi website
            b.GetSection("OpenFigiSettings").Bind(settings);

            var keyLookups = new List <MappingKey>();

            keyLookups.Add(MappingKey.CURRENCY);
            keyLookups.Add(MappingKey.EXCH_CODE);
            keyLookups.Add(MappingKey.ID_TYPE);
            keyLookups.Add(MappingKey.MARKET_SECTOR);
            keyLookups.Add(MappingKey.MIC_CODE);
            keyLookups.Add(MappingKey.SECURITY_TYPE_ONE);
            keyLookups.Add(MappingKey.SECURITY_TYPE_TWO);

            var keyValues = new Dictionary <MappingKey, List <string> >();

            using (var p = new MappingProvider(settings.ApiKey))
            {
                foreach (var kl in keyLookups)
                {
                    Console.WriteLine($"Looking up {kl} values...");
                    var vals = await p.LookupMappingKeyValuesAsync(kl).ConfigureAwait(false);

                    Console.WriteLine($"Found {vals?.Values?.Count() ?? 0:N0} values for key {kl}");
                    keyValues.Add(vals.Key, vals.Values.ToList());
                }
                var request = new MappingRequest();
                var j1      = new MappingJob()
                {
                    IdType          = IdType.ID_EXCH_SYMBOL,
                    Id              = "MSFT",
                    SecurityTypeTwo = "Common Stock",
                    ExchangeCode    = "US"
                };

                request.Add(j1);

                var j2 = new MappingJob()
                {
                    IdType          = IdType.ID_EXCH_SYMBOL,
                    Id              = "MSFT",
                    SecurityTypeTwo = "Option",
                    Expiration      = new Range <DateTime?>(new DateTime(2018, 11, 1), new DateTime(2019, 04, 01)),
                    OptionType      = OptionType.Call
                };

                request.Add(j2);

                var r1 = await p.RunMappingJobsAsync(request).ConfigureAwait(false);

                foreach (var eq in r1[0].Records.Take(5))
                {
                    Console.WriteLine($"Ticker: {eq.Ticker}\t\t\tFIGI:{eq.Id}\tMarket Sector: {eq.MarketSectorDescription}\tDescription: {eq.Name}");
                }
                foreach (var op in r1[1].Records.Take(5))
                {
                    Console.WriteLine($"Ticker: {op.Ticker}\tFIGI:{op.Id}\tMarket Sector: {op.MarketSectorDescription}\tDescription: {op.Name}");
                }
            }

            Console.ReadLine();
        }
        public void SuccessMatchCurrentVersion()
        {
            // Arrange
            var validatorFactory = new Mock <IValidatorEngine>();
            var mappingEngine    = new Mock <IMappingEngine>();
            var repository       = new Mock <IRepository>();
            var searchCache      = new Mock <ISearchCache>();

            var service = new PartyService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            // Domain details
            var start  = new DateTime(1999, 12, 31);
            var finish = new DateTime(2020, 1, 1);
            var system = new SourceSystem {
                Name = "Endur"
            };
            var mapping = new PartyMapping
            {
                System       = system,
                MappingValue = "A"
            };
            var details = new PartyDetails
            {
                Name     = "Party 1",
                Validity = new DateRange(start, finish)
            };
            var party = new Party
            {
                Id = 1
            };

            party.AddDetails(details);
            party.ProcessMapping(mapping);

            // Contract details
            var identifier = new EnergyTrading.Mdm.Contracts.MdmId
            {
                SystemName = "Endur",
                Identifier = "A"
            };
            var cDetails = new EnergyTrading.MDM.Contracts.Sample.PartyDetails
            {
                Name = "Party 1"
            };

            mappingEngine.Setup(x => x.Map <PartyMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping)).Returns(identifier);
            mappingEngine.Setup(x => x.Map <PartyDetails, EnergyTrading.MDM.Contracts.Sample.PartyDetails>(details)).Returns(cDetails);
            validatorFactory.Setup(x => x.IsValid(It.IsAny <MappingRequest>(), It.IsAny <IList <IRule> >())).Returns(true);

            var list = new List <PartyMapping> {
                mapping
            };

            repository.Setup(x => x.Queryable <PartyMapping>()).Returns(list.AsQueryable());

            var request = new MappingRequest
            {
                SystemName = "Endur",
                Identifier = "A",
                ValidAt    = SystemTime.UtcNow(),
                Version    = 0
            };

            // Act
            var response = service.Map(request);

            // Assert
            repository.Verify(x => x.Queryable <PartyMapping>());

            Assert.IsNull(response.Contract, "Contract not null");
            Assert.IsTrue(response.IsValid);
            Assert.AreEqual(0UL, response.Version);
        }
        public void UnsuccessfulMatchReturnsNotFound()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();
            var service = new SourceSystemService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            var list = new List<SourceSystemMapping>();
            repository.Setup(x => x.Queryable<SourceSystemMapping>()).Returns(list.AsQueryable());
            validatorFactory.Setup(x => x.IsValid(It.IsAny<MappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);

            var request = new MappingRequest { SystemName = "Endur", Identifier = "A", ValidAt = SystemTime.UtcNow() };

            // Act
            var contract = service.Map(request);

            // Assert
            repository.Verify(x => x.Queryable<SourceSystemMapping>());
            Assert.IsNotNull(contract, "Contract null");
            Assert.IsFalse(contract.IsValid, "Contract valid");
            Assert.AreEqual(ErrorType.NotFound, contract.Error.Type, "ErrorType difers");
        }
 public bool Matches(MappingRequest request)
 {
     return true;
 }
        public void SuccessMatchCurrentVersion()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new PartyService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            // Domain details
            var start = new DateTime(1999, 12, 31);
            var finish = new DateTime(2020, 1, 1);
            var system = new SourceSystem { Name = "Endur" };
            var mapping = new PartyMapping
            {
                System = system,
                MappingValue = "A"
            };
            var details = new PartyDetails
            {
                Name = "Party 1",
                Validity = new DateRange(start, finish)
            };
            var party = new Party
            {
                Id = 1
            };
            party.AddDetails(details);
            party.ProcessMapping(mapping);

            // Contract details
            var identifier = new EnergyTrading.Mdm.Contracts.MdmId
            {
                SystemName = "Endur",
                Identifier = "A"
            };
            var cDetails = new EnergyTrading.MDM.Contracts.Sample.PartyDetails
            {
                Name = "Party 1"
            };

            mappingEngine.Setup(x => x.Map<PartyMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping)).Returns(identifier);
            mappingEngine.Setup(x => x.Map<PartyDetails, EnergyTrading.MDM.Contracts.Sample.PartyDetails>(details)).Returns(cDetails);
            validatorFactory.Setup(x => x.IsValid(It.IsAny<MappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);

            var list = new List<PartyMapping> { mapping };
            repository.Setup(x => x.Queryable<PartyMapping>()).Returns(list.AsQueryable());

            var request = new MappingRequest
            {
                SystemName = "Endur",
                Identifier = "A",
                ValidAt = SystemTime.UtcNow(),
                Version = 0
            };

            // Act
            var response = service.Map(request);

            // Assert
            repository.Verify(x => x.Queryable<PartyMapping>());

            Assert.IsNull(response.Contract, "Contract not null");
            Assert.IsTrue(response.IsValid);
            Assert.AreEqual(0UL, response.Version);
        }
 public void IsNexusMappingRequest_NexusSourceSystem_ReturnsTrue()
 {
     var mappingRequest = new MappingRequest { SystemName = SourceSystemNames.Nexus, Identifier = "999" };
     Assert.IsTrue(mappingRequest.IsNexusMappingRequest());
 }
 public void IsNexusMappingRequest_EmptySourceSystem_ReturnsFalse()
 {
     var mappingRequest = new MappingRequest();
     Assert.IsFalse(mappingRequest.IsNexusMappingRequest());
 }
 public void HasNumericIdentifier_WithNaN_ReturnsTrue()
 {
     var mappingRequest = new MappingRequest { SystemName = SourceSystemNames.Nexus, Identifier = "string" };
     Assert.IsFalse(mappingRequest.HasNumericIdentifier());
 }
 public void HasNumericIdentifier_WithInteger_ReturnsTrue()
 {
     var mappingRequest = new MappingRequest { SystemName = SourceSystemNames.Nexus, Identifier = "999" };
     Assert.IsTrue(mappingRequest.HasNumericIdentifier());
 }
		public object Delete(MappingRequest request)
		{
			var configStore = GetConfigurationStorage();
			if (configStore == null) return ServerError("No Configuration is available");

			var config = configStore.Load();
			if (config == null) return ServerError("Error attempting to load configuration.");

			var mapping = config.Mappings.FirstOrDefault(x => x.Identity.LeanKit == request.BoardId);
			if (mapping == null)
				return ServerError(string.Format("There is no mapping for board [{0}]", request.BoardId));

			try
			{
				config.Mappings.Remove(mapping);
				configStore.Save(config);
			}
			catch (Exception ex)
			{
				return ServerError("An unexpected error occurred while attempting to remove the requested mapping: " + ex.Message);
			}

			return OK();
		}
 public object Resolve(MappingRequest request)
 {
     return Activator.CreateInstance(request.DestinationType);
 }
        public static bool HasNumericIdentifier(this MappingRequest mappingRequest)
        {
            int id;

            return(int.TryParse(mappingRequest.Identifier, out id));
        }
        public void SuccessMatch()
        {
            // Arrange
            var validatorFactory = new Mock <IValidatorEngine>();
            var mappingEngine    = new Mock <IMappingEngine>();
            var repository       = new Mock <IRepository>();
            var searchCache      = new Mock <ISearchCache>();

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            // Domain details
            var start  = new DateTime(1999, 12, 31);
            var finish = new DateTime(2020, 1, 1);
            var system = new SourceSystem {
                Name = "Endur"
            };
            var mapping = new LocationMapping
            {
                System       = system,
                MappingValue = "A"
            };
            var location = new Location
            {
                Id       = 1,
                Validity = new DateRange(start, finish)
            };

            //Location.AddDetails(details);
            location.ProcessMapping(mapping);

            // Contract details
            var identifier = new EnergyTrading.Mdm.Contracts.MdmId
            {
                SystemName = "Endur",
                Identifier = "A"
            };
            var cDetails = new EnergyTrading.MDM.Contracts.Sample.LocationDetails();

            mappingEngine.Setup(x => x.Map <LocationMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping)).Returns(identifier);
            mappingEngine.Setup(x => x.Map <Location, EnergyTrading.MDM.Contracts.Sample.LocationDetails>(location)).Returns(cDetails);
            validatorFactory.Setup(x => x.IsValid(It.IsAny <MappingRequest>(), It.IsAny <IList <IRule> >())).Returns(true);

            var list = new List <LocationMapping> {
                mapping
            };

            repository.Setup(x => x.Queryable <LocationMapping>()).Returns(list.AsQueryable());

            var request = new MappingRequest {
                SystemName = "Endur", Identifier = "A", ValidAt = SystemTime.UtcNow(), Version = 1
            };

            // Act
            var response  = service.Map(request);
            var candidate = response.Contract;

            // Assert
            mappingEngine.Verify(x => x.Map <LocationMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping));
            mappingEngine.Verify(x => x.Map <Location, EnergyTrading.MDM.Contracts.Sample.LocationDetails>(location));
            repository.Verify(x => x.Queryable <LocationMapping>());
            Assert.IsNotNull(candidate, "Contract null");
            Assert.AreEqual(2, candidate.Identifiers.Count, "Identifier count incorrect");
            // NB This is order dependent
            Assert.AreSame(identifier, candidate.Identifiers[1], "Different identifier assigned");
            Assert.AreSame(cDetails, candidate.Details, "Different details assigned");
            Assert.AreEqual(start, candidate.MdmSystemData.StartDate, "Start date differs");
            Assert.AreEqual(finish, candidate.MdmSystemData.EndDate, "End date differs");
        }