Exemplo n.º 1
0
        // if prepare is false, don't show it!
        public bool Prepare(DbFace dbface, string lastrun)
        {
            // Try to look up any new annoucements
            List<Dictionary<string, object>> rows = dbface.AssocEnumerate(string.Format("select * from announces where date_created > '{0} 23:59' order by id asc", DbFace.EscapeSingles(lastrun)));
            if (rows != null && rows.Count == 0)
                rows = null;

            // Are there any messages to display?
            if (userMessages.Count == 0 && rows == null)
                return false;

            // fill out the messages box
            StringBuilder messages = new StringBuilder();
            // basic definitions
            messages.Append("{\\rtf1\\ansi\\deff0{\\colortbl;\\red0\\green0\\blue0;\\red128\\green128\\blue0;}");
            foreach (string message in userMessages) {
                messages.AppendLine("\\cf2");
                messages.AppendLine("\\bullet  " + message + "\\line");
            }

            // Add in any annoucements
            if (rows != null)
            {
                foreach (Dictionary<string, object> row in rows)
                {
                    messages.AppendLine("\\bullet {\\b " + row["subject"] + "}\\line\\line");
                    messages.AppendLine(row["body"] + "\\line\\line");
                }
            }
            messages.AppendLine("}");

            rtbMessages.Rtf = messages.ToString();
            return true;
        }
Exemplo n.º 2
0
        public AirportFinder(TextBox txtOrigins, DbFace dbface, StatusManager status)
        {
            this.txtOrigins = txtOrigins;
            idleEnumerator = null;

            InitializeComponent();

            // Collect All Airports
            airports = Airport.LoadAllAirports(dbface, "country asc");
            if (airports == null)
            {
                status.AddNow("Could not access airport information", 0, 0);
                this.Close();
                return;
            }

            txtSearch.Text = "";

            catalog = new Dictionary<string,Airport>();

            // Display all airports
            foreach (Airport airport in airports)
            {
                string line = airport.ToString();
                catalog.Add(line.ToLower(), airport);
                lstAirports.Items.Add(airport);
            }
        }
Exemplo n.º 3
0
        public SelectDestinations(DbFace dbface, StatusManager status)
        {
            this.dbface = dbface;

            InitializeComponent();

            // Select all countries and their airports
            List<Airport> airports = Airport.LoadAllAirports(dbface, "country asc");

            if (airports == null)
            {
                status.AddNow("Could not access airport information", 0, 0);
                this.Close();
                return;
            }

            TreeNode node = null;   // the current node we're adding t
            int lastchecked = 0, lastunchecked = 0;
            foreach (Airport airport in airports)
            {
                string country = airport.Country;
                if (node == null || node.Text != country)
                {
                    if (node != null)
                    {
                        if (lastchecked == 0)
                            node.StateImageIndex = 0;
                        else if (lastunchecked == 0)
                            node.StateImageIndex = 1;
                        else
                            node.StateImageIndex = 2;
                    }

                    lastchecked = lastunchecked = 0;

                    // need to add the country
                    node = destinations.Nodes.Add(country, country);
                }

                // Add this
                TreeNode child = node.Nodes.Add(airport.Code, airport.Title + " (" + airport.Code + ")");
                child.StateImageIndex = airport.IsEnabled ? 1 : 0;
                if (airport.IsEnabled)
                    lastchecked++;
                else
                    lastunchecked++;
            }

            if (lastchecked == 0)
                node.StateImageIndex = 0;
            else if (lastunchecked == 0)
                node.StateImageIndex = 1;
            else
                node.StateImageIndex = 2;
        }
Exemplo n.º 4
0
        public FlightViewBox(Flight flight, DbFace dbface)
        {
            InitializeComponent();

            this.flight = flight;

            // Fill out all the data files
            lblOrigin.Text = Airport.GetAirport(flight.Origin, dbface).ToString();
            lblDestination.Text = Airport.GetAirport(flight.Destination, dbface).ToString();
            lblLeave.Text = flight.DateLeave.ToString("M/d/yyyy");
            lblReturn.Text = flight.DateReturn.ToString("M/d/yyyy");
            lblPrice.Text = "$" + flight.Price.ToString();
            lblDistance.Text = flight.Km.ToString() + " km";
            TimeSpan span = DateTime.Now.Subtract(flight.LastChecked);
            if (span.Days > 0)
                lblLastChecked.Text = span.Days + " days and " + span.Hours + " hours ago";
            else
                lblLastChecked.Text = span.Hours + " hours ago";

            lblLink.Text = "http://www.orbitz.com/";
        }
