public async Task <Country> GetDocumentByCountry(int countryId) { var query = new GraphQLRequest { Query = @" query country($input: CountryInput!) { countries(input: $input) { list{ id identifications { id name discriminator regexp digits abbreviation default prefix mask_edit status prefixes{ id abbreviation status } } } } }", Variables = new { input = new { id = countryId } } }; try { var response = await _client.PostAsync(query); List <Country> countries = new List <Country>(); countries = response.GetDataFieldAs <CountryResponse>("countries").List; return(countries[0]); } catch (Exception e) { throw e; } }
public async Task GetWaterData(DateTime start, DateTime end) { try { // Enable loading screen LoadingViewEnable(); Debug.WriteLine("GET WATER DATA: " + start.ToString() + " - " + end.ToString()); Device.BeginInvokeOnMainThread(() => { LoadingLabel.Text = "Getting water data..."; }); DateTime startTime = start; DateTime endTime = end; // Set timespan - minusSpan (UTC - FINNISH TIME) is to get UTC data relative to finnish time datePickers // e.g. 10/10/2018 00:00:00 - 11/10/2018 00:00:00 FI TIME (+2) is 9/10/2018 22:00:00 - 10/10/2018 22:00:00 UTC TIME DateTime FinlandTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, App.FinlandTimeZone); TimeSpan minusSpan = DateTime.UtcNow - FinlandTime; startTime = new DateTime(start.Year, start.Month, start.Day, 0, 0, 0).Add(minusSpan); endTime = new DateTime(end.Year, end.Month, end.Day).Add(new TimeSpan(23, 59, 59).Add(minusSpan)); // Clear old datalists SingletonWaterFlowDataList dataListFlow = SingletonWaterFlowDataList.Instance; SingletonWaterLevelDataList dataListLevel = SingletonWaterLevelDataList.Instance; dataListFlow.Clear(); dataListLevel.Clear(); // Get Data and parse it await Task.Run(async() => { String startTm = String.Format("{0:s}", startTime); String endTm = String.Format("{0:s}", endTime); var WaterFlowDataRequest = new GraphQLRequest { Query = "{ water_data_query( start_time: \"" + startTm + "\" end_time: \"" + endTm + "\" ) { flow level timestamp } }" }; Debug.WriteLine("{ water_data_query( start_time: \"" + startTm + "\" end_time: \"" + endTm + "\" ) { flow level timestamp } }"); var graphQLClient = new GraphQLClient("http://api.otpt18-c.course.tamk.cloud/"); var graphQLResponse = await graphQLClient.PostAsync(WaterFlowDataRequest); var dynamicData = graphQLResponse.Data["water_data_query"]; Device.BeginInvokeOnMainThread(() => { LoadingLabel.Text = "Updating graphs..."; }); // Get timeDifference DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, App.FinlandTimeZone); TimeSpan timeDifference = localTime - DateTime.UtcNow; // Add fetched data into datalists foreach (JObject data in dynamicData) { DateTime time = new DateTime(1970, 1, 1).AddMilliseconds(double.Parse(data["timestamp"].ToString())).Add(timeDifference); dataListFlow.Add(new WaterFlowData( // Date time, // Flow in cubic meter per second float.Parse(data["flow"].ToString()) )); dataListLevel.Add(new WaterLevelData( // Date time, // Level in meters float.Parse(data["level"].ToString()) / 100 // value is in centimeters so dividing by 100 )); } Debug.WriteLine("GOT WATER DATA, FLOW OBJECTS: " + dataListFlow.Count + " - LEVEL OBJECTS: " + dataListLevel.Count); DateTime newestLevelDate = SingletonWaterLevelDataList.Instance.OrderByDescending(x => x.Timestamp).First().Timestamp; Debug.WriteLine("-------------------------------------- NEWEST DATE ON LIST: " + newestLevelDate.ToString()); }).ContinueWith((task) => { // Update plots Device.BeginInvokeOnMainThread(() => { // Update date limits UpdateDatePickers(); SingletonWaterLevelModel.Instance.SetSeries(SingletonWaterLevelDataList.Instance); SingletonWaterFlowModel.Instance.SetSeries(SingletonWaterFlowDataList.Instance); CreatePlot(); // Disable loading screen LoadingViewDisable(); Debug.WriteLine("----- WATER DATA GOT AND UI UPDATED"); }); }); } catch (Exception e) { Debug.WriteLine("Error: " + e.ToString()); } }
public async Task <GraphQLResponse> GetHotelsData(SearchInputData data, string SessionID) { try { var HotelRequest = new GraphQLRequest { //client: ""citybookers"", testMode: true, context: ""LOGI"" Query = @" query VariableData($hotelsdata:[String!]!,$ch_in: Date!,$ch_out:Date!,$paxesdata:[RoomInput!]!,$nat:Country,$Money:Currency ) { hotelX { search(criteria: {checkIn:$ch_in, checkOut:$ch_out,hotels:$hotelsdata ,nationality:$nat,currency:$Money, occupancies:$paxesdata}, settings: {client: ""Demo_Client"", testMode: true, context: ""HOTELTEST""}) { errors { code type description } warnings { code type description } options { id supplierCode hotelCode hotelName remarks token boardCode accessCode market hotelCodeSupplier boardCodeSupplier paymentType status occupancies{ id paxes{ age } } rooms{ code occupancyRefId beds { type description count shared } description refundable units roomPrice{ price { net currency gross exchange{ rate currency } } } } supplements{ code name description supplementType chargeType mandatory durationType quantity unit effectiveDate expireDate resort { name } price{ net currency } } surcharges{ chargeType description mandatory price{net currency} } cancelPolicy{ refundable cancelPenalties{ hoursBefore currency penaltyType value } } price { net currency gross exchange{ rate currency } } } } } } ", OperationName = "VariableData", Variables = new { hotelsdata = data.hotels, ch_in = data.checkin, ch_out = data.checkout, paxesdata = data.occupancies, nat = data.Nationality, Money = data.currency } }; // "C:\Users\Dev User\source\repos\Hotels2\SMYROOMS" string path = @"C:\Users\Dev User\source\repos\Hotels2\SMYROOMS\ConfigData.xml"; XDocument doc = XDocument.Load(path); var url = doc.Element("MetaData").Element("URL").Value; var KeyData = doc.Element("MetaData").Element("TokenKEYoriginal").Value; var requestData = JsonConvert.SerializeObject(HotelRequest); LoggerHelper.WriteToFile("SMLogs/SearchRequests", "SearchRequest_" + SessionID, "SearchRequest", requestData); var graphQLClient = new GraphQLClient(url); graphQLClient.DefaultRequestHeaders.Add("Authorization", KeyData); var graphQLResponse = graphQLClient.PostAsync(HotelRequest).Result; var ResponseData = JsonConvert.SerializeObject(graphQLResponse); LoggerHelper.WriteToFile("SMLogs/SearchResponses", "SearchResponse_" + SessionID, "SearchResponse", ResponseData); return(graphQLResponse); } catch (Exception ex) { var requestData = JsonConvert.SerializeObject(ex); LoggerHelper.WriteToFile("SMLogs/SearchQUERYException", "SearchQUERYException_" + SessionID, "SearchQUERYException", requestData); throw; } }
private async Task HandleShemaConf(HttpContext context) { string path = context.Request.Path.Value; if (path.EndsWith("schema.json")) { //generate admin schema.conf for client var gqlRequest = new GraphQL.Common.Request.GraphQLRequest { Query = @"{ __schema { queryType { name } types { inputFields { name description type{ name ofType{ kind name ofType{ kind name ofType { name description } } } } defaultValue } name description interfaces { name description } enumValues { description deprecationReason } fields { name description type { name kind } isDeprecated deprecationReason } kind possibleTypes { name description } } mutationType { name } directives { name description locations args { name description type{ kind name ofType{ kind name ofType { name description } } } defaultValue } } } }", OperationName = "" }; string endpoint = context.Request.Scheme + "://" + context.Request.Host.ToString() + context.Request.Path.Value.Substring(0, path.Length - 11) + "graphql"; GraphQLClient graphQLClient = new GraphQLClient(endpoint); var graphQLResponse = await graphQLClient.PostAsync(gqlRequest); string dataContent = JsonConvert.SerializeObject(new { data = graphQLResponse.Data }); context.Response.ContentType = "application/octet-stream"; await context.Response.WriteAsync(dataContent); return; } }
public async Task GetAllWaterDataOnAppStart() { try { Debug.WriteLine("GET DATA ON APP START"); Device.BeginInvokeOnMainThread(() => { LoadingLabel.Text = "Getting water data..."; }); // Clear old datalists SingletonWaterFlowDataList dataListFlow = SingletonWaterFlowDataList.Instance; SingletonWaterLevelDataList dataListLevel = SingletonWaterLevelDataList.Instance; dataListFlow.Clear(); dataListLevel.Clear(); // Get Data and parse it await Task.Run(async() => { var WaterFlowDataRequest = new GraphQLRequest { Query = "{ water_data_query( start_time: \"\" end_time: \"\" ) { flow level timestamp } }" }; var graphQLClient = new GraphQLClient("http://api.otpt18-c.course.tamk.cloud/"); var graphQLResponse = await graphQLClient.PostAsync(WaterFlowDataRequest); var dynamicData = graphQLResponse.Data["water_data_query"]; Device.BeginInvokeOnMainThread(() => { LoadingLabel.Text = "Updating graphs..."; }); // Get timeDifference DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, App.FinlandTimeZone); TimeSpan timeDifference = localTime - DateTime.UtcNow; // Add fetched data into datalists foreach (JObject data in dynamicData) { DateTime time = new DateTime(1970, 1, 1).AddMilliseconds(double.Parse(data["timestamp"].ToString())).Add(timeDifference); dataListFlow.Add(new WaterFlowData( // Date time, // Flow in cubic meter per second float.Parse(data["flow"].ToString()) )); dataListLevel.Add(new WaterLevelData( // Date time, // Level in meters float.Parse(data["level"].ToString()) / 100 // value is in centimeters so dividing by 100 )); } Debug.WriteLine("GOT WATER DATA, FLOW OBJECTS: " + dataListFlow.Count + " - LEVEL OBJECTS: " + dataListLevel.Count); Debug.WriteLine("GETTING ALERT LEVEL"); var AlertLevelRequest = new GraphQLRequest { Query = "{ water_level_alarm{ alarm_level } }" }; graphQLResponse = await graphQLClient.PostAsync(AlertLevelRequest); var alertData = graphQLResponse.Data["water_level_alarm"]; JObject alertLvl = alertData; Debug.WriteLine("-------- ALERT LEVEL IS: " + alertLvl["alarm_level"].ToString()); // The alarm level is in centimeters in database so dividing by 100 to get value in meters SingletonWaterLevelModel.Instance.AlertLineValue = double.Parse(alertLvl["alarm_level"].ToString()) / 100; }).ContinueWith((task) => { // Update plots Device.BeginInvokeOnMainThread(() => { // Update date limits UpdateDatePickersOnAppStart(); SingletonWaterLevelModel.Instance.SetSeries(SingletonWaterLevelDataList.Instance); SingletonWaterFlowModel.Instance.SetSeries(SingletonWaterFlowDataList.Instance); CreatePlot(); // Add plot to the page AddPlotToPage(); // Create onclick events for buttons and datepickers WaterFlowButton.Clicked += WaterFlowButtonPressed; WaterLevelButton.Clicked += WaterLevelButtonPressed; StartDatePicker.DateSelected += StartDatePicker_DateSelected; EndDatePicker.DateSelected += EndDatePicker_DateSelected; // Disable loading screen LoadingViewDisable(); // Check alert CheckIfAlertIsOn(); Debug.WriteLine("---------- WATER DATA GOT AND UI UPDATED"); }); }); } catch (Exception e) { Debug.WriteLine("Error: " + e.ToString()); } }
public async Task <List <Appointment> > GetAppointments(DateTime start, DateTime end) { _client.DefaultRequestHeaders.Add("Authorization", "SFMyNTY.g3QAAAACZAAEZGF0YW0AAAAHNTA6MTgxOGQABnNpZ25lZG4GAHI8YElsAQ.1t0AfDf1vU1u4DV4rbv4j1VYa7WHaIw3kyHG2B8jm38"); var query = new GraphQLRequest { Query = @"query getAppointments ($start:DateTime, $end:DateTime) { appointments (updatedAtStart:$start, updatedAtEnd:$end) { start insertedAt type { id encounterType { id name } name } status location { name } provider { isActive name } patient { clientId } } }", Variables = new { updatedAtStart = start, updatedAtEnd = end } }; try { var response = await _client.PostAsync(query); if (response.Errors?.Any() ?? false) { var unprocessedIds = response.Errors.Select(x => x.AdditonalEntries) .Where(y => y.ContainsKey("extensions")).Where(z => z.ContainsKey("unprocessedIds")); } // to get the json string in data set //string jsonstr = JsonConvert.SerializeObject(response); List <Appointment> result = response.GetDataFieldAs <List <Appointment> >("appointments"); //string jsonstr = JsonConvert.SerializeObject(response); Dictionary <TestClass, int> output = new Dictionary <TestClass, int>(new TestClass.EqualityComparer()); HashSet <string> locationServiceSet = new HashSet <string>(); //Dictionary<string, bool> locationServiceMap = new Dictionary<string, bool>(); foreach (Appointment app in result) { if (app.Start.HasValue && app.Type != null && app.Location != null) { //service type string serviceType = app.Type.Name.ToLower().Contains("care") || app.Type.Name.ToLower().Contains("play") ? app.Type.Name : "Style"; DateTime currDate = app.Start.Value.Date; DateTime lastDate = currDate.AddDays(14); DateTime firstDate = currDate.AddDays(-28); for (DateTime x = firstDate; x < lastDate; x = x.AddDays(1)) { TestClass xTestClass = new TestClass(x, serviceType, app.Location.Name); if (!output.ContainsKey(xTestClass)) { output.Add(xTestClass, 0); } TestClass totalAppClass = new TestClass(x, "Total No of Appointments", app.Location.Name); if (!output.ContainsKey(totalAppClass)) { output.Add(totalAppClass, 0); } if (serviceType.ToLower().Contains("care")) { TestClass totalCare = new TestClass(x, "Total Care", app.Location.Name); if (!output.ContainsKey(totalCare)) { output.Add(totalCare, 0); } } } // increment by 1 for all three case below TestClass test = new TestClass(currDate, serviceType, app.Location.Name); output[test] = output[test] + 1; // Aggregation - Total Care if (serviceType.ToLower().Contains("care")) { TestClass totalCare = new TestClass(app.Start.Value.Date, "Total Care", app.Location.Name); output[totalCare] = output[totalCare] + 1; } // Aggregation - Total Appointments TestClass totalAppointments = new TestClass(app.Start.Value.Date, "Total No of Appointments", app.Location.Name); output[totalAppointments] = output[totalAppointments] + 1; } } Debug.WriteLine(output.Count); foreach (KeyValuePair <TestClass, int> kvp in output.OrderBy(x => x.Key.Location).ThenBy(x => x.Key.Type).ThenBy(x => x.Key.Start)) { Debug.WriteLine("{0}, -> {1}", kvp.Key, output[kvp.Key].ToString(), kvp.Value); } return(result); } catch (Exception ex) { throw ex; } }
//Lista de Bancos Asociados #region ConsultaBanksAsociadosAsync public async Task <AlliedAccount> ConsultaBanksAsociadosAsync(string idPais) { var query = new GraphQLRequest { Query = @"query($idPais: String!){ bancosaliados(idPais:$idPais){ titular documentoidentidad cuentas{ idbanco nombre cuenta currencysymbol currencyiso } } }", Variables = new { idPais = idPais } }; try { var response = await _client.PostAsync(query); return(response.GetDataFieldAs <AlliedAccount>("bancosaliados")); } catch (Exception e) { Console.WriteLine(e); return(new AlliedAccount()); } }
public async Task <GraphQLResponse> HotelBooking(HotelBookInput data, string sessionid) { GraphQLResponse graphQLResponse = new GraphQLResponse(); var randomd = "Book" + RandomString(5); try { var BooKingRequest = new GraphQLRequest { //"01[180823[180824[1[14[1[EN[GB[en[EUR[0[1[422[1[14[1[0[1 | 30#30|1|2018-08-23|1|143250|143278|14|0|0[1[30#30[H4sIAAAAAAAA/8pNLUpOTMmPdvWLdq0oyCxKdUksSY02MtE3sNA3MjC0AAAAAP//AQAA//+mSODzIAAAAA==" // rooms: [{occupancyRefId: $roomid, paxes: [{name: ""Test1"", surname: ""Test1"", age: 26}, {name: ""Test2"", surname: ""Test2"", age: 30}]}] Query = @"mutation Variablesdata($data:String!,$clientNum:String!,$cardtype:String!,$cardHolderName:String!,$cardHolderSurName:String!,$cardNum:String!,$cardCvc:String!,$expiredMonth:Int!,$expiredyear:Int!,$holderName:String!,$holdersurName:String!,$bookingRooms:[BookRoomInput!]!) { hotelX { book(input: {optionRefId:$data, clientReference:$clientNum, deltaPrice: { amount: 10, percent: 10, applyBoth: true}, paymentCard: {cardType:$cardtype, holder: {name:$cardHolderName, surname:$cardHolderSurName}, number:$cardNum, CVC:$cardCvc, expire: {month:$expiredMonth, year:$expiredyear}}, holder: {name:$holderName, surname:$holdersurName}, rooms:$bookingRooms}, settings: {client: ""Demo_Client"", testMode: true}) { booking { status payable remarks reference{ supplier client } hotel { hotelCode checkIn checkOut creationDate boardCode rooms{ occupancyRefId code description price{ net gross currency binding exchange{rate currency} } } occupancies{ id paxes{ age } } } price { currency binding net gross exchange { currency rate } } cancelPolicy{ refundable cancelPenalties{ value currency hoursBefore penaltyType } } } errors { code type description } warnings { code description } } } }", OperationName = "Variablesdata", Variables = new { data = data.optionRefId, cardtype = data.paymentCard.cardType, cardHolderName = data.paymentCard.holder.name, cardHolderSurName = data.paymentCard.holder.surname, cardNum = data.paymentCard.number, cardCvc = data.paymentCard.CVC, expiredMonth = data.paymentCard.expire.month, expiredyear = data.paymentCard.expire.year, holderName = data.holder.name, holdersurName = data.holder.surname, bookingRooms = data.rooms, clientNum = randomd } }; string path = @"C:\Users\Dev User\source\repos\Hotels2\SMYROOMS\ConfigData.xml"; XDocument doc = XDocument.Load(path); var url = doc.Element("MetaData").Element("URL").Value; var KeyData = doc.Element("MetaData").Element("TokenKEY").Value; var requestData = JsonConvert.SerializeObject(BooKingRequest); LoggerHelper.WriteToFile("SMLogs/BookingRequests", "BookingRequest_" + sessionid, "BookingRequest", requestData); var graphQLClient = new GraphQLClient(url); graphQLClient.DefaultRequestHeaders.Add("Authorization", KeyData); graphQLResponse = await graphQLClient.PostAsync(BooKingRequest); var ResponseData = JsonConvert.SerializeObject(graphQLResponse); LoggerHelper.WriteToFile("SMLogs/BookingResponse", "BookingResponse_" + sessionid, "BookingResponse", ResponseData); return(graphQLResponse); } catch (Exception ex) { var requestData = JsonConvert.SerializeObject(ex); LoggerHelper.WriteToFile("SMLogs/BookingQueryException", "BookingQueryException_" + sessionid, "BookingQueryException", requestData); throw; } }
public async Task <GraphQLResponse> ValidationData(string id, string SessionID) { try { var ValidationRequest = new GraphQLRequest { //"01[180823[180824[1[14[1[EN[GB[en[EUR[0[1[422[1[14[1[0[1 | 30#30|1|2018-08-23|1|143250|143278|14|0|0[1[30#30[H4sIAAAAAAAA/8pNLUpOTMmPdvWLdq0oyCxKdUksSY02MtE3sNA3MjC0AAAAAP//AQAA//+mSODzIAAAAA==" Query = @"query variabledata($data:String! ) { hotelX { quote(criteria: {optionRefId:$data }, settings: {client: ""Demo_Client"", testMode: true, context: ""HOTELTEST""}) { errors { code description } warnings { code description } optionQuote { optionRefId status price { currency binding net gross exchange { currency rate } } cancelPolicy{ refundable cancelPenalties{ currency hoursBefore penaltyType value } } } } } }", OperationName = "variabledata", Variables = new { data = id, } }; string path = @"C:\Users\Dev User\source\repos\SMYROOMS\SMYROOMS\ConfigData.xml"; XDocument doc = XDocument.Load(path); var url = doc.Element("MetaData").Element("URL").Value; var KeyData = doc.Element("MetaData").Element("TokenKEY").Value; var requestData = JsonConvert.SerializeObject(ValidationRequest); LoggerHelper.WriteToFile("c:/HotelsB2C/Logs/SMLogs/ValidationRequests", "ValidationRequest_" + SessionID, "ValidationRequest", requestData); var graphQLClient = new GraphQLClient(url); graphQLClient.DefaultRequestHeaders.Add("Authorization", KeyData); var graphQLResponse = await graphQLClient.PostAsync(ValidationRequest); var ResponseData = JsonConvert.SerializeObject(graphQLResponse); LoggerHelper.WriteToFile("c:/HotelsB2C/Logs/SMLogs/ValidationResponse", "ValidationResponse_" + SessionID, "ValidationResponse", ResponseData); return(graphQLResponse); } catch (Exception ex) { var requestData = JsonConvert.SerializeObject(ex); LoggerHelper.WriteToFile("c:/HotelsB2C/Logs/SMLogs/ValidationQueryException", "ValidationQueryException_" + SessionID, "ValidationQueryException", requestData); throw; } }
/// <summary> /// Creates and executes a custom request. /// </summary> /// <param name="request">The request to be executed.</param> /// <returns>The response gained from the smash.gg API.</returns> public Task <GraphQLResponse> ExecuteCustomRequest(GraphQLRequest request) { return(_graphQlClient.PostAsync(request)); }