public async Task Upsert(string table, TrafikverketTrainAnnouncementModel record, string ActivityId) { var collection = db.GetCollection <TrafikverketTrainAnnouncementModel>(table); collection.ReplaceOne(filter: (u => u.ActivityId == ActivityId), options: new UpdateOptions { IsUpsert = true }, replacement: record); }
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); } } }