Exemplo n.º 5
0
        public AtoCFlightViewBox(AtoCFlight flight, DbFace dbface)
        {
            InitializeComponent();

            this.flight = flight;

            // Fill out all the data files
            lblPointA.Text = Airport.GetAirport(flight.PointA, dbface).ToString();
            lblPointB.Text = Airport.GetAirport(flight.PointB, dbface).ToString();
            lblPointC.Text = Airport.GetAirport(flight.PointC, dbface).ToString();
            lblDate_AtoB.Text = flight.Date_AtoB.ToString("M/d/yyyy");
            lblDate_BtoC.Text = flight.Date_BtoC.ToString("M/d/yyyy");
            lblPrice.Text = "$" + flight.Price_AtoB.ToString() + " + $" + flight.Price_BtoC.ToString();
            lblDistance.Text = flight.Km_AtoB.ToString() + " km + " + flight.Km_BtoC.ToString() + " km";
            TimeSpan span = DateTime.Now.Subtract(flight.LastChecked);
            if (span.Days > 0)
                lblLastChecked.Text = span.Days + " days and " + span.Hours + " hours ago";
            else
                lblLastChecked.Text = span.Hours + " hours ago";

            lblLink.Text = "http://www.orbitz.com/";
        }
Exemplo n.º 6
0
        public MainWindow()
        {
            // The announcements may include configuration errors and community-wide notices
            Announcements announcer = new Announcements();

            InitializeComponent();

            // set up our connection to the database
            masterdbface = new DbFace();
            source = "orbitz";
            user = GetIpAddress();

            // read the configuration file
            DateTime earlyDate, lateDate;
            if (!DateTime.TryParse(ConfigurationManager.AppSettings["earliest"], out earlyDate))
            {
                announcer.AddMessage("Could not understand 'earliest' configuration date format; resetting to today.");
                earlyDate = DateTime.Now;
            }
            if (!DateTime.TryParse(ConfigurationManager.AppSettings["latest"], out lateDate))
            {
                announcer.AddMessage("Could not understand 'latest' configuration date format; resetting to five months from now.");
                lateDate = DateTime.Now.AddMonths(5);
            }
            // adjust the dates to maintain the difference
            if (earlyDate < DateTime.Now)
            {
                TimeSpan diff = lateDate.Subtract(earlyDate);
                earlyDate = DateTime.Now;
                lateDate = DateTime.Now.Add(diff);
            }
            else if (lateDate < DateTime.Now)
            {
                announcer.AddMessage("Invalid 'latest' date; resetting to five months from 'earliest'.");
                lateDate = earlyDate.AddMonths(5);
            }
            earliest.Value = earlyDate;
            latest.Value = lateDate;

            int shortNumber, longNumber;
            if (!int.TryParse(ConfigurationManager.AppSettings["shortest"], out shortNumber))
            {
                announcer.AddMessage("The 'shortest' configuration is not a number; resetting to 5");
                shortNumber = 5;
            }
            if (!int.TryParse(ConfigurationManager.AppSettings["longest"], out longNumber))
            {
                announcer.AddMessage("The 'longest' configuration is not a number; resetting to 12");
                longNumber = 12;
            }

            shortest.Text = shortNumber.ToString();
            longest.Text = longNumber.ToString();

            txtOrigins.Text = ConfigurationManager.AppSettings["origins"];
            if (txtOrigins.Text == null || txtOrigins.Text.Length == 0) {
                announcer.AddMessage("The 'origins' configuration is missing: resetting to JFK, LGA, EWR, DCA, BWI, IAD, BOS");
                txtOrigins.Text = "JFK, LGA, EWR, DCA, BWI, IAD, BOS";
            }

            txtPointA.Text = ConfigurationManager.AppSettings["pointas"];
            if (txtPointA.Text == null || txtPointA.Text.Length == 0) {
                announcer.AddMessage("The 'pointas' configuration is missing: resetting to JFK, LGA, EWR");
                txtPointA.Text = "JFK, LGA, EWR";
            }
            txtPointC.Text = ConfigurationManager.AppSettings["pointcs"];
            if (txtPointC.Text == null || txtPointC.Text.Length == 0) {
                announcer.AddMessage("The 'pointcs' configuration is missing: resetting to DCA, BWI, IAD");
                txtPointC.Text = "DCA, BWI, IAD";
            }

            if (ConfigurationManager.AppSettings["mode"] != null)
                cmbSearch.SelectedText = ConfigurationManager.AppSettings["mode"];

            Airport.DisableCodes(ConfigurationManager.AppSettings["disabled"], masterdbface);

            int simulNumber;
            if (!int.TryParse(ConfigurationManager.AppSettings["simultaneous"], out simulNumber))
            {
                announcer.AddMessage("The 'simultaneous' configuration is not a number: resetting to 2");
                simulNumber = 2;
            }
            else if (simulNumber > 9)
            {
                announcer.AddMessage("The 'simultaneous' configuration is more than 9; resetting to 9");
                simulNumber = 9;
            }
            numSimul.Value = simulNumber;

            cmbSearch.SelectedIndex = 0;

            results = new OrderedListBox(lstResults);
            status = new StatusManager(statusStrip1, toolStripStatusLabel1, toolStripProgressBar1);

            lstResults.Click += this.lstResults_SelectedIndexChanged;
            FormClosing += Form1_Closing;
            Application.Idle += OnIdle;
            status.AddNow("Initialized.", 1, 0);

            // display the annoucements box
            DateTime lastrun = DateTime.Now;
            if (!DateTime.TryParse(ConfigurationManager.AppSettings["lastrun"], out lastrun))
                lastrun = DateTime.Now;

            if (announcer.Prepare(masterdbface, MyDate(lastrun)))
                announcer.Show();
        }
