public Train getPreviousTrain(Train t)
 {
     String depart = t.depart;
     String arrive = t.arrive;
     int arrivalTimeMinutes = t.arrivalTimeMinutes;
     DataRow[] options = orariTable.Select("depart = '" + depart + "' AND arrive = '" + arrive + "' AND arrivalTimeMinutes < " + arrivalTimeMinutes.ToString());
     int eBrake = 0;
     int nextTime = arrivalTimeMinutes;
     while (options.Length == 0) // Spero che quando non ci sono treni adeguati che ritorna null, invece di un array vuoto....
     {
         eBrake = eBrake + 1;
         Console.WriteLine("next time was: " + nextTime.ToString());
         nextTime = nextTime - (10 * eBrake);
         getTrainTimes(depart, arrive, day, FUNCS.minutesToTimeString(nextTime));
         Console.WriteLine("next time is: " + nextTime.ToString());
         options = orariTable.Select("depart = '" + depart + "' AND arrive = '" + arrive + "' AND arrivalTimeMinutes < " + arrivalTimeMinutes.ToString());
         if (eBrake > 6 || nextTime < 1)
         {
             //getTrainTimes(depart, arrive, day, FUNCS.minutesToTimeString(nextTime));
             return null;
         }
     }
     // Return last train.
     DataRow choice = options[options.Length-1];
     return new Train(choice["depart"].ToString(), choice["arrive"].ToString(), choice["date"].ToString(), Int32.Parse(choice["trainNumber"].ToString()), Int32.Parse(choice["timeMinutes"].ToString()), Int32.Parse(choice["arrivalTimeMinutes"].ToString()), Int32.Parse(choice["durationMinutes"].ToString()), Int32.Parse(choice["costEuro"].ToString()), Int32.Parse(choice["type"].ToString()));
 }
        // Will add to the DB, returning an int 0 based on success, an error code otherwise.
        public int getTrainTimes(String departure, String arrival, String date, String time)
        {
            if (departure.Equals(arrival))
            {
                return -1;
            }

            Console.WriteLine(departure + ", " + arrival + ", " + date + ", " + time);
            // Return object:
            //String[][] times = new string[10][]; // Makes space for 10 solutions of 2 times each.

            /***
             * Info we want to add to DB
             *
             * 1) Station of Departure
             * 2) Station of Arrival
             * 3) Time of Departure
             * 4) Time of Arrival
             * 5) Date of trip
             * 6) Trip duration (why not)
             * 7) Train number
             * 8) Train type
             * 9) Ticket Cost
             *
             **/
            String stationD = validateStation(departure);
            String stationA = validateStation(arrival);
            // Stations were wrong. Return an error code.
            if ((stationD.Equals("error") || stationA.Equals("error")) == true)
            {
                return ERROR.INVALID_STATION;
            }

            int timeD = 0; // minutes from midnight
            int timeA = 0; // minutes from midnight
            String dateT; // mm-dd-yyyy format string
            int duration; // minutes
            int trainNum;
            int trainType; // Comes from TRAIN_TYPES class constant. See below.
            int trainCost;

            Dictionary<String, String> postArgs = new Dictionary<string, string>(){
                {"url_desktop", "https://www.lefrecce.it/B2CWeb/searchExternal.do?parameter=initBaseSearch&amp;lang=it"},
                {"url_mobile", "https://www.lefrecce.it/B2CWeb/searchExternal.do?parameter=initBaseSearch&amp;lang=it"},
                {"tripType", "on"},
                {"isRoundTrip", "false"},
                {"departureStation", "Milano Centrale"},
                {"arrivalStation", "Torino Porta Susa"},
                {"departureDate", "06-06-2015"},
                {"returnDate", "06-06-2015"},
                {"ynFlexibleDates", "off"},
                {"selectedTrainType", "tutti"},
                {"selectedTrainClassifications", ""}
            };

            postArgs["departureStation"] = departure;
            postArgs["arrivalStation"] = arrival;
            postArgs["departureDate"] = date;
            postArgs["departureTime"] = FUNCS.twoDigitHour(time).Split(new char[]{':'})[0];

            string post_data = createPostDataString(postArgs);
            //Console.WriteLine(post_data);
            string uri = "https://www.lefrecce.it/B2CWeb/searchExternal.do?parameter=initBaseSearch&amp;lang=it";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";
            //request.AllowAutoRedirect = false;
            request.CookieContainer = new CookieContainer(); // Handles the redirects, etc.

            byte[] postBytes = Encoding.ASCII.GetBytes(post_data);

            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postBytes.Length;
            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            String html = new StreamReader(response.GetResponseStream()).ReadToEnd();
            //Console.WriteLine(html);

            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(html);

            var root = htmlDoc.DocumentNode;
            int counterSR = 0;
            int counterT = 0;

            #region parseResponse

            #region checkForDateChange

            List<String> train_dates = new List<String>();
            String currentDay = date;
            Regex dateRegex = new Regex(@"\d\d\-\d\d-\d\d\d\d");

            foreach (HtmlNode n in root.SelectNodes("//*[contains(@class, 'panel')]/div"))
            {
                String id = n.GetAttributeValue("id","false");
                if (id.Substring(0, id.Length - 1).Equals("travelSolution"))
                {
                    // it's a solutionRow, we need to add its date to the train_dates.
                    train_dates.Add(currentDay.ToString());

                }
                else if (id.Equals("separator"))
                {
                    // it's a new date. use the one listed.
                    currentDay = n.SelectSingleNode(".//table/thead/tr/th").InnerText.Trim();
                    Console.WriteLine("changed current date to....");
                }

            }

            // At this point, train_dates should be a list of dates corresponding to each solution row, so we can add each solutions date to the db.
            #endregion

            int solutionNumber = 0;

            foreach (HtmlNode node in root.SelectNodes("//*[contains(@class,'solutionRow')]"))
            {

                String[] currentTime = new string[2];

                //Console.WriteLine("Solution " + counterSR.ToString());
                // Get the times:
                foreach (HtmlNode node2 in node.SelectNodes(".//td/div/span[contains(@class, 'time')]"))
                {
                    string thisTime = node2.InnerHtml.Trim();
                    if (counterT % 2 == 0)
                    {
                        //Console.WriteLine("Depart: " + thisTime);
                        //currentTime[0] = thisTime;
                        timeD = FUNCS.timeStringToMinutes(thisTime);
                    }
                    else
                    {
                        //Console.WriteLine("Arrive: " + thisTime);
                        //currentTime[1] = thisTime;
                        timeA = FUNCS.timeStringToMinutes(thisTime);
                    }
                    counterT++;

                }

                duration = timeA - timeD;
                // Wait, I don't need this... I just calculate it from my own times. Done above.
                /*
                // Get the duration:
                counterT = 0;
                foreach (HtmlNode node2 in node.SelectNodes(".//td/div/span[contains(@class, 'bottom')]"))
                {
                    string thisStation = node2.InnerHtml.Trim();
                    if (counterT % 2 == 0)
                    {
                        Console.WriteLine("Depart: " + thisStation);
                        //currentTime[0] = thisTime;
                        timeD = FUNCS.timeStringToMinutes(thisStation);
                    }
                    else
                    {
                        Console.WriteLine("Arrive: " + thisStation);
                        //currentTime[1] = thisTime;
                        timeA = FUNCS.timeStringToMinutes(thisStation);
                    }
                    counterT++;

                }*/

                // Get the Type/Number:

                String descT = node.SelectNodes(".//td/div/div/div[contains(@class, 'descr')]")[0].InnerText;//.Split(new char[] { ' ' });
                //String trainTypeName = desc[0];

                Regex descRX = new Regex(@"[^\t\r\n\v\f]+"); // Will grab everything that's not whitespace...
                String[] desc = descRX.Matches(descT).Cast<Match>().Select(m => m.Value).ToArray();

                String trainTypeName = desc[0];
                trainType = FUNCS.getTrainTypeCode(trainTypeName);
                if (trainTypeName == "Autobus")
                {
                    trainNum = -11;
                }
                else
                {
                    if (desc[1].Equals("Urb"))
                    {
                        desc[1] = "0";
                    }
                        trainNum = Int32.Parse(desc[1]);

                }

                // Get the Cost:

                try
                {
                    String costString = node.SelectNodes(".//td/span/div/span[contains(@class, 'price')]")[0].InnerText;
                    Regex costRX = new Regex(@"[0-9]+");
                    String cx = costRX.Matches(costString).Cast<Match>().Select(m => m.Value).ToArray()[0];
                    String cy = cx.Replace(",", ".");
                    trainCost = Int32.Parse(cy);

                }
                catch (Exception)
                {
                    trainCost = -1;
                }

            #endregion parseResponse

                //times[counterSR] = (String[])currentTime.Clone();
                // Here we add what we've gotten from the node to the DB, if valid.

                DataRow currentSolution = orariTable.NewRow();

                currentSolution["depart"] = stationD;
                currentSolution["arrive"] = stationA;
                currentSolution["trainNumber"] = trainNum;
                currentSolution["date"] = train_dates[solutionNumber++];
                currentSolution["timeMinutes"] = timeD;
                currentSolution["durationMinutes"] = duration;
                currentSolution["arrivalTimeMinutes"] = timeA;
                currentSolution["costEuro"] = trainCost;
                currentSolution["type"] = trainType;

                try
                {
                    if (trainNum != -11) // if it's not a bus.
                    {
                        orariTable.Rows.Add(currentSolution);
                    }
                }
                catch (ConstraintException e)
                {
                    Console.WriteLine(currentSolution["trainNumber"]);
                    DataRow choice = orariTable.Select("trainNumber = " + currentSolution["trainNumber"].ToString())[0];
                    Train error = new Train(choice["depart"].ToString(), choice["arrive"].ToString(), choice["date"].ToString(), Int32.Parse(choice["trainNumber"].ToString()), Int32.Parse(choice["timeMinutes"].ToString()), Int32.Parse(choice["arrivalTimeMinutes"].ToString()), Int32.Parse(choice["durationMinutes"].ToString()), Int32.Parse(choice["costEuro"].ToString()), Int32.Parse(choice["type"].ToString()));
                    if (error.depart.Equals("Firenze S. M. Novella") && error.arrive.Equals("Milano Centrale"))
                    {
                        bool breaker = true;
                    }
                }
                counterSR++;

            }

            Console.WriteLine("We got " + counterT.ToString() + " times in " + counterSR.ToString() + " solutions.");
            return 0;
        }
        // Does the exact same thing as fillLeg, but not for every companion. Called by fillLeg.
        public int setLeg(Train t)
        {
            bool skippy = false;
            if (t == null)
            {
                skippy = true;
                t = new Train("nowhere", "here", "mai", -1, -1, -1, -1, -1, -1); // We've got to do something... I suppose there are better ways to do this, but...
            }
            String d = t.depart;
            String a = t.arrive;
            for (int i = 0; i < legs.Length; i++)
            {
                if (legs[i].depart.Equals(d) && legs[i].arrive.Equals(a))
                {
                    legs[i].train = t;
                    legs[i].time_start = t.timeMinutes;
                    legs[i].time_end = t.arrivalTimeMinutes;
                    if (i > 0 && ((legs[i].time_start < legs[i - 1].time_end + manager.minLayover) && legs[i].date.Equals(legs[i-1].date)) && !skippy)
                    {
                        legs[i].conflict_before = true;
                        legs[i - 1].conflict_after = true;
                    }
                    else
                    {
                        if (i > 0)
                        {
                            legs[i].conflict_before = false;
                            legs[i - 1].conflict_after = false;
                        }
                    }
                    if (i < legs.Length - 1 && ((legs[i].time_end > legs[i + 1].time_start - manager.minLayover) && legs[i].date.Equals(legs[i+1].date)))
                    {
                        legs[i].conflict_after = true;
                        legs[i + 1].conflict_before = true;
                    }
                    else
                    {
                        if (i < legs.Length - 1)
                        {
                            legs[i].conflict_after = false;
                            legs[i + 1].conflict_before = false;
                        }
                    }
                    return i;

                }
                else if (legs[i].depart.Equals(d) && legs[i].arrive.Equals(a) && skippy)
                {
                    legs[i].skip = skippy; // We don't know how to get answer for this train, skip it.
                    legs[i].train = null;
                }
                else
                {
                    //Console.WriteLine("this comp has no such train!!");
                }
            }
            return -1;
        }
        public int fillLeg(Train t)
        {
            bool skippy = false;
            if (t == null)
            {
                skippy = true;
                t = new Train("nowhere", "here", "mai", -1, -1, -1, -1, -1, -1); // We've got to do something... I suppose there are better ways to do this, but...
            }

            String d = t.depart;
            String a = t.arrive;
            int index = new int();
            for (int i = 0; i < legs.Length; i++)
            {
                if (legs[i].depart.Equals(d) && legs[i].arrive.Equals(a) && !skippy)
                {
                    legs[i].train = t;
                    legs[i].time_start = t.timeMinutes;
                    legs[i].time_end = t.arrivalTimeMinutes;
                    if (i > 0 && ((legs[i].time_start < legs[i - 1].time_end + manager.minLayover)&&(legs[i].date.Equals(legs[i-1].date))))
                    {
                        legs[i].conflict_before = true;
                        legs[i - 1].conflict_after = true;
                    }
                    else
                    {
                        if (i > 0)
                        {
                            legs[i].conflict_before = false;
                            legs[i - 1].conflict_after = false;
                        }
                    }
                    if (i < legs.Length - 1 && ((legs[i].time_end > legs[i + 1].time_start - manager.minLayover)&&(legs[i].date.Equals(legs[i+1].date))))
                    {
                        legs[i].conflict_after = true;
                        legs[i + 1].conflict_before = true;
                    }
                    else
                    {
                        if (i < legs.Length - 1)
                        {
                            legs[i].conflict_after = false;
                            legs[i + 1].conflict_before = false;
                        }
                    }
                    index = i;
                    break;

                }
                else if (legs[i].depart.Equals(d) && legs[i].arrive.Equals(a) && skippy)
                {
                    legs[i].skip = skippy; // We don't know how to get answer for this train, skip it.
                    legs[i].train = null;
                }
                else
                {
                    //Console.WriteLine("This comp has no such train!");
                }
            }

            // Different from setLeg
            String[] cs = legs[index].comps;
            foreach (string c in cs){
                Missionary thisComp = manager.getMissionaryByName(c);
                if (thisComp != null)
                {
                    thisComp.setLeg(t);
                }
            }

            return -1;
        }
示例#5
0
 public void setTrain(Train train)
 {
     this.train = train;
 }
示例#6
0
 public Schedule(Train train, int id, Route route)
 {
     this.route = route;
     this.id    = id;
     this.train = train;
 }
示例#7
0
 public Schedule()
 {
     route = new Route();
     train = new Train();
     id    = 0;
 }