-
Notifications
You must be signed in to change notification settings - Fork 1
/
Form1.cs
2439 lines (2066 loc) · 96.9 KB
/
Form1.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.Net;
using System.IO;
using System.Data.OleDb;
using System.Text.RegularExpressions;
using Microsoft.CSharp.RuntimeBinder;
using System.Configuration;
using System.Reflection;
using System.Web.Script.Serialization;
using System.Globalization;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
//List<Missionary> missionaries = new List<Missionary>();
MissionaryManager missionaryManagerChristensen; // I, Anz. Christensen, am organizing all the missionaries.
TrainManager conductorChristensen; // As well as the trains. Thus, they are named after myself. :)
ExcelManager excelManagerChristensen; // And so we may as well continue the trend...
int nextMissionaryID = 0;
public Form1()
{
InitializeComponent();
//listBox1.Items = new String[] { "Kenneth", "Christensen" };
}
// Will take the Missionaries from MissioanryManager and work with the TrainManager to schedule things.
public void Schedule_Trips()
{
missionaryManagerChristensen.calculateTrips();
//for (int i = 0; i < nextMissionaryID - 1; i++) // Cycle through missionarys in the Manager by ID.
//{
// managerChristensen.calculateTrip(
//}
}
// Will build the MissionaryManager from the Excel File
public void Analyze_File(String fileURI, String sheetName, String outputFileName)
{
DateTime selectedDate = monthCalendar1.TodayDate;
String selectedDateString = FUNCS.twoDigitHour(selectedDate.Day) + "-" + FUNCS.twoDigitHour(selectedDate.Month) + "-" + selectedDate.Year;
selectedDateString = "26-08-2015";
//conductorChristensen = new TrainManager(selectedDateString);
//missionaryManagerChristensen = new MissionaryManager(conductorChristensen);
excelManagerChristensen = new ExcelManager(selectedDateString);
//var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory());
excelManagerChristensen.Import_Travel_File(fileURI, sheetName);
conductorChristensen = excelManagerChristensen.getConductor();
missionaryManagerChristensen = excelManagerChristensen.getMissionaryManager();
//int x = conductorChristensen.getTrainTimes("Milano Centrale", "Torino Porta Susa", "09-06-2015", "06");
missionaryManagerChristensen.printAllMissionaries();
Console.WriteLine("About to calculate!");
missionaryManagerChristensen.calculateTrips();
Console.WriteLine("calculating");
missionaryManagerChristensen.printAllMissionaries();
missionaryManagerChristensen.printAllMissionarySchedules();
excelManagerChristensen.write_to_text_file("C:\\Users\\SEC2016583\\Desktop",outputFileName,missionaryManagerChristensen.getAllMissionarySchedules());
Console.Beep();
FUNCS.ShowPromptBox("Finished running", "You should look on the desktop for your file.", "I mean nothing right now.");
//Console.WriteLine(data.Columns);
}
// Runs when you click submit file.
private void submitFile(object sender, EventArgs e)
{
string f = textBox1.Text;
string s = textBox2.Text;
string o = textBox3.Text;
Properties.Settings.Default.inputFile = f;
Properties.Settings.Default.sheetName = s;
Properties.Settings.Default.outputFile = o;
Properties.Settings.Default.Save();
Console.WriteLine("getting info in excel file at " + f+", in sheet "+s);
Analyze_File(f,s,o);
}
// Runs when you click browse.
private void showFileBrowser(object sender, EventArgs e)
{
//int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
textBox1.Text = file;
/*try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
* */
}
}
private void Analyze_File2(object sender, EventArgs e)
{
//Analyze_File("nothing");
}
}
public class Train
{
public String depart { get; set; } // Departure City
public String arrive { get; set; } // Arrival City
public int trainNumber { get; set; } // Train number
public String date { get; set; } // Date of train.
public int timeMinutes { get; set; } // Departure time in minutes since 00:00.
public int arrivalTimeMinutes { get; set; } // ARrival time in minutes since 00:00.
public int durationMinutes { get; set; } // Train ride duration in minutes
public int costEuro { get; set; } // Cost of ticket in Euro
public int type { get; set; } // Type of train
public Train(String d, String a, String dt, int tN, int tM, int aTM, int dM, int cE, int t){
depart = d;
arrive = a;
date = dt;
trainNumber = tN;
timeMinutes = tM;
arrivalTimeMinutes = aTM;
durationMinutes = dM;
costEuro = cE;
type = t;
}
}
public class TrainManager
{
public Dictionary<String, String> stationsSettings;
public List<String> stations;
public String[] hubs;
List<Train> trains;
DataSet trainDB;
DataTable orariTable;
DataColumn trainID;
String day;
String transferDay;
String previousDay;
private const String noDayParameter = "none";
private String checkDayParameter(String s)
{
if (s.Equals(noDayParameter)){
return day;
} else {
return s;
}
}
public String[] getHubs()
{
return hubs.ToArray();
}
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()));
}
public Train getNextTrain(Train t)
{
String depart = t.depart;
String arrive = t.arrive;
int timeMinutes = t.timeMinutes;
DataRow[] options = orariTable.Select("depart = '" + depart + "' AND arrive = '" + arrive + "' AND timeMinutes > " + timeMinutes.ToString());
int eBrake = 0;
int nextTime = timeMinutes;
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 timeMinutes < " + timeMinutes.ToString());
if (eBrake > 6)
{
//getTrainTimes(depart, arrive, day, FUNCS.minutesToTimeString(nextTime));
return null;
}
}
// Return first train.
DataRow choice = options[0];
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()));
}
#region unusedMethods
public Train getTrain(String origin, String destination, int time, String usedDay = "none")
{
// TODO: Get a train by looking through our DB, adding to it if necessary, calling getSchedule
return null;
}
public Train getSchedule(String origin, String destination, int time, String usedDay = "none")
{
// TODO: Download more schedule with the given info.
return null;
}
#endregion unusedMethods
public void saveSettings()
{
JavaScriptSerializer jsoner = new JavaScriptSerializer();
Properties.Settings.Default.Cities = jsoner.Serialize(stationsSettings);
Properties.Settings.Default.Save();
}
public TrainManager(String d)
{
day = d;
trains = new List<Train>();
String fromResources = WindowsFormsApplication1.Properties.Resources.Stations;
Regex getStations = new Regex(@"""([^""]|\\"")*"""); // Will grab every step
String[] stationsArray = getStations.Matches(fromResources).Cast<Match>().Select(m => m.Value).ToArray();
JavaScriptSerializer jsoner = new JavaScriptSerializer();
String JSONdict = Properties.Settings.Default.Cities;
stationsSettings = jsoner.Deserialize<Dictionary<String, String>>(JSONdict);
if (stationsSettings == null)
{
stationsSettings = new Dictionary<string, string>();
}
for (int z = 0; z < stationsArray.Length; z++ )
{
stationsArray[z] = stationsArray[z].Replace("\"", "");
}
stations = stationsArray.ToList<String>();
hubs = new String[WindowsFormsApplication1.Properties.Settings.Default.hubs.Count];
WindowsFormsApplication1.Properties.Settings.Default.hubs.CopyTo(hubs,0);
foreach (string h in hubs)
{
Console.WriteLine(validateStation(h));
}
trainDB = new DataSet("trains");
orariTable = trainDB.Tables.Add("orari");
Type x = typeof(Int32);
trainID = orariTable.Columns.Add("trainNumber", x);
orariTable.Columns.Add("depart", typeof(String));
orariTable.Columns.Add("arrive", typeof(String));
orariTable.Columns.Add("date", typeof(String));
orariTable.Columns.Add("timeMinutes", x);
orariTable.Columns.Add("arrivalTimeMinutes", x);
orariTable.Columns.Add("durationMinutes", x);
orariTable.Columns.Add("costEuro", x);
orariTable.Columns.Add("type", x);
//orariTable.PrimaryKey = new DataColumn[] { trainID };
UniqueConstraint distinctIDArriveDepart = new UniqueConstraint(new DataColumn[] { orariTable.Columns["trainNumber"], orariTable.Columns["arrive"], orariTable.Columns["depart"], orariTable.Columns["date"] });
orariTable.Constraints.Add(distinctIDArriveDepart);
}
public Train getTrainToArriveAt(String depart, String arrive, int arrivalTimeMinutes, String usedDay = noDayParameter, bool sleepover = false)
{
// Check if the default parameter is left this.noDayParameter, if so, make it = this.day.
usedDay = checkDayParameter(usedDay);
depart = validateStation(depart);
arrive = validateStation(arrive);
String queryString = String.Format("depart ='{0}' AND arrive = '{1}' AND arrivalTimeMinutes < {2} AND date = '{3}'",depart, arrive, arrivalTimeMinutes, usedDay);
DataRow[] options = orariTable.Select(queryString, "arrivalTimeMinutes DESC");
//DataRow[] options = orariTable.Select("depart = '" + depart + "' AND arrive = '" + arrive + "' AND arrivalTimeMinutes < " + arrivalTimeMinutes.ToString());
int eBrake = 0;
int nextTime = arrivalTimeMinutes;
bool firstTime = true;
while (options.Length == 0 || (firstTime && options.Length > 0 && ((20*60+30) - Int32.Parse(options[0]["arrivalTimeMinutes"].ToString())) > (60 * 1))) // 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);
if (options.Length > 0 && firstTime)
{
nextTime = nextTime - 90; // If we're not leaving LATE enough, because of a sleepover, we need to give ourselves plenty of time.
}
if (options.Length > 0)
{
firstTime = false;
}
getTrainTimes(depart, arrive, usedDay, FUNCS.minutesToTimeString(nextTime));
Console.WriteLine("next time is: " + nextTime.ToString());
String queryString2 = String.Format("depart ='{0}' AND arrive = '{1}' AND arrivalTimeMinutes < {2} AND date = '{3}'", depart, arrive, arrivalTimeMinutes, usedDay);
options = orariTable.Select(queryString2, "arrivalTimeMinutes DESC");
//options = orariTable.Select("depart = '" + depart + "' AND arrive = '" + arrive + "' AND arrivalTimeMinutes < " + arrivalTimeMinutes.ToString());
if (eBrake > 6)
{
//getTrainTimes(depart, arrive, day, FUNCS.minutesToTimeString(nextTime));
return null;
}
}
// Naive... return the last one, we'll optimize later.
DataRow choice = options[0];
if (sleepover) // if we're sleeping over, return the last possible solution.
{
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()));
}
public Train getTrainToLeaveAt(String depart, String arrive, int timeMinutes, String usedDay = noDayParameter)
{
if (depart.Equals(arrive))
{
Console.WriteLine("This coppia doesn't need travel: " + depart);
return null;
}
// Check if the default parameter is left this.noDayParameter, if so, make it = this.day.
usedDay = checkDayParameter(usedDay);
String queryString = String.Format("depart ='{0}' AND arrive = '{1}' AND timeMinutes < {2} AND date = '{3}'", depart, arrive, timeMinutes, usedDay);
DataRow[] options = orariTable.Select(queryString);
//DataRow[] options = orariTable.Select("depart = '" + depart + "' AND arrive = '" + arrive + "' AND timeMinutes < " + timeMinutes.ToString());
int eBrake = 0;
int nextTime = timeMinutes;
while (options == null || options.Length == 0) // Spero che quando non ci sono treni adeguati che ritorna null, invece di un array vuoto....
{
if (depart == "Firenze S. M. Novella" && arrive == "Milano Centrale")
{
int x = 42; // gimmi a break point...
}
getTrainTimes(depart, arrive, usedDay, FUNCS.minutesToTimeString(nextTime -= (10 * eBrake)));
String queryString2 = String.Format("depart ='{0}' AND arrive = '{1}' AND timeMinutes < {2} AND date = '{3}'", depart, arrive, timeMinutes, usedDay);
//String query = "depart = '" + depart + "' AND arrive = '" + arrive + "' AND timeMinutes < " + timeMinutes.ToString();
Console.WriteLine(queryString2);
options = orariTable.Select(queryString2);
if (eBrake++ > 6)
{
return null;
}
}
// Naive... return the first one, we'll optimize later.
DataRow choice = options[0];
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&lang=it"},
{"url_mobile", "https://www.lefrecce.it/B2CWeb/searchExternal.do?parameter=initBaseSearch&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&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;
}
public String validateStation (String station){
String s = station.Trim();
//try
//{
// s = Properties.Settings.Default[station].ToString();
//}
//catch (SettingsPropertyNotFoundException)
//{
// s = "error";
//}
if (stationsSettings.ContainsKey(station))
{
s = stationsSettings[station];
}
if (stations.Contains(s))
{
return s;
}
else
{
String newStationSetting = FUNCS.ShowPromptBox("Invalid train station", "What station does '" + station + "' actually mean (Look up on trenitalia.com if you don't know)?", station);
stationsSettings[station] = newStationSetting;
saveSettings();
return validateStation(newStationSetting);
}
//if (s.Equals("error")){
// //String withQuotes = "\"" + station + "\"";
// //withQuotes = "\"AACHEN HBF\"";
// if (stations.Contains(station)){
// return station; // theh passed name is a legitimate option. Give it back.
// } else {
// //return "error"; // the passed name is not a legitmate option, and they haven't told us what it should be. Maybe we could ask for it? Later.
// String newStationSetting = FUNCS.ShowPromptBox("What station does '"+station+"' actually mean (Look up on trenitalia.com if you don't know)?", "Invalid train station", station);
// var property = new SettingsProperty(Properties.Settings.Default.Properties["Milano"]);
// property.Name = station;
// Properties.Settings.Default.Properties.Add(property);
// Properties.Settings.Default[station] = newStationSetting;
// Properties.Settings.Default.Save();
// return newStationSetting;
// }
//}
return s; // return the station which corresponds to the one passed.
}
public String createPostDataString(Dictionary<String, String> args)
{
String returnValue = "";
String[] keys = args.Keys.ToArray();
String[] values = args.Values.ToArray();
int j = args.Keys.ToArray().Length;
for (int i = 0; i < j; i++)
{
returnValue = returnValue + Uri.EscapeUriString(keys[i]) + "=" + Uri.EscapeUriString(values[i]);
if (i != j){
returnValue = returnValue + "&";
}
}
return returnValue;
}
}
public class Missionary
{
public String fullName { get; set; }
public String name {get; set;}
public int id { get; set; }
//public String[] legs { get; set; }
public String[][] comps { get; set; }
public Leg[] legs { get; set; }
public int[] legIndexs { get; set; }
public MissionaryManager manager { get; set; }
public String home { get; set; }
public String zone { get; set; }
public String ToString()
{
String sB = "";
foreach (Leg cl in legs){
string s = "";
if (cl.train != null)
{
s = cl.train.depart;
}
sB = sB+" "+s;
}
String cB = "";
foreach (String[] a in comps)
{
cB = cB + " (";
foreach (String b in a)
{
cB = cB + ", " + b;
}
cB = cB + ")";
}
return fullName + "; " + name + "; " + zone + "; " + id.ToString() + ", " + sB+"; "+cB;
}
public int getTravelTime()
{
return legs[legs.Length - 1].time_end - legs[0].time_start;
}
public string getSchedule()
{
string scheduleResponse = "";
foreach (Leg l in legs)
{
if (l.train != null)
{
scheduleResponse = scheduleResponse + l.train.date + ": " + FUNCS.minutesToTimeString(l.train.timeMinutes) + "-" + FUNCS.minutesToTimeString(l.train.arrivalTimeMinutes) + " " + l.train.depart + " -> " + l.train.arrive + "(" + TRAIN_TYPES.getTypeFromNumber(l.train.type)+": "+ l.train.trainNumber+")"+"\r\n";
}
else
{
scheduleResponse = scheduleResponse + "No train found for trip from " + l.depart + " to " + l.arrive + ".\r\n";
}
}
return scheduleResponse;
}
// Checks through the legs, and returns the time that we will be leaving from String d.
public int getTimeToEndLeg(String d)
{
for (int i = 0; i < legs.Length; i++)
{
Leg l = legs[i];
Train t = l.train;
// We've found the train we're leaving on....
if (t != null && t.depart.Equals(d))
{
if (l.skip == true)
{
if (i > 0 && legs[i - 1].train != null)
{
return legs[i - 1].train.arrivalTimeMinutes;
}
else
{
return manager.preferredFinish;
}
}
// But if we're sleeping at our destination, we actually need to get to bed on time...
if (i > 0 && legs[i - 1].going_to_sleepover)
{
Console.WriteLine(String.Format("Returning the preferred finish time ({0}) while going to {1}.", manager.preferredFinish, d));
return manager.preferredFinish;
}
return t.timeMinutes;
}
else
{
return manager.preferredFinish;
}
}
return -1;
}
// Checks through the legs, and returns the time that we will be arriving at station String d
public int getReadyTimeAt(String d)
{
for (int i = 0; i < legs.Length-1; i++)
{
if (legs[i].train != null && legs[i].train.arrive.Equals(d))
//if (legs[i+1].train != null && legs[i + 1].train.depart.Equals(d))
{ // Then legs[i] is the leg we're looking for, because it arrives at said station.
if (legs[i].skip == true)
{
if (i > 0 && legs[i - 1].train != null && legs[i - 1].train.arrivalTimeMinutes != null)
{
return legs[i - 1].train.arrivalTimeMinutes+60;
}
else
{
return manager.preferredStart+60;
}
}
// If we just got done with a sleepover, we need to get going in the morning though.
if (legs[i].going_to_sleepover)
{
Console.WriteLine(String.Format("Returning the preferred finish time ({0}) while going to {1}.", manager.preferredFinish, d));
return manager.preferredStart;
}
return legs[i].train.arrivalTimeMinutes;
}
}
return 11*60; // Say eleven oclock for now. TODO
}
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;
}
// 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;