public ContractManagerTest() { //TODO: init the ads cm = new ContractManager() { AsService = ass = new AdapterServerServiceMockImpl(), BcService = new BeContractServiceImpl() }; mathCall = new BeContractCall() { Id = "GetMathemathicFunction", ISName = "Test Man", Inputs = new Dictionary <string, dynamic>() { { "A", 54 }, { "B", 154 } } }; adrByDog = new BeContractCall() { Id = "GetAddressByDogId", ISName = "Test Man", Inputs = new Dictionary <string, dynamic>() { { "MyDogID", "Heyto" }, } }; }
public void ValidateBeContractCall(BeContract contract, BeContractCall call) { if (!contract.Id.Equals(call.Id)) { throw new BeContractException("Contract's do not have the same ID") { BeContract = contract, BeContractCall = call }; } if (string.IsNullOrWhiteSpace(call.ISName)) { //TODO: test if the ISName exists in the DB ? throw new BeContractException("The BeContractCall has no ISName"); } //Test inputs contract.Inputs?.ForEach(input => { if (call.Inputs == null) { throw new BeContractException("The BeContracts needs inputs but the call hasn't inputs !") { BeContract = contract, BeContractCall = call } } ; if (call.Inputs.TryGetValue(input.Key, out dynamic value)) { //Check if the dynamic is a int64 if (value.GetType() == typeof(Int64)) { value = (int)value; call.Inputs[input.Key] = value; } //Check the types if (value.GetType().Name != input.Type) { throw new BeContractException($"The contract expects {input.Type} but {value.GetType().Name} was found") { BeContract = contract, BeContractCall = call }; } } else if (input.Required) { //Key isn't find and is required throw new BeContractException($"No key was found for {input.Key} and it is required") { BeContract = contract, BeContractCall = call }; } }); }
public async Task <BeContractReturn> CallAsync(AdapterServer ads, BeContractCall call) { BeContractReturn res = null; using (var client = new HttpClient()) { try { //Use the ads.Url as baseaddress, don't send this to Be-Road ! client.BaseAddress = new Uri(ads.Url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var httpContent = new StringContent(JsonConvert.SerializeObject(call), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(ads.Root + "/" + call.Id, httpContent); if (response.IsSuccessStatusCode) { res = await response.Content.ReadAsAsync <BeContractReturn>(); } } catch (Exception ex) { throw new BeContractException("Cannot call the Adapter Server: " + ex.Message); } } return(res); }
static BeContractCall CreateContractCall(string id, params string[] parameters) { var call = new BeContractCall() { Id = id, ISName = "Console App", Inputs = new Dictionary <string, dynamic>() }; parameters.ToList().ForEach(param => { var split = param.Split(':'); if (split.Length == 2) { if (int.TryParse(split[1], out int n)) { call.Inputs.Add(split[0], n); } else { call.Inputs.Add(split[0], split[1]); } } }); return(call); }
public BeContractReturn GetBankContract(BeContractCall call) { return(new BeContractReturn() { Id = "GetBankContract", Outputs = new Dictionary <string, dynamic>() { { "Bankaccount", bankAccounts.FirstOrDefault(b => b.Key.Equals(call.Inputs["NRID"])).Value ?? "No account here" } } }); }
public async Task <BeContractReturn> CallAsync(AdapterServer ads, BeContractCall call) { //Empty await for the method await Task.Run(() => { }); switch (call.Id) { case "GetOwnerIdByDogId": return(HandleGetOwnerIdByDogId(call)); default: return(new BeContractReturn()); } }
private async Task <ManageViewModel> GetUserPop(string nrid, string justification) { using (var client = new HttpClient()) { var user = new ManageViewModel(); try { client.BaseAddress = new Uri("http://proxy/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var call = new BeContractCall { Id = "GetPopulationContract", ISName = $"Public Service/{nrid}", Inputs = new Dictionary <string, dynamic>() { { "NRID", nrid }, { "Justification", justification } } }; var httpContent = new StringContent(JsonConvert.SerializeObject(call), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("api/contract/call", httpContent); if (response.IsSuccessStatusCode) { var resp = await response.Content.ReadAsAsync <Dictionary <int, BeContractReturn> >(); var outputs = resp.Values.Select(ret => ret.Outputs).ToList(); var userValues = outputs.SelectMany(d => d) .ToDictionary(t => t.Key, t => t.Value); user.FirstName = userValues["FirstName"]; user.LastName = userValues["LastName"]; user.Locality = userValues["Locality"]; user.Nationality = userValues["Nationality"]; var birthDate = userValues["Birthday"].Split(' '); user.BirthDateD = birthDate[0]; user.BirthDateM = birthDate[1]; user.BirthDateY = birthDate[2]; } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(user); } }
public async Task <Dictionary <int, BeContractReturn> > GetAddressByDogAsync(string dogId) { var addrByDog = new BeContractCall() { Id = "GetAddressByDogId", ISName = "ADS Mock", Inputs = new Dictionary <string, dynamic>() { { "MyDogID", dogId }, } }; return(await CallToProxyAsync(addrByDog)); }
public BeContractReturn GetServiceInfo(BeContractCall call) { // Calling the IS to get their info return(new BeContractReturn() { Id = "GetServiceInfo", Outputs = new Dictionary <string, dynamic>() { { "Name", "MockADS" }, { "Purpose", "Testing" }, { "CreationDate", DateTime.Now.ToShortDateString() } } }); }
private BeContractReturn HandleGetOwnerIdByDogId(BeContractCall call) { var ret = new BeContractReturn() { Id = call.Id, Outputs = new Dictionary <string, dynamic>() }; if ((call.Inputs["DogID"] as string).Equals("D-123")) { ret.Outputs.Add("OwnerIDOfTheDog", "Wilson !"); } return(ret); }
public static BeContractReturn GetSumFunction(BeContractCall call) { var a = Convert.ToInt32(call.Inputs["A"]); var b = Convert.ToInt32(call.Inputs["B"]); return(new BeContractReturn() { Id = "GetMathemathicFunction", Outputs = new Dictionary <string, dynamic>() { { "Total", a + b }, { "Formula", "Total = A + B" } } }); }
public static BeContractReturn GetAddressByOwnerId(BeContractCall call) { switch (call.Inputs["OwnerID"]) { case "Wilson !": return(ReturnAnswer("Charleroi nord", 9999, "Belgique")); case "Mika !": return(ReturnAnswer("Bxl", 1080, "Belgique")); case "Flo": return(ReturnAnswer("Charleroi Centre", 1000, "Belgique")); case "Pierre": return(ReturnAnswer("Charleroi Central", 5000, "Belgique")); default: return(ReturnAnswer("SDF", 0, "SDF")); } }
public BeContractReturn GetOwnerId(BeContractCall call) { switch (call?.Inputs["DogID"]) { case "D-123": return(ReturnAnswer("Wilson !")); case "D-122": return(ReturnAnswer("Mika !")); case "D-124": return(ReturnAnswer("Flo !")); case "D-126": return(ReturnAnswer("Pierre !")); default: return(ReturnAnswer("Incognito !")); } }
public async Task <HttpResponseMessage> CallContractAsync(BeContractCall call) { try { var callRes = await cm.CallAsync(call); await CallToMLAsync(new { ContractId = call.Id, UserName = call.ISName, UserType = "TEMP", Response = false, call.Inputs }, "api/Contract/Call"); return(Request.CreateResponse(HttpStatusCode.OK, callRes)); } catch (BeContractException ex) { await CallToMLAsync(new { UserName = call.ISName ?? "Undefined username", UserType = "TEMP", ex.Message }, "api/Exception/Call"); return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message)); } }
public async Task <CarViewModel> GetCar(string nrid, string justification) { using (var client = new HttpClient()) { var car = new CarViewModel(); try { client.BaseAddress = new Uri("http://proxy/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var call = new BeContractCall { Id = "GetDivContract", ISName = $"Public Service/{nrid}", Inputs = new Dictionary <string, dynamic>() { { "NRID", nrid }, { "Justification", justification } } }; var httpContent = new StringContent(JsonConvert.SerializeObject(call), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("api/contract/call", httpContent); if (response.IsSuccessStatusCode) { var resp = await response.Content.ReadAsAsync <Dictionary <int, BeContractReturn> >(); var outputs = resp.Values.Select(ret => ret.Outputs).ToList(); var carValues = outputs.SelectMany(d => d) .ToDictionary(t => t.Key, t => t.Value); car.Owner = db.Users.FirstOrDefault(u => u.UserName.Equals(nrid)); car.Brand = carValues["Brand"]; car.NumberPlate = carValues["NumberPlate"]; } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(car); } }
private async Task <PublicServiceData> GetPSDOfContract(string nrid, string contractId) { var data = new PublicServiceData() { ContractName = contractId }; using (var client = new HttpClient()) { try { client.BaseAddress = new Uri(ConfigHelper.GetServiceUrl("proxy")); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var call = new BeContractCall { Id = contractId, ISName = "Privacy Passport", Inputs = new Dictionary <string, dynamic>() { { "NRID", nrid }, { "Justification", "Reading my own data" } } }; var httpContent = new StringContent(JsonConvert.SerializeObject(call), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("api/contract/call", httpContent); if (response.IsSuccessStatusCode) { var resp = await response.Content.ReadAsAsync <Dictionary <int, BeContractReturn> >(); var outputs = resp.Values.Select(ret => ret.Outputs); data.NRID = nrid; data.Datas = outputs.SelectMany(d => d) .ToDictionary(t => t.Key, t => t.Value); data.AccessInfos = await GetAccessInfosOf(contractId, nrid); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } return(data); }
public async Task <BeContractReturn> CallAsync(AdapterServer ads, BeContractCall call) { BeContractReturn ret = null; await Task.Run(() => { switch (ads.ISName) { case "Doggies": ret = VeterinaryMock.GetOwnerId(call); break; case "MathLovers": ret = MathematicsMock.GetSumFunction(call); break; case "CitizenDatabank": ret = AddressMock.GetAddressByOwnerId(call); break; default: ret = new BeContractReturn(); break; } }); return(ret); }
/// <summary> /// Call a contract /// </summary> /// <param name="call">The inputs for the contract call</param> /// <returns></returns> public async Task <Dictionary <int, BeContractReturn> > CallAsync(BeContractCall call) { if (call == null) { throw new BeContractException("Contract call is null"); } var contract = await BcService.FindBeContractByIdAsync(call.Id); Console.WriteLine($"Calling contract {contract?.Id}"); //Filter to only give the correct outputs var notFiltredReturns = await CallAndLoopQueriesAsync(call, contract); var filtredReturns = new Dictionary <int, BeContractReturn>(); var groupedOutputs = contract.Outputs?.GroupBy(output => output.LookupInputId); groupedOutputs.ToList().ForEach(group => { var beContractReturn = new BeContractReturn { Outputs = new Dictionary <string, dynamic>() }; group.ToList().ForEach(output => { var ret = notFiltredReturns[output.LookupInputId].Outputs.FirstOrDefault(o => o.Key.Equals(output.Key)); beContractReturn.Id = notFiltredReturns[output.LookupInputId].Id; beContractReturn.Outputs.Add(ret.Key, ret.Value); }); filtredReturns.Add(group.Key, beContractReturn); }); filtredReturns.ToList().ForEach(ret => { Console.WriteLine($"At LookupInputId {ret.Key} for contract {ret.Value.Id}"); ret.Value.Outputs.ToList().ForEach(output => { Console.WriteLine($"\t{output.Key} - {output.Value}"); }); }); return(filtredReturns); }
private async Task <Dictionary <int, BeContractReturn> > CallToProxyAsync(BeContractCall call) { Dictionary <int, BeContractReturn> ret = null; using (var client = new HttpClient()) { client.BaseAddress = new Uri(ConfigHelper.GetServiceUrl("proxy")); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var httpContent = new StringContent(JsonConvert.SerializeObject(call), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("api/contract/call", httpContent); if (response.IsSuccessStatusCode) { ret = await response.Content.ReadAsAsync <Dictionary <int, BeContractReturn> >(); } } return(ret); }
/// <summary> /// Call the contract with the specified inputs to a specified service /// </summary> /// <param name="contract">Contract that will be called</param> /// <param name="call">The inputs for the contract</param> /// <returns>Returns the outputs for that specific contract</returns> private async Task <BeContractReturn> CallServiceAsync(BeContract contract, BeContractCall call) { //Get the ads for this call var ads = await AsService.FindASAsync(call.Id); if (ads == null) { throw new BeContractException($"No service found for {call.Id}") { BeContractCall = call } } ; //Check if the caller has the permission if (!(await AuthService.CanInformationSystemUseContract(call.ISName, contract))) { throw new BeContractException($"The caller {call.ISName} does not have the permission to use {call.Id}") { BeContractCall = call, BeContract = contract } } ; //If everything is fine, call the service BeContractReturn returns = await AsService.CallAsync(ads, call); //TODO: // -Send error to the service if (returns != null) { validators.ValidateBeContractReturn(contract, returns); } return(returns); }
public BeContractReturn GetFunnyContract(BeContractCall call) => new BeContractReturn() { Id = "GetFunnyContract", Outputs = GetOutputsOf(funny, call.Inputs["NRID"]) };
public BeContractReturn GetDivContract(BeContractCall call) => new BeContractReturn() { Id = "GetDivContract", Outputs = GetOutputsOf(div, call.Inputs["NRID"]) };
public AdapterServerTest() { asService = new AdapterServerServiceMockImpl(); valid = new Validators(); call = valid.Generators.GenerateBeContractCall(GetBeContractCallString()); }
public BeContractReturn GetPopulationContract(BeContractCall call) => new BeContractReturn() { Id = "GetPopulationContract", Outputs = GetOutputsOf(population, call.Inputs["NRID"]) };
/// <summary> /// Find the contract with the call id /// Loop over every query /// </summary> /// <param name="call">The inputs for the contract call</param> /// <returns>Return a list of contract id with his return types</returns> private async Task <List <BeContractReturn> > CallAndLoopQueriesAsync(BeContractCall call, BeContract contract = null) { if (contract == null) { contract = await BcService.FindBeContractByIdAsync(call.Id); } if (contract == null) { throw new BeContractException($"No contract was found with id {call.Id}"); } validators.ValidateBeContractCall(contract, call); var returns = new List <BeContractReturn>(); //If it's a nested contract, loop through it if (contract?.Queries?.Count > 0) { foreach (var q in contract.Queries) { //Create the BeContractCall var callInQuery = new BeContractCall() { Id = q.Contract.Id, ISName = call.ISName, Inputs = new Dictionary <string, dynamic>() }; //Fill in the inputs of the BeContractCall q.Contract.Inputs?.ForEach(input => { var mapping = q.Mappings.FirstOrDefault(m => m.InputKey.Equals(input.Key)); if (mapping == null) { throw new BeContractException($"No mapping exists for inputKey {input.Key}"); } //We need to check our contract input if (mapping.LookupInputId == 0) { if (!call.Inputs.TryGetValue(mapping.LookupInputKey, out dynamic value)) { throw new BeContractException($"No value was found for the key {mapping.LookupInputKey} in the lookupinputid n°{mapping.LookupInputId}") { BeContractCall = call } } ; callInQuery.Inputs.Add(input.Key, value); } //Find the contract where we need to search the value else { if ((mapping.LookupInputId - 1) >= returns.Count) { throw new BeContractException($"Mapping LookupInputId n°{mapping.LookupInputId} is bigger then the returns size {returns.Count}"); } var returnToBeUsed = returns[mapping.LookupInputId - 1]; if (returnToBeUsed == null) { throw new BeContractException($"No output was found for query {q.Contract.Id} with mapping lookupinputid n°{mapping.LookupInputId}") { BeContractCall = call } } ; //We need to check our contract outputs if (!returnToBeUsed.Outputs.TryGetValue(mapping.LookupInputKey, out dynamic value)) { throw new BeContractException($"No value was found for the key {mapping.LookupInputKey} in the contract outputs of n°{mapping.LookupInputId}") { BeContractCall = call } } ; callInQuery.Inputs.Add(input.Key, value); } }); //Call the contract var loopdQueries = await CallAndLoopQueriesAsync(callInQuery); if (loopdQueries.Contains(null)) { throw new BeContractException($"Got an null in loopqueries with id {callInQuery.Id}"); } returns.AddRange(loopdQueries); } ; } else { var serviceReturns = await CallServiceAsync(contract, call); if (serviceReturns == null) { throw new BeContractException($"Got an null in serviceCall with id {call.Id}"); } returns.Add(serviceReturns); } return(returns); }