Exemplo n.º 7
0
        // Get a random airport, based on salience.  Defaults to BOS, if there's an error.
        public static string GetSalientAirportCode(DbFace dbface)
        {
            lock (dbface)
            {
                List<Dictionary<string, object>> rows = dbface.AssocEnumerate("select * from airports order by salience * rand() desc limit " + (countDisabled + 1));
                if (rows == null)
                    return "BOS";

                foreach (Dictionary<string, object> row in rows)
                {
                    Airport airport = RecordAirport(row);
                    if (!airport.enabled)
                        continue;

                    return airport.code;
                }

                return "BOS";
            }
        }
Exemplo n.º 8
0
        public static List<Airport> LoadAllAirports(DbFace dbface, string order)
        {
            string sql = "select * from airports";
            if (!string.IsNullOrEmpty(order))
                sql += " order by " + order;

            List<Dictionary<string, object>> rows = dbface.AssocEnumerate(sql);
            if (rows == null)
                return null; // failed!

            List<Airport> airports = new List<Airport>();
            foreach (Dictionary<string, object> row in rows)
                airports.Add(Airport.RecordAirport(row));

            return airports;
        }
Exemplo n.º 9
0
        // Disable the airports described in this list
        public static void DisableCodes(string list, DbFace dbface)
        {
            if (list == null)
                return;

            string[] codes = ParseAirportCodes(list);
            if (codes.Length > 20)
            {
                // First cache all airports
                LoadAllAirports(dbface, null);
            }

            foreach (string code in codes)
                GetAirport(code, dbface).IsEnabled = false;
        }
Exemplo n.º 10
0
        // Get an airport, either from the cache or the database
        public static Airport GetAirport(string code, DbFace dbface)
        {
            lock (cache)
            {
                // look in the cache
                Airport airport;
                if (cache.TryGetValue(code, out airport))
                    return airport;

                // look in the database
                List<Dictionary<string, object>> rows = dbface.AssocEnumerate(string.Format("select * from airports where code = '{0}' limit 1", code));
                if (rows == null || rows.Count != 1)
                    return new Airport(code, "Unknown", "Unknown");

                Dictionary<string, object> row = rows[0];

                airport = new Airport((string)row["code"], (string)row["title"], (string)row["country"]);
                cache[code] = airport;

                return airport;
            }
        }
