public static async void GetLocationName(string street, string municipality) { string url = "https://api.vasttrafik.se/bin/rest.exe/v2/location.name?input=" + street + "%20" + municipality + "&format=json"; //string url = "https://api.vasttrafik.se/bin/rest.exe/v2/location.name?input=sanneg%C3%A5rdshamnen&format=json"; using (HttpResponseMessage response = await ApiHelperVasttrafik.ApiClient.GetAsync(url)) { if (response.IsSuccessStatusCode) { string fromVastTrafik = await response.Content.ReadAsStringAsync(); JObject jsonObject = JObject.Parse(fromVastTrafik); var locationName = jsonObject.SelectToken("LocationList").SelectToken("StopLocation")[0]; MongoCRUD db = new MongoCRUD("admin"); VastTrafikModelLocation model = new VastTrafikModelLocation(); model.Name = locationName[key : "name"].ToString(); model.Lon = locationName[key : "lon"].ToObject <float>(); model.Lat = locationName[key : "lat"].ToObject <float>(); db.InsertRecord(Vasttrafik.locations, model); } else { Console.Write("Fel vid kontakt med API"); throw new Exception(response.ReasonPhrase); } } }
static void Main(string[] args) { MongoCRUD db = new MongoCRUD("AddressBook"); // startar en webclient ApiHelper.InitializeClient(); string apikey = "'6bb34852b5b140e69f3eec606ea04220'"; // sätter query i en string string quearyString = "<REQUEST>" + // Use your valid authenticationkey "<LOGIN authenticationkey=" + apikey + "/>" + "<QUERY objecttype='TrainStation' schemaversion='1'>" + "<FILTER>" + "<IN name='CountyNo' value='14'/>" + "</FILTER>" + "<INCLUDE>AdvertisedLocationName</INCLUDE>" + "<INCLUDE>LocationSignature</INCLUDE>" + "<INCLUDE>LocationInformationText</INCLUDE>" + "</QUERY>" + "</REQUEST>"; // sätter query i formatet för http body request StringContent query = new StringContent(quearyString); //Console.WriteLine(TrafikverketProcessor.PostTrafikVerket(query)); db.InsertRecord("test", TrafikverketProcessor.PostTrafikVerket(query)); Console.ReadLine(); }
public static void LoopTrainAnnouncement() { IList <string> signList = new List <string>(); signList = MongoCRUD.FindStationSign("14"); foreach (var sign in signList) { TrafikverketProcessor.PostTrainAnnouncement(Query.TrainAnnouncement(sign)); } }
public static async void GetGeo(StopPointNameMunicipalityModel model, string street, string municipality) { try { string url = "https://api.vasttrafik.se/bin/rest.exe/v2/location.name?input=" + street + "%20" + municipality + "&format=json"; //string url = "https://api.vasttrafik.se/bin/rest.exe/v2/location.name?input=sanneg%C3%A5rdshamnen&format=json"; using (HttpResponseMessage response = await ApiHelperVasttrafik.ApiClient.GetAsync(url)) { if (response.IsSuccessStatusCode) { string fromVastTrafik = await response.Content.ReadAsStringAsync(); JObject jsonObject = JObject.Parse(fromVastTrafik); var locationName = jsonObject.SelectToken("LocationList").SelectToken("StopLocation")[0]; //Console.WriteLine(model); MongoCRUD db = new MongoCRUD("admin"); model.Lon = locationName[key : "lon"].ToObject <float>(); model.Lat = locationName[key : "lat"].ToObject <float>(); //Tuple coordReturn = new Tuple(longitude, latitude); await db.Upsert(Vasttrafik.affectedLocation, model); } else { Console.Write("Fel vid kontakt med Västtrafik API"); Console.WriteLine(response.ReasonPhrase); //throw new Exception(response.ReasonPhrase); } } } catch { } }
static async Task Main(string[] args) { MongoCRUD db = new MongoCRUD("admin"); //startar en webclient //ApiHelper.InitializeClientVastTrafik(); //TrafikverketProcessor.PostTrainAnnouncement(Query.TrainAnnouncement("F")); //Kalla på metoden postrafikverket OBS! för att hämta tågstationer krävs att _id i TrafikverketModel.cs är borttaget men detta krockar med TrainAnnouncement senare //TrafikverketProcessor.PostTrainStation(Query.TrainStation()); //VastTrafikProcessor.GetLocationName("pilgatan", "göteborg"); // var testlist = db.FindRecord<string>("Locationsss", "Name", "Västra Parken"); // Console.WriteLine(testlist); // skapar en timer för programmet, inställningar anger hur ofta metoderna ska loopas igenom Timer timer = new Timer(); // endast timerMinutes behöver ändras för att sätta intervallerna på timern int timerMinutes = 1; timer.Interval = 1000 * 60 * timerMinutes; timer.Elapsed += OnTimedEvent; timer.Enabled = true; // Ligger endast för att blocka körningen från avslut ( för att kolla fel/ok medelanden) Console.ReadLine(); }
public static async void GetTrafficSituation() { string url = "https://api.vasttrafik.se/ts/v1/traffic-situations"; using (HttpResponseMessage response = await ApiHelperVasttrafik.ApiClient.GetAsync(url)) { if (response.IsSuccessStatusCode) { string fromVastTrafik = await response.Content.ReadAsStringAsync(); JArray trafficSituation = JArray.Parse(fromVastTrafik); MongoCRUD db = new MongoCRUD("admin"); foreach (var traffic in trafficSituation) { VastTrafikModelTrafficSituation model = new VastTrafikModelTrafficSituation(); model.SituationNumber = traffic[key : "situationNumber"].ToString(); model.CreationTime = traffic[key : "creationTime"].ToObject <DateTime>(); model.StartTime = traffic[key : "startTime"].ToObject <DateTime>(); model.EndTime = traffic[key : "endTime"].ToObject <DateTime>(); model.Severity = traffic[key : "severity"].ToString(); model.Title = traffic[key : "title"].ToString(); model.Description = traffic[key : "description"].ToString(); model.AffectedStopPoints = new List <AffectedStopPointsModel>(); try { JArray affectedStopPoints = JArray.Parse(traffic.SelectToken("affectedStopPoints").ToString()); foreach (var stops in affectedStopPoints) { AffectedStopPointsModel modelaffected = new AffectedStopPointsModel(); modelaffected.Name = stops[key : "name"].ToString(); modelaffected.StopPointGid = stops[key : "gid"].ToString(); modelaffected.MunicipalityName = stops[key : "municipalityName"].ToString(); model.AffectedStopPoints.Add(modelaffected); StopPointNameMunicipalityModel stopName = new StopPointNameMunicipalityModel(); stopName.Name = stops[key : "name"].ToString(); stopName.MunicipalityName = stops[key : "municipalityName"].ToString(); stopName.SituationNumber = model.SituationNumber.ToString(); try { JArray affectedLines = JArray.Parse(traffic.SelectToken("affectedLines").ToString()); foreach (var stop in affectedLines) { stopName.TransportAuthorityName = stop[key : "transportAuthorityName"].ToString(); stopName.DefaultTransportModeCode = stop[key : "defaultTransportModeCode"].ToString(); } } catch { Console.WriteLine("affectedLines Error"); break; } GetGeo(stopName, stopName.Name, stopName.MunicipalityName); await db.Upsert(Vasttrafik.affectedLocation, stopName); } } catch { Console.WriteLine("Catchen"); break; } /* * try * { * JArray affectedLines = JArray.Parse(traffic.SelectToken("affectedLines").ToString()); * Console.WriteLine(affectedLines); * * foreach (var stop in affectedLines) * { * * StopPointNameMunicipalityModel modelaffected = new StopPointNameMunicipalityModel(); * modelaffected.TransportAuthorityName = stop[key: "transportAuthorityName"].ToString(); * modelaffected.DefaultTransportModeCode = stop[key: "defaultTransportModeCode"].ToString(); * modelaffected.SituationNumber = model.SituationNumber.ToString(); * * await db.Upsert(Vasttrafik.affectedLocation, modelaffected); * } * } * catch * { * Console.WriteLine("affectedLines Error"); * break; * } */ await db.Upsert(Vasttrafik.traficSituation, model); } } else { Console.Write("Fel vid kontakt med API"); throw new Exception(response.ReasonPhrase); } } }
public static async void PostTrainAnnouncement(HttpContent data) { string url = "https://api.trafikinfo.trafikverket.se/v2/data.json"; using (HttpResponseMessage response = await ApiHelper.ApiClient.PostAsync(url, data)) { if (response.IsSuccessStatusCode) { string fromTrafikverket = await response.Content.ReadAsStringAsync(); JObject jsonObject = JObject.Parse(fromTrafikverket); var trainAnnouncements = jsonObject.SelectToken("RESPONSE").SelectToken("RESULT")[0].SelectToken("TrainAnnouncement"); MongoCRUD db = new MongoCRUD("admin"); foreach (var announcement in trainAnnouncements) { TrafikverketTrainAnnouncementModel model = new TrafikverketTrainAnnouncementModel(); try { if (announcement[key: "ActivityId"].ToString() != null) { model.ActivityId = announcement[key : "ActivityId"].ToString(); try { model.AdvertisedTimeAtLocation = announcement[key : "AdvertisedTimeAtLocation"].ToObject <DateTime>(); } catch { } try { model.EstimatedTimeAtLocation = announcement[key : "EstimatedTimeAtLocation"].ToObject <DateTime>(); } // för många poster utan estimatedTimeAtLocation, skippar loggning av fel catch { } try { model.Canceled = announcement[key : "Canceled"].ToObject <bool>(); } catch { } try { model.InformationOwner = announcement[key : "InformationOwner"].ToString(); } catch { } try { model.LocationSignature = announcement[key : "LocationSignature"].ToString(); } catch { } try { var token = announcement[key : "FromLocation"][0]; string stringFromLocation = token.First.ToString(); stringFromLocation = Regex.Replace(stringFromLocation, "\"", ""); string[] substring = Regex.Split(stringFromLocation, " "); model.FromLocation = substring[1]; } catch { } try { var token = announcement[key : "ToLocation"][0]; string stringToLocation = token.First.ToString(); stringToLocation = Regex.Replace(stringToLocation, "\"", ""); string[] substring = Regex.Split(stringToLocation, " "); model.ToLocation = substring[1]; } catch { } try { model.Deviation = announcement[key : "Deviation"][0].ToString(); } catch { } await db.Upsert(Trafikverket.trainAnnouncement, model, model.ActivityId); } //db.InsertRecord("TrainAnnouncement", model); } catch { Console.WriteLine("error reading/writing"); } } } else { //throw new Exception(response.ReasonPhrase); } } }
public static async void PostTrainMessage(HttpContent data) { string url = "https://api.trafikinfo.trafikverket.se/v2/data.json"; using (HttpResponseMessage response = await ApiHelper.ApiClient.PostAsync(url, data)) { if (response.IsSuccessStatusCode) { string fromTrafikverket = await response.Content.ReadAsStringAsync(); JObject jsonObject = JObject.Parse(fromTrafikverket); // json objectet från trafikverket har strukturen ("RESPONSE") ("RESULT") [ ("TrainStation") ] var trainMessage = jsonObject.SelectToken("RESPONSE").SelectToken("RESULT")[0].SelectToken("TrainMessage"); //Console.WriteLine(trainMessage.ToString()); MongoCRUD db = new MongoCRUD("admin"); foreach (var message in trainMessage) { TrafikverketTrainMessageModel model = new TrafikverketTrainMessageModel(); // sätter in alla värden enligt modellen i TrafikverketModel //model.EventId = message[key: "EventId"].ToString(); model.Header = message[key : "Header"].ToString(); model.ExternalDescription = message[key : "ExternalDescription"].ToString(); JToken geo = message[key : "Geometry"]; JToken wgs84 = geo[key : "WGS84"]; string pointstring = wgs84.ToString(); // Regex för att ta bort "POINT" från fältet och sedan "( )" pointstring = Regex.Replace(pointstring, "POINT", ""); pointstring = Regex.Replace(pointstring, @"[()]", ""); // delar stringen på alla mellanrum. !OBS fältet startar med mellanrum vilket skapar 3! delar string[] substring = Regex.Split(pointstring, " "); // plockar upp och delar ut cordinaterna, mest för läsbarhet och att inte råka skicka med mellanrummet string[] coords = { substring[1], substring[2] }; model.Longitude = float.Parse(coords[0], CultureInfo.InvariantCulture); model.Latitude = float.Parse(coords[1], CultureInfo.InvariantCulture); model.EventId = message[key : "EventId"].ToString(); model.StartDateTime = message[key : "StartDateTime"].ToObject <DateTime>(); model.ModifiedTime = message[key : "ModifiedTime"].ToString(); model.AffectedLocation = message[key : "AffectedLocation"].ToObject <List <string> >(); // försöker lägga till EndDate om detta finns annars skriver ut felmedelande i consolen try { model.EndDateTime = message[key : "EndDateTime"].ToObject <DateTime>(); } catch { //Console.WriteLine("No endate time set for model"); } //db.InsertRecord("TrainMessage", model); await db.Upsert(Trafikverket.trainMessage, model); } } else { Console.WriteLine("!!FEL VID KONTAKT MED API!!"); throw new Exception(response.ReasonPhrase); } } }
public static async void PostTrainStation(HttpContent data) { string url = "https://api.trafikinfo.trafikverket.se/v2/data.json"; int errorCountyNo = 0; using (HttpResponseMessage response = await ApiHelper.ApiClient.PostAsync(url, data)) { if (response.IsSuccessStatusCode) { string fromTrafikverket = await response.Content.ReadAsStringAsync(); JObject jsonObject = JObject.Parse(fromTrafikverket); // json objectet från trafikverket har strukturen ("RESPONSE") ("RESULT") [ ("TrainStation") ] var trainStations = jsonObject.SelectToken("RESPONSE").SelectToken("RESULT")[0].SelectToken("TrainStation"); MongoCRUD db = new MongoCRUD("admin"); foreach (var message in trainStations) { TrafikverketTrainStationModel model = new TrafikverketTrainStationModel(); model.AdvertisedLocationName = message[key : "AdvertisedLocationName"].ToString(); model.LocationSignature = message[key : "LocationSignature"].ToString(); try { model.CountyNo = message[key : "CountyNo"][0].ToString(); } catch { errorCountyNo += 1; } JToken geo = message[key : "Geometry"]; JToken wgs84 = geo[key : "WGS84"]; string pointstring = wgs84.ToString(); // Regex för att ta bort "POINT" från fältet och sedan "( )" pointstring = Regex.Replace(pointstring, "POINT", ""); pointstring = Regex.Replace(pointstring, @"[()]", ""); // delar stringen på alla mellanrum. !OBS fältet startar med mellanrum vilket skapar 3! delar string[] substring = Regex.Split(pointstring, " "); // plockar upp och delar ut cordinaterna, mest för läsbarhet och att inte råka skicka med mellanrummet string[] coords = { substring[1], substring[2] }; model.Longitude = float.Parse(coords[0], CultureInfo.InvariantCulture); model.Latitude = float.Parse(coords[1], CultureInfo.InvariantCulture); // Fortsättning på kod, läs upp från databasen för att kolla efter dubbleter i DB db.InsertRecord(Trafikverket.station, model); } Console.WriteLine("Failed to get " + errorCountyNo + " number of county numbers from API"); } else { Console.WriteLine("!!FEL VID KONTAKT MED API!!"); throw new Exception(response.ReasonPhrase); } } }