//return the current latitude of the flight. //calculate the current latitude of the flight according to the Proportional percentage //of the flight route so far. public double calculateLat(int i, FlightPlan FlightPlan, string relativeTo) { //DataTime TimeSpan segmentInitialTime; if (i == 0) { segmentInitialTime = TimeSpan.Parse(FlightPlan.loc.date_time.Substring(11, 8)); } else { segmentInitialTime = TimeSpan.Parse(FlightPlan.segmentsList[i - 1].endTime.Substring(11, 8)); } TimeSpan now = TimeSpan.Parse(relativeTo.Substring(11, 8)); TimeSpan current = now - segmentInitialTime; double secondCurrentTime = current.TotalSeconds; int timeSpandSecond = FlightPlan.segmentsList[i].timespan_seconds; double startLoc; if (i == 0) { startLoc = FlightPlan.loc.latitude; } else { startLoc = FlightPlan.segmentsList[i - 1].latitude; } double endLoc = FlightPlan.segmentsList[i].latitude; double currentLoc = (((endLoc - startLoc)) * (secondCurrentTime / timeSpandSecond)) + startLoc; return(currentLoc); }
public Coordinate CurrentPlace(string current, FlightPlan flightPlan, double diff) { List <Segment> s = flightPlan.Segments; int findIndex = this.FindIndexSegment(s, diff); double latStart, longStart, latEnd, longEnd; if (findIndex == 0) { latStart = flightPlan.Initial_Location.Latitude; longStart = flightPlan.Initial_Location.Longitude; latEnd = s[findIndex].Latitude; longEnd = s[findIndex].Longitude; } else { latStart = s[findIndex - 1].Latitude; longStart = s[findIndex - 1].Longitude; latEnd = s[findIndex].Latitude; longEnd = s[findIndex].Longitude; } //use divide line to parts equation //find the time from the begin to the current in the spesfic segment double left = diff - SumTimeSpan(s, findIndex); //find the left time double right = s[findIndex].Timespan_Seconds - left; double currentlat = (latStart * right + latEnd * left) / (left + right); double currentlong = (longStart * right + longEnd * left) / (left + right); Coordinate currentP = new Coordinate(currentlat, currentlong); return(currentP); }
public FlightPlan addFlightPlan(FlightPlan flightPlan) { // generate ID function string uniqueID = generateUniqueID(flightPlan.company_name); // post into Initial_Locations table Initial_Location initial_Location = flightPlan.initial_location; string dateString = "'" + initial_Location.date_time .ToString("yyyy-MM-ddTHH:mm:ssZ") + "'"; string postQuery_Initial_Locations = "INSERT INTO Initial_Locations(Longitude, " + "Latitude, Date) VALUES(@longitude, @latitude, " + dateString + ")"; DataMan.ExcuteQuery(postQuery_Initial_Locations, initial_Location); // post into FlightPlans table string getQuery_extractInitialLocationID = "SELECT ID FROM " + "Initial_Locations ORDER BY ID DESC LIMIT 1"; var x = DataMan.ExcuteQuery(getQuery_extractInitialLocationID); int lastIDFromInitialLocations = (int)x.ToList()[0].ID; string postQuery_FlightPlans = "INSERT INTO " + "FlightPlans(ID, Company, Passengers, Initial_Location_ID)" + " VALUES('" + uniqueID + "',@company_name, @passengers, " + lastIDFromInitialLocations + ")"; DataMan.ExcuteQuery(postQuery_FlightPlans, flightPlan); // post into Segments table string postQuery_Segment = ""; foreach (Segment segment in flightPlan.segments) { postQuery_Segment = "INSERT INTO Segments(Longitude, Latitude, TimeSpan, " + "Flight_ID) VALUES(@longitude, @latitude, @timespan_seconds, '" + uniqueID + "')"; DataMan.ExcuteQuery(postQuery_Segment, segment); } return(flightPlan); }
//check if the flight is still active and return the answer. public bool activeFligth(FlightPlan FlightPlanObject, string relativeTo) { TimeSpan now = TimeSpan.Parse(relativeTo.Substring(11, 8)); TimeSpan start = TimeSpan.Parse(FlightPlanObject.loc.date_time.Substring(11, 8)); int numSegments = FlightPlanObject.segmentsList.Count; TimeSpan end = TimeSpan.Parse(FlightPlanObject.segmentsList[numSegments - 1].endTime.Substring(11, 8)); if (start <= end) { // start and stop times are in the same day if (now >= start && now <= end) { // current time is between start and stop return(true); } } else { // start and stop times are in different days if (now >= start || now <= end) { // current time is between start and stop return(true); } } return(false); }
public void DeleteFlight(string id) { // Try to remove the Flight with this id. FlightPlan flightPlan = dicFlightPlans[id]; dicFlightPlans.TryRemove(id, out flightPlan); }
// Insert flight plan to dictionary public string InsertFlightPlan(FlightPlan flightPlan) { if (!IsValidFlightPlan(flightPlan)) { throw new Exception("Not a valid flight plan"); } // Checks if date and tine are in format and throws execption if not. DateTime.Parse(flightPlan.Location.DateTime); string flightId = null; // Tries 30 times to give a unique id that is not in dictionary. int numOfTries = 30; int i = 0; for (; i < numOfTries; i++) { flightId = MakeUniqueId(); if (!flightPlans.ContainsKey(flightId)) { flightPlans[flightId] = flightPlan; break; } } if (i == numOfTries) { flightId = null; } return(flightId); }
//create a flight plan from json element and insert to cache. public void getJson(JsonElement value) { FlightPlan FlightPlanObject = createFlightPlanFronJson(value); AddToCache(FlightPlanObject); AddFlightPlan(FlightPlanObject); }
/** * Get the current flight location using linear interpolation **/ public static Tuple <double, double> GetLocation(FlightPlan flightPlan, int index, DateTime currentTime, DateTime timeFromTakeOff) { Segment currentSegment; if (index == 0) { // initialize the first segment currentSegment = new Segment(flightPlan.Id, flightPlan.InitialLocation.Longitude, flightPlan.InitialLocation.Latitude, 0); } else { currentSegment = flightPlan.Segments.ElementAt(index - 1); } // get the last position flight and the new position double startLon = currentSegment.Longitude; double endLon = flightPlan.Segments.ElementAt(index).Longitude; double startLat = currentSegment.Latitude; double endLat = flightPlan.Segments.ElementAt(index).Latitude; double longitude = LinearInterpolation(startLon, endLon, timeFromTakeOff, flightPlan.Segments.ElementAt(index).TimespanSeconds, currentTime); double latitude = LinearInterpolation(startLat, endLat, timeFromTakeOff, flightPlan.Segments.ElementAt(index).TimespanSeconds, currentTime); // return the updated location return(Tuple.Create(longitude, latitude)); }
//return FlightPlan by Id public FlightPlan getFlightPlanById(IMemoryCache cache, string Id) { FlightPlan FlightPlan = null; IFlightManager FlightManager = new FlightManager(); if (cache.TryGetValue("FlightPlanDictionary", out FlightPlanDictionary)) { //Id = Id.Substring(1, Id.Length - 2); if (!FlightPlanDictionary.TryGetValue(Id, out FlightPlan)) { Console.WriteLine("error"); } } ServerManager serverManager = new ServerManager(); Dictionary <string, string> IdFromServer = serverManager.getIdFromServer(); string serverId; if (Id[0] == '{') { Id = Id.Substring(1, Id.Length - 2); } if (IdFromServer.TryGetValue(Id, out serverId)) { //get Flights plan from external server by id FlightPlan = serverManager.externalFlightPlanById(Id, serverId); } return(FlightPlan); }
//calculate the arrival time of the flight. public string TimeCalculate(string dataTime, int i, int timespanSecond, FlightPlan FlightPlanObject) { DateTime segmentInitialTime; DateTime segmentEndTime; if (i == 0) { string initialTime = parseTime(dataTime); segmentInitialTime = DateTime.Parse(initialTime); } else { segmentInitialTime = DateTime.Parse(FlightPlanObject.segmentsList[i - 1].endTime); } TimeSpan t = TimeSpan.FromSeconds(timespanSecond); string answer = string.Format("{0:D2}:{1:D2}:{2:D2}", t.Hours, t.Minutes, t.Seconds, t.Milliseconds); segmentEndTime = segmentInitialTime + TimeSpan.Parse(answer); return(segmentEndTime.ToString()); }
public FlightPlan createFP(string input) { dynamic obj = JsonConvert.DeserializeObject(input); FlightPlan newPlan; try { newPlan = new FlightPlan { company_name = obj["company_name"], passengers = obj["passengers"], initial_location = new initial_location { longitude = obj["initial_location"]["longitude"], latitude = obj["initial_location"]["latitude"], date_time = obj["initial_location"]["date_time"] }, segments = new List <Segment>() }; } catch (Exception e) { return(null); } idCreate(newPlan); createSegments(newPlan, input); return(newPlan); }
public async Task <FlightPlan> serverGet(Server server, string id) { HttpWebResponse response; FlightPlan flightList = null; try { string request = server.ServerURL + "/api/FlightPlan/" + id; string url = string.Format(request); WebRequest objre = WebRequest.Create(url); objre.Method = "GET"; // get response from the extrnal server response = (HttpWebResponse)await objre.GetResponseAsync(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); // makeing new list of flight if (checkInput(responseFromServer)) { flightList = JsonConvert.DeserializeObject <FlightPlan>(responseFromServer); } } catch (Exception e) { e.ToString(); } return(flightList); }
/* * Connects to the server and sends a request for the * flight plan with the given id. The flight plan necesserily * belongs to this server. */ public FlightPlan GetFlightFromServer(Server toGetFrom, string id) { FlightPlan fromServerFlightPlan = FlightPlan.NullFlightPlan; try { var response = GetResponse(toGetFrom, id); response.Wait(); HttpResponseMessage responseFromServer = response.Result; responseFromServer.EnsureSuccessStatusCode(); Task <string> responseBody = responseFromServer.Content.ReadAsStringAsync(); responseBody.Wait(); string content = responseBody.Result; JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); fromServerFlightPlan = javaScriptSerializer.Deserialize <FlightPlan>(content); dynamic response_d = JsonConvert.DeserializeObject(content); LinkedList <Segment> segments = response_d.segments.ToObject <LinkedList <Segment> >(); fromServerFlightPlan.Segments = segments; return(fromServerFlightPlan); } catch (HttpRequestException) { fromServerFlightPlan = FlightPlan.NullFlightPlan; fromServerFlightPlan.Passengers = -2; } catch (SocketException) { } catch (AggregateException) { } return(fromServerFlightPlan); }
internal bool IsFlightValid(FlightPlan flightPlan) { if (flightPlan.InitialLocation == null || flightPlan.Segments == null) { return(false); } foreach (Segment seg in flightPlan.Segments) { if (seg.Latitude < -90 || seg.Latitude > 90) { return(false); } if (seg.Longitude < -180 || seg.Longitude > 180) { return(false); } if (seg.TimeInSeconds == 0) { return(false); } } if (flightPlan.InitialLocation.Longitude < -180 || flightPlan.InitialLocation.Longitude > 180 || flightPlan.InitialLocation.Latitude < -90 || flightPlan.InitialLocation.Latitude > 90) { return(false); } return(true); }
private void CreateFlightPlan(string id, JObject jsonFlightPlan, FlightPlan tempFlightPlan) { tempFlightPlan.Company_Name = (string)jsonFlightPlan["company_name"]; tempFlightPlan.Flight_Id = id; tempFlightPlan.Initial_Location = new LocationAndTime(); tempFlightPlan.Initial_Location.Latitude = (double)jsonFlightPlan["initial_location"]["latitude"]; tempFlightPlan.Initial_Location.Longitude = (double)jsonFlightPlan["initial_location"]["longitude"]; tempFlightPlan.Initial_Location.StartTime = (DateTime)jsonFlightPlan["initial_location"]["date_time"]; tempFlightPlan.Initial_Location.StartTime = tempFlightPlan.Initial_Location.StartTime.ToUniversalTime(); tempFlightPlan.Passengers = (int)jsonFlightPlan["passengers"]; tempFlightPlan.Segments = new List <Segment>(); // adding each segment foreach (var segment in jsonFlightPlan["segments"]) { Segment segmentTemp = new Segment(); segmentTemp.Latitude = (double)segment["latitude"]; segmentTemp.Longitude = (double)segment["longitude"]; segmentTemp.Timespan_seconds = (int)segment["timespan_seconds"]; if (!segmentTemp.IsValidSegment()) { tempFlightPlan.Segments.Add(segmentTemp); } } }
// Create a FlightPlan object from a json file. private FlightPlan CreateFlightPlanFromJson(string strResult) { FlightPlan flightPlan = new FlightPlan(); var json = JObject.Parse(strResult); flightPlan.CompanyName = json["company_name"].ToString(); double longitude = Convert.ToDouble(json["initial_location"]["longitude"]); double latitude = Convert.ToDouble(json["initial_location"]["latitude"]); DateTime dateTime = Convert.ToDateTime(json["initial_location"]["date_time"]); Location location = new Location(longitude, latitude, dateTime); flightPlan.InitialLocation = location; flightPlan.Passengers = Convert.ToInt32(json["passengers"]); List <Segment> segments = new List <Segment>(); JArray items = (JArray)json["segments"]; int length = items.Count; // Create segments. for (int i = 0; i < length; i++) { double longitude1 = Convert.ToDouble(json["segments"][i]["longitude"]); double latitude1 = Convert.ToDouble(json["segments"][i]["latitude"]); int timespnaSeconds = Convert.ToInt32(json["segments"][i]["timespan_seconds"]); Segment segment = new Segment(longitude1, latitude1, timespnaSeconds); segments.Add(segment); } flightPlan.Segments = segments; return(flightPlan); }
public string AddFlight(FlightPlan fp) { // valid field check if (fp.company_name == null) { throw new ArgumentException("company name must be provided"); } if (fp.passengers < 0) { throw new ArgumentOutOfRangeException("number of passengers cannot be less then 0"); } if (fp.segments == null) { throw new ArgumentException("there must be at list one segments"); } //existens check string key = GetId(fp); if (key != null) { return(key); } FlightPlan x = fp; Random rnd = new Random(); key = GenerateNewRandom(); bool item = flights.TryAdd(key, fp); return(key); }
/** * Checks if flight is happening at the given time **/ public static bool IsActive(FlightPlan flightPlan, DateTime time) { // if the departure didn't happen yet if (flightPlan.InitialLocation.DateTime.Ticks > time.Ticks) { return(false); } else { double segmentsTime = 0; // calculate all the segments timespan of the flight foreach (Segment segment in flightPlan.Segments) { segmentsTime += segment.TimespanSeconds; } // calculate the time of landing DateTime totalFlightTime = flightPlan.InitialLocation.DateTime.AddSeconds(segmentsTime); // return true if the flight hasn't landed yet if (DateTime.Compare(totalFlightTime, time) > 0) { return(true); } return(false); } }
public async Task <FlightPlan> GetExternalFlightPlanAsync(string id) { FlightPlan flightPlan = null; try { //get the server that has the flightPlan string serverId = flightplanServer[id]; ServerFlight s = db.GetServerById(serverId); if (serverId == null) { return(null); } string url = "api/FlightPlan/" + id; //build new http client to new request HttpClient httpClient = BuildHttpClient(s); try { //get string response and convert to object flight plan string resp = await ResponceAsync(httpClient, url); flightPlan = JsonConvert.DeserializeObject <FlightPlan>(resp); } catch (Exception) { //Console.WriteLine("failed in external filghtPlan by id get response"); } } catch //no server has the flight plan { flightPlan = null; } return(flightPlan); }
// Sets current location of the flight. private Flight GetFlightWithCurrentLocation(DateTime initialTime, DateTime givenTime, FlightPlan plan, bool isExternal, string id) { var initialLocation = new Tuple <double, double>(plan.Location.Longitude, plan.Location.Latitude); // go over all segments of flight and checks of it's inside it foreach (var segment in plan.Segments) { double seconds = segment.TimeSpanSeconds; var endLocation = new Tuple <double, double>(segment.Longitude, segment.Latitude); DateTime endTime = initialTime.AddSeconds(seconds); // if it's inside the segment get the current location according to time if (givenTime >= initialTime && givenTime < endTime) { // Gets the current location. var currentLocation = Interpolation(initialLocation, endLocation, initialTime, givenTime, seconds); var flight = new Flight(id, isExternal, plan) { Longitude = currentLocation.Item1, Latitude = currentLocation.Item2 }; return(flight); } initialTime = endTime; initialLocation = endLocation; } return(null); }
/* * Get all the flights realtive to DatTime dt1. * create flight object for each appropiate Flight Plan */ private Flight[] GetsFlightsHelper(DateTime dt1) { List <Tuple <string, FlightPlan> > list = GetFlightPlanFromDb(); Flight flight = null; List <Flight> flightList = new List <Flight>(); foreach (Tuple <string, FlightPlan> tuple in list) { FlightPlan flightPlan = tuple.Item2; if (flightPlan == null) { continue; } DateTime dt2 = DateTime.Parse(flightPlan.InitialLocation.DateTime); if (DateTime.Compare(dt1, dt2) < 0) { continue; } flight = CheckFlightPlan(flightPlan, dt1, dt2, tuple.Item1); if (flight != null) { flightList.Add(flight); } } return(flightList.ToArray()); }
//create a random id for a flight plan public string CreateIdentifier(FlightPlan flightPlan) { StringBuilder builder = new StringBuilder(); Random random = new Random(); int length = random.Next(6, 11); string companyStr = flightPlan.CompanyName; int companyNmLen = flightPlan.CompanyName.Length; int j = 0; for (int i = 0; i < 3; i++) { char c = Char.ToUpper(companyStr[j % companyNmLen]); if (c >= 'A' && c <= 'Z') { builder.Append(c); j++; } else { i--; j++; } } for (int i = 0; i < length - 3; i++) { builder.Append(random.Next(0, 10)); } return(builder.ToString()); }
// Add a given FlightPlan into the data base. public string AddFlightPlan(FlightPlan fp) { string id = SetId(); dataAccess.InsertFlightPlan(fp, id); return(id); }
// Equals override for FlightPlan. public override bool Equals(Object other) { FlightPlan otherFlightPlan = (FlightPlan)other; if (this.CompanyName.CompareTo(otherFlightPlan.CompanyName) != 0) { return(false); } if (this.Passengers != otherFlightPlan.Passengers) { return(false); } if (!(this.InitialLocation.Equals(otherFlightPlan.InitialLocation))) { return(false); } int i = 0; int size = this.Segments.Count <= otherFlightPlan.Segments.Count ? this.Segments.Count : otherFlightPlan.Segments.Count; for (i = 0; i < size; i++) { Segment thisSegment = this.Segments[i]; Segment otherSegment = otherFlightPlan.Segments[i]; if (!thisSegment.Equals(otherSegment)) { return(false); } } return(true); }
internal FlightPlan CreateNewFlightPlan(FlightPlan flightPlan) { //generate random id string FlightId = generator.GanerateId(); flightPlan.Id = FlightId; db.FlightPlans.Add(flightPlan); //adding all segments to DB int segmentNum = 1; foreach (Segment element in flightPlan.Segments) { //adding segment number for segments in the same flight plan element.SegmentNumber = segmentNum; segmentNum++; element.FlightId = FlightId; element.Id = generator.GanerateId(); db.Segments.Add(element); } //adding InitialLocation to DB flightPlan.InitialLocation.FlightId = FlightId; flightPlan.InitialLocation.Id = generator.GanerateId(); db.InitLocations.Add(flightPlan.InitialLocation); db.SaveChanges(); return(flightPlan); }
private async Task <FlightPlan> GetFlightPlanFromServer(string url, string id) { FlightPlan retFP = null; HttpClient client = new HttpClient(); client.Timeout = TimeSpan.FromSeconds(2); HttpResponseMessage response = null; try { response = await client.GetAsync(url + "/api/FlightPlan/" + id , HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); } catch (Exception) { throw new Exception("Cannot get an answer from: " + url); } if (response != null && response.IsSuccessStatusCode) { var settings = new JsonSerializerSettings(); settings.ContractResolver = new CustomContractResolver(); // Get the response var customerJsonString = await response.Content.ReadAsStringAsync(); // Deserialise the data retFP = JsonConvert.DeserializeObject <FlightPlan>(customerJsonString, settings); } if (retFP == null) { throw new Exception("There was a problem getting the flight plan with the id: " + id + " from: " + url); } return(retFP); }
private async void findCurrSeg(FlightPlan flightPlan, DBContext context, Flight flightFromPlan, DateTime relativeDate) { double longBegin = flightPlan.Initial_location.Longitude; double latBegin = flightPlan.Initial_location.Latitude; List <Segment> segment = await context.Segments.ToListAsync(); DateTime begin; DateTime end = TimeZoneInfo.ConvertTimeToUtc(DateTime.Parse(getInitialLocation(flightPlan, context).date_time)); foreach (Segment s in segment) { if (beginWith(s.id, flightPlan.id)) { begin = end; end = begin.AddSeconds(s.timespan_seconds); //check if the flight is now: //if begin < relative: res is - int beginCompRel = DateTime.Compare(begin, relativeDate); //if relative < end: res is - int endCompRel = DateTime.Compare(relativeDate, end); if (beginCompRel <= 0 && endCompRel <= 0) { double relativeTimePassed = (relativeDate - begin).TotalSeconds / (end - begin).TotalSeconds; flightFromPlan.longitude = longBegin + relativeTimePassed * (s.Longitude - longBegin); flightFromPlan.latitude = latBegin + relativeTimePassed * (s.Latitude - latBegin); break; } } longBegin = s.Longitude; latBegin = s.Latitude; } }
// get the location of the given flight plan relative to the given dateTime private Tuple <double, double> GetLocation(FlightPlan flightPlan, DateTime dateTime) { double longitude = flightPlan.InitialLocation.Longitude; double latitude = flightPlan.InitialLocation.Latitude; var startTime = flightPlan.InitialLocation.MyDateTime; double timeGap = (dateTime - startTime).TotalSeconds; double distance; double ratio; // if the given time is the initial time if (timeGap == 0) { return(new Tuple <double, double>(longitude, latitude)); } foreach (FlightSegment currentSegment in flightPlan.Segments) { // if the given time is in this segment if (timeGap <= currentSegment.TimespanSeconds) { // get the time ratio ratio = timeGap / currentSegment.TimespanSeconds; // calculate the new longitude and latitude with the ratio addition distance = currentSegment.Longitude - longitude; longitude += ratio * distance; distance = currentSegment.Latitude - latitude; latitude += ratio * distance; break; } // remove this segment time timeGap -= currentSegment.TimespanSeconds; longitude = currentSegment.Longitude; latitude = currentSegment.Latitude; } return(new Tuple <double, double>(longitude, latitude)); }
private void AddFlightPlanToCache(FlightPlan fp, string id) { List <FlightPlan> flightPlans = GetFlightPlans(); Dictionary <string, FlightPlan> flightIds = GetFlightIds(); flightIds.Add(id, fp); flightPlans.Add(fp); SaveFlightPlansAndIds(flightPlans, flightIds); }
//This function adds new flight plan to the flight plans list public void AddFlight(FlightPlan f) { string id = flightManager.GenerateId(); Flight flight = new Flight(f, id); flightManager.AddFlight(flight); f.FlightId = id; flightPlans.Add(f); }