Exemplo n.º 11
0
        // Collect new results given the search criteria
        public void CollectNewRoundTrips()
        {
            DbFace dbface = new DbFace();
            Random randgen = new Random();

            string[] origins = Airport.ParseAirportCodes(txtOrigins.Text);

            while (searching)
            {
                if (!TestDbFace(ref dbface))
                    continue;
                if (origins.Length < 1)
                {
                    status.Add("ERROR: Please add some origin airports!");
                    return;
                }

                // set up the specific query parameters
                string origin = origins[randgen.Next(origins.Length)];
                string destination = Airport.GetSalientAirportCode(dbface);
                status.Add(string.Format("Checking price from {0} to {1}", origin, destination));

                if (origin == destination)
                    continue;

                TimeSpan range = latest.Value.Subtract(earliest.Value);
                DateTime start = earliest.Value.AddDays(randgen.NextDouble() * range.Days);

                int shortdays = GetNum(shortest.Text, false).Value;
                int longdays = GetNum(longest.Text, false).Value;
                DateTime end = start.AddDays(randgen.Next(shortdays, longdays));

                // Try to look up the price
                int price = GetPrice(origin, destination, start, end);
                if (price == int.MaxValue)
                {
                    status.Add(string.Format("Failed to get price from {0} to {1}", origin, destination));
                    continue;
                }
                status.Add(string.Format("Price from {0} to {1}: ${2}", origin, destination, price));

                // get the distance involved
                int distance = GetDistance(origin, destination, dbface);

                RecordOption(origin, destination, start, end, price, distance, dbface);
            }
        }
Exemplo n.º 12
0
        public void CollectNewAtoCs()
        {
            DbFace dbface = new DbFace();
            Random randgen = new Random();

            string[] pointas = Airport.ParseAirportCodes(txtPointA.Text);
            string[] pointcs = Airport.ParseAirportCodes(txtPointC.Text);

            while (searching)
            {
                if (!TestDbFace(ref dbface))
                    continue;
                if (pointas.Length < 1)
                {
                    status.Add("ERROR: Please add some point A airports!");
                    return;
                }
                if (pointcs.Length < 1)
                {
                    status.Add("ERROR: Please add some point C airports!");
                    return;
                }

                // set up the specific query parameters
                string pointa = pointas[randgen.Next(pointas.Length)];
                string pointb = Airport.GetSalientAirportCode(dbface);
                string pointc = pointcs[randgen.Next(pointcs.Length)];

                if (pointa == pointb || pointb == pointc)
                    continue;

                status.Add(string.Format("Checking price from {0} to {1}", pointa, pointb));

                TimeSpan range = latest.Value.Subtract(earliest.Value);
                DateTime start = earliest.Value.AddDays(randgen.NextDouble() * range.Days);

                // Try to look up the price
                int priceatob = GetPrice(pointa, pointb, start, null);
                if (priceatob == int.MaxValue)
                {
                    status.Add(string.Format("Failed to get price from {0} to {1}", pointa, pointb));
                    continue;
                }

                int distanceatob = GetDistance(pointa, pointb, dbface);

                status.Add(string.Format("Checking price from {0} to {1}", pointb, pointc));

                int shortdays = GetNum(shortest.Text, false).Value;
                int longdays = GetNum(longest.Text, false).Value;
                DateTime end = start.AddDays(randgen.Next(shortdays, longdays));

                // Try to look up the price
                int pricebtoc = GetPrice(pointb, pointc, end, null);
                if (pricebtoc == int.MaxValue)
                {
                    status.Add(string.Format("Failed to get price from {0} to {1}", pointb, pointc));
                    continue;
                }

                int distancebtoc = GetDistance(pointb, pointc, dbface);

                status.Add(string.Format("Price from {0} to {1} to {2}: ${3}", pointa, pointb, pointc, priceatob + pricebtoc));

                RecordAtoCOption(pointa, pointb, pointc, start, end, priceatob, pricebtoc, distanceatob, distancebtoc, dbface);
            }
        }
Exemplo n.º 13
0
 // a long representation, with all the relevant information
 public string ToLongString(DbFace dbface)
 {
     Airport pointaAirport = Airport.GetAirport(pointa, dbface);
     Airport pointbAirport = Airport.GetAirport(pointb, dbface);
     Airport pointcAirport = Airport.GetAirport(pointc, dbface);
     return string.Format("From {0} to {1} for ${1}, {2} km, on {3}; then to {4} for ${5}, {6} km on {7} ({8:F1} c/mi)", pointaAirport.ToString(), pointbAirport.ToString(), price_atob, km_atob, date_atob.ToString("MM/dd"), pointcAirport.ToString(), price_btoc, km_btoc, date_btoc.ToString("MM/dd"), Score);
 }
Exemplo n.º 14
0
        // Find all flights that fit the search criteria
        // if nextstart = 0, don't try again
        public List<AtoCFlight> FindStoredAtoCFlights(DbFace dbface, string order, int start, int limit, int maxgive, out int nextstart)
        {
            List<AtoCFlight> flights = new List<AtoCFlight>();

            string[] pointas = Airport.ParseAirportCodes(txtPointA.Text);
            string[] pointcs = Airport.ParseAirportCodes(txtPointC.Text);
            List<Dictionary<string, object>> rows = dbface.AssocEnumerate(string.Format("select atob.id as atob_id, atob.origin as atob_origin, atob.destination as atob_destination, atob.date as atob_date, atob.price as atob_price, atob.km as atob_km, atob.date_created as atob_date_created, btoc.id as btoc_id, btoc.origin as btoc_origin, btoc.destination as btoc_destination, btoc.date as btoc_date, btoc.price as btoc_price, btoc.km as btoc_km, btoc.date_created as btoc_date_created from oneways atob left join oneways btoc on atob.destination = btoc.origin where (atob.origin = '{0}') and (btoc.destination = '{1}') and atob.date >= '{2}' and atob.date <= '{3}' and btoc.date >= '{4}' and btoc.date <= '{5}' and datediff(btoc.date, atob.date) >= {6} and datediff(btoc.date, atob.date) <= {7} order by {8} limit {9}, {10}", string.Join("' or atob.origin = '", pointas), string.Join("' or btoc.destination = '", pointcs), MyDate(earliest.Value), MyDate(latest.Value.AddDays(-GetNum(shortest.Text, false).Value)), MyDate(earliest.Value.AddDays(GetNum(shortest.Text, false).Value)), MyDate(latest.Value), GetNum(shortest.Text, false).Value, GetNum(longest.Text, false).Value, order, start, limit));

            nextstart = start;
            foreach (Dictionary<string, object> row in rows)
            {
                nextstart++;

                AtoCFlight flight = new AtoCFlight(row);
                // Is this airport enabled?
                if (Airport.IsAirportEnabled(flight.PointB))
                {
                    flights.Add(flight);
                    if (flights.Count == maxgive)
                        return flights;
                }
            }

            if (rows.Count < limit)
                nextstart = 0;
            return flights;
        }
Exemplo n.º 15
0
 // a long representation, with all the relevant information
 public string ToLongString(DbFace dbface)
 {
     Airport originAirport = Airport.GetAirport(origin, dbface);
     Airport destinationAirport = Airport.GetAirport(destination, dbface);
     return string.Format("From {0} to {1} for ${1}, {2} km, from {3} to {4} ({6:F1} c/mi)", originAirport.ToString(), destinationAirport.ToString(), price, km, date_leave.ToString("MM/dd"), date_return.ToString("MM/dd"), Score);
 }
Exemplo n.º 16
0
        // Check a previously queried flight for the current price
        // if nextstart = 0, don't try any more
        public bool CheckOldFlight(DbFace dbface, int start, out int nextstart)
        {
            List<Flight> flights = FindStoredFlights(dbface, "(km / price) * datediff(now(), created) desc", start, 10, 1, out nextstart);
            if (flights.Count == 0)
            {
                nextstart = 0;
                return false;
            }

            Flight flight = flights[0];

            // Did this happen today?  if so, we're done
            TimeSpan ago = DateTime.Now.Subtract(flight.LastChecked);
            if (ago.TotalDays < 1)
            {
                nextstart = 0;
                return false;
            }

            // Lookup this price
            int price = GetPrice(flight.Origin, flight.Destination, flight.DateLeave, flight.DateReturn);
            if (price == int.MaxValue)
                return false; // failed

            // succeeded!  update the database
            dbface.Execute(string.Format("update flights set price = {0}, created = now(), user = '******' where id = {2}", price, user, flight.Id), false);

            // replace in the results
            results.Remove(flight.Score, flight.ToString());
            flight.Price = price;
            results.Add(flight.Score, flight);

            nextstart--;    // because won't be there!
            status.Add(string.Format("Old result updated: {0} to {1} is ${2}", flight.Origin, flight.Destination, price));
            return true;
        }
Exemplo n.º 17
0
        // Record a new flight option
        public void RecordOption(string origin, string destination, DateTime start, DateTime end, int price, int distance, DbFace dbface)
        {
            lock (dbface)
            {
                dbface.Execute(string.Format("insert into flights (origin, destination, date_leave, date_return, price, km, source, user) values ('{0}', '{1}', '{2}', '{3}', {4}, {5}, '{6}', '{7}') on duplicate key update price = {4}, source = '{6}', user = '******'", origin, destination, MyDate(start), MyDate(end), price, distance, source, user), false);
            }

            lock (results)
            {
                Flight flight = new Flight(origin, destination, Airport.GetAirport(destination, dbface).Country, start, end, price, distance, DateTime.Now);
                results.Add(flight.Score, flight);
            }
        }
Exemplo n.º 18
0
        // Record a new flight option
        public void RecordAtoCOption(string pointa, string pointb, string pointc, DateTime start, DateTime end, int priceatob, int pricebtoc, int distanceatob, int distancebtoc, DbFace dbface)
        {
            lock (dbface)
            {
                dbface.Execute(string.Format("insert into oneways (origin, destination, date, price, km, source, user) values ('{0}', '{1}', '{2}', {3}, {4}, '{5}', '{6}') on duplicate key update price = {3}, source = '{5}', user = '******'", pointa, pointb, MyDate(start), priceatob, distanceatob, source, user), false);
                dbface.Execute(string.Format("insert into oneways (origin, destination, date, price, km, source, user) values ('{0}', '{1}', '{2}', {3}, {4}, '{5}', '{6}') on duplicate key update price = {3}, source = '{5}', user = '******'", pointb, pointc, MyDate(end), pricebtoc, distancebtoc, source, user), false);
            }

            lock (results)
            {
                AtoCFlight flight = new AtoCFlight(pointa, pointb, pointc, start, end, (uint) priceatob, (uint) pricebtoc, (uint) distanceatob, (uint) distancebtoc, DateTime.Now);
                results.Add(flight.Score, flight);
            }
        }
Exemplo n.º 19
0
        // Look up stored results
        public void LookupResults()
        {
            DbFace dbface = new DbFace();
            int start = 0;

            while (results.Count < 600)
            {
                try
                {
                    status.Add("Looking up stored results...");

                    // find anything that fits our criteria
                    int nextstart = 0;

                    if (cmbSearch.SelectedIndex == 0) {
                        List<Flight> flights = FindStoredFlights(dbface, "km / price desc", start, 200, 600 - results.Count, out nextstart);
                        foreach (Flight flight in flights) {
                            lock (results) {
                                results.Add(flight.Score, flight);
                            }
                        }
                    } else if (cmbSearch.SelectedIndex == 1) {
                        List<AtoCFlight> flights = FindStoredAtoCFlights(dbface, "(atob.km + btoc.km) / (atob.price + btoc.price) desc", start, 200, 600 - results.Count, out nextstart);
                        foreach (AtoCFlight flight in flights) {
                            lock (results) {
                                results.Add(flight.Score, flight);
                            }
                        }
                    }

                    if (nextstart == 0)
                        break;
                    start = nextstart;
                }
                catch (Exception ex)
                {
                    // Fail!
                    status.Add("Error: " + ex.Message);
                    return;
                }
            }

            status.Add("Stored results query complete.");

            // Check old flights from now on
            start = 0;
            while (searching)
            {
                int nextstart = 0;
                if (cmbSearch.SelectedIndex == 0)
                    CheckOldFlight(dbface, start, out nextstart);
                else if (cmbSearch.SelectedIndex == 1)
                    CheckOldAtoCFlight(dbface, start, out nextstart);
                if (nextstart == 0)
                    break;  // nothing more to check
                start = nextstart;
            }
        }
Exemplo n.º 20
0
        // Get the distance between two airports
        public int GetDistance(string from, string to, DbFace dbface)
        {
            lock (dbface)
            {
                // Try to get the distance from the database
                int? distance = dbface.GetValue<int>(string.Format("select km from distances where origin = '{0}' and destination = '{1}'", from, to));
                if (distance.HasValue)
                    return distance.Value;

                if (from == "NYC")
                    from = "JFK";
                if (from == "LON")
                    from = "LHR";

                // Otherwise, query www.world-airport.codes.com
                CookieContainer cookies = new CookieContainer();
                string output = WebUtilities.GetPage("http://www.world-airport-codes.com/dist/?a1=" + from + "&a2=" + to, ref cookies);

                int kiloi = output.IndexOf("kilometres");
                if (kiloi < 0)
                    return 0;   // error!

                string kilostr = output.Substring(kiloi - 13, 13);
                int? value = GetNum(kilostr, true);

                if (!value.HasValue)
                {
                    status.Add(string.Format("Could not find distance from {0} to {1}", from, to));
                    return 0;
                }

                dbface.Execute(string.Format("insert into distances (origin, destination, km) values ('{0}', '{1}', {2})", from, to, value.Value), false);
                return value.Value;
            }
        }
Exemplo n.º 21
0
        // Find all flights that fit the search criteria
        // if nextstart = 0, don't try again
        public List<Flight> FindStoredFlights(DbFace dbface, string order, int start, int limit, int maxgive, out int nextstart)
        {
            List<Flight> flights = new List<Flight>();

            string[] origins = Airport.ParseAirportCodes(txtOrigins.Text);
            List<Dictionary<string, object>> rows = dbface.AssocEnumerate(string.Format("select flights.*, airports.country as destcountry from flights left join airports on flights.destination = airports.code where (origin = '{0}') and date_leave >= '{1}' and date_leave <= '{2}' and datediff(date_return, date_leave) >= {3} and datediff(date_return, date_leave) <= {4} order by {5} limit {6}, {7}", string.Join("' or origin = '", origins), MyDate(earliest.Value), MyDate(latest.Value), GetNum(shortest.Text, false).Value, GetNum(longest.Text, false).Value, order, start, limit));

            nextstart = start;
            foreach (Dictionary<string, object> row in rows)
            {
                nextstart++;

                Flight flight = new Flight(row);
                // Is this airport enabled?
                if (Airport.IsAirportEnabled(flight.Destination))
                {
                    flights.Add(flight);
                    if (flights.Count == maxgive)
                        return flights;
                }
            }

            if (rows.Count < limit)
                nextstart = 0;
            return flights;
        }
Exemplo n.º 22
0
        // Check or refresh dbface
        public bool TestDbFace(ref DbFace dbface)
        {
            if (!string.IsNullOrEmpty(dbface.LastError))
            {
                dbface.Dispose();
                dbface = new DbFace();
                // try it out now-- might fail!
                dbface.GetConnection();
                if (!string.IsNullOrEmpty(dbface.LastError))
                {
                    status.Add("ERROR: Count not connect to the database.");
                    Thread.Sleep(1000);
                    return false;
                }
            }

            return true;
        }
Exemplo n.º 23
0
        // Check a previously queried a-to-c flight for the current price
        // if nextstart = 0, don't try any more
        public bool CheckOldAtoCFlight(DbFace dbface, int start, out int nextstart)
        {
            List<AtoCFlight> flights = FindStoredAtoCFlights(dbface, "((atob.km + btoc.km) / (atob.price + btoc.price)) * (datediff(now(), atob.date_created) * datediff(now(), btoc.date_created)) desc", start, 10, 1, out nextstart);
            if (flights.Count == 0)
            {
                nextstart = 0;
                return false;
            }

            AtoCFlight flight = flights[0];

            // Did this happen today?  if so, we're done
            TimeSpan ago = DateTime.Now.Subtract(flight.LastChecked);
            if (ago.TotalDays < 1)
            {
                nextstart = 0;
                return false;
            }

            // Lookup this prices
            int price_atob = GetPrice(flight.PointA, flight.PointB, flight.Date_AtoB, null);
            if (price_atob == int.MaxValue)
                return false; // failed
            int price_btoc = GetPrice(flight.PointB, flight.PointC, flight.Date_BtoC, null);
            if (price_btoc == int.MaxValue)
                return false; // failed

            // succeeded!  update the database
            dbface.Execute(string.Format("update flights set price = {0}, created = now(), user = '******' where id = {2}", price_atob, user, flight.Id_AtoB), false);
            dbface.Execute(string.Format("update flights set price = {0}, created = now(), user = '******' where id = {2}", price_btoc, user, flight.Id_BtoC), false);

            // replace in the results
            results.Remove(flight.Score, flight.ToString());
            flight.Price_AtoB = (uint) price_atob;
            flight.Price_BtoC = (uint) price_btoc;
            results.Add(flight.Score, flight);

            nextstart--;    // because won't be there!
            status.Add(string.Format("Old result updated: {0} to {1} to {2} is ${3}", flight.PointA, flight.PointB, flight.PointC, price_atob + price_btoc));
            return true;
        }