-
Notifications
You must be signed in to change notification settings - Fork 2
/
NewCard.cs.bak
760 lines (654 loc) · 28.8 KB
/
NewCard.cs.bak
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
using SPORTident;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Net.Http.Headers;
using System.Xml.Linq;
namespace h24
{
public class NewCard
{
//klc01 db;
public int HandleNewCard(int readout_id)
{
var db = new klc01();
string chip_id_s = db.si_readout.First(a => a.readout_id == readout_id).chip_id;
int competitor_id = this.GetRunnerByCardId(chip_id_s);
while (competitor_id == 0)
{
//chip not found
frmChipNotFound f2 = new frmChipNotFound(chip_id_s);
f2.ShowDialog();
competitor_id = this.GetRunnerByCardId(chip_id_s);
}
//insert leg
int leg_id = this.InsertLeg(readout_id, competitor_id, out int guessed_course);
int slip_id = this.InsertSlip(leg_id);
return slip_id; //processedResult;
}
public long UpdateLeg(int readout_id)
{
int leg_id;
using (var db = new klc01())
{
//string chip_id_s = db.legs.First(a => a.leg_id == leg_id).chip_id;
string action = "U";
int competitor_id;
int course_id;
int guessed_course;
var query = (from r in db.si_readout
join l in db.legs on r.readout_id equals l.readout_id into gl
from x in gl.DefaultIfEmpty()
where r.readout_id == readout_id
select new
{
chip_id = r.chip_id,
leg_id = x != null ? x.leg_id : 0,
comp_id = x != null ? x.comp_id : 0,
course_id = x != null ? x.course_id : 0
}).FirstOrDefault();
int chip_id = int.Parse(query.chip_id);
leg_id = query.leg_id;
if (leg_id == 0)
action = "I";
if (query.comp_id == 0)
competitor_id = db.competitors.First(a => a.comp_chip_id == chip_id).comp_id;
else
competitor_id = query.comp_id;
//if ((int)query.course_id == 0)
course_id = GetCourseAndGuessed(competitor_id, readout_id, out guessed_course);
//else
//course_id = (int)query.course_id;
//update or insert to legs
//TODO - tohle nejak nefunguje
//var aaa = db.sp_upsert_legs(readout_id, competitor_id, course_id, guessed_course, action);
leg_id = int.Parse(db.sp_upsert_legs(readout_id, competitor_id, course_id, guessed_course, action).FirstOrDefault().ToString());
int y= UpdateTeamRaceEnd(competitor_id);
}
int slip_id = this.InsertSlip(leg_id);
//
//_ = PostSlip(readout_id);
return 0; //processedResult;
}
public int GetRunnerByCardId(string cardId)
{
int competitor_id;
long chip_id = Int32.Parse(cardId);
try
{
using (var db = new klc01())
{
competitor_id = db.competitors.First(a => a.comp_chip_id == chip_id).comp_id;
}
return competitor_id;
}
catch (Exception ex)
{
//MessageBox.Show($"An exception occured finding {chip_id}: \n\n{ex.Message}.", "ReaderDemoProject", MessageBoxButtons.OK, MessageBoxIcon.Error);
return 0;
}
}
public List<int> GuessCourse(int readout_id)
{
using (var db = new klc01())
{
var a = db.sp_guess_course(readout_id);//.FirstOrDefault();
return a.Where(x => x != null).Cast<int>().ToList();
//return b;
}
}
public int GetCourseFromLegs(long competitor_id)
{
using (var db = new klc01())
{
var leg = db.legs.FirstOrDefault(a => a.comp_id == competitor_id && a.readout_id == null);
if (leg == null)
return 0;
else
return (int)leg.course_id;
}
}
public int GetCourseAndGuessed(int competitor_id, int readout_id, out int guessed_course)
{
int course_id = 0;
List<int> guessed_courses;
try
{
course_id = this.GetCourseFromLegs(competitor_id);
guessed_courses = this.GuessCourse(readout_id);
if (course_id == 0)
{
if (guessed_courses.Count() == 1)
course_id = guessed_courses[0];
else
{
using (var db = new klc01())
{
course_id = db.slips.Where(b => b.readout_id == readout_id).Select(s => s.course_id).FirstOrDefault();
}
}
while (course_id == 0)
{
//unknown course
frmCourseNotFound frm = new frmCourseNotFound(competitor_id, readout_id);
frm.ShowDialog();
course_id = frm.course;
frm.course = 0;
}
}
if (guessed_courses.Contains(course_id))
guessed_course = course_id;
else
guessed_course = 0;
return course_id;
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
string err = "";
foreach (var eve in ex.EntityValidationErrors)
{
err += "Entity of type " + eve.Entry.Entity.GetType().Name + " in state " + eve.Entry.State + " has the following validation errors:";
foreach (var ve in eve.ValidationErrors)
{
err += "- Property: " + ve.PropertyName + ", Error: " + ve.ErrorMessage + "";
}
}
MessageBox.Show(err);
throw;
}
}
public int InsertLeg(int readout_id, int competitor_id, out int guessed_course)
{
using (var db = new klc01())
{
int course_id;
try
{
course_id = GetCourseAndGuessed(competitor_id, readout_id, out guessed_course);
//update or insert to legs
int leg_id = int.Parse(db.sp_upsert_legs(readout_id, competitor_id, course_id, guessed_course, "I").FirstOrDefault().ToString());
int x = UpdateTeamRaceEnd(competitor_id);
return leg_id;
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
string err = "";
foreach (var eve in ex.EntityValidationErrors)
{
err += "Entity of type " + eve.Entry.Entity.GetType().Name + " in state " + eve.Entry.State + " has the following validation errors:";
foreach (var ve in eve.ValidationErrors)
{
err += "- Property: " + ve.PropertyName + ", Error: " + ve.ErrorMessage + "";
}
}
MessageBox.Show(err);
throw;
}
}
}
public int UpdateTeamRaceEnd(int competitor_id)
{
using (var db = new klc01())
{
try
{
int cnt = int.Parse(db.update_team_race_end(competitor_id).ToString());
return cnt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw;
}
}
}
public int InsertSlip(int leg_id)
{
using (var db = new klc01())
{
try
{
//update or insert to slips
return db.sp_insert_slips(leg_id);
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
string err = "";
foreach (var eve in ex.EntityValidationErrors)
{
err += "Entity of type " + eve.Entry.Entity.GetType().Name + " in state " + eve.Entry.State + " has the following validation errors:";
foreach (var ve in eve.ValidationErrors)
{
err += "- Property: " + ve.PropertyName + ", Error: " + ve.ErrorMessage + "";
}
}
MessageBox.Show(err);
throw;
}
}
}
public long GetResult(SportidentCard card)//, long competitor_id)
{
if (card == null)
{
throw new ArgumentNullException("card");
}
return 0;
}
public static async Task RegisterClient()
{
using (var db = new klc01())
{
string url = db.settings.FirstOrDefault(c => c.config_name == "live_url").config_value;
string uid= db.settings.FirstOrDefault(c => c.config_name == "live_user").config_value;
string pwd = db.settings.FirstOrDefault(c => c.config_name == "live_password").config_value;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url + "/register");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"client_name\":\"" + uid + "\"," +
"\"password\":\""+ pwd + "\"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
}
public static async Task<string> LoginClient()
{
using (var db = new klc01())
{
HttpClient httpClient = new HttpClient();
string url = db.settings.FirstOrDefault(c => c.config_name == "live_url").config_value;
string pwd = db.settings.FirstOrDefault(c => c.config_name == "live_password").config_value;
string uid = db.settings.FirstOrDefault(c => c.config_name == "live_user").config_value;
string uri = url + "/login";
string json = "{\"client_name\":\"" + uid + "\"," +
"\"password\":\"" + pwd + "\"}";
StringContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(uri, httpContent);
// Save the token for further requests.
var responseToken = await response.Content.ReadAsStringAsync();
dynamic JsonResponse = JObject.Parse(responseToken);
string token = JsonResponse.token;
//update token in db
var result = db.settings.FirstOrDefault(c => c.config_name == "live_token");
if (result != null)
{
result.config_value = token;
db.SaveChanges();
}
// Set the authentication header.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return token != null ? token : null;
}
}
public static async Task TruncateEntries()
{
using (var db = new klc01())
{
HttpClient client = new HttpClient();
string live_entries = db.settings.FirstOrDefault(c => c.config_name == "live_entries_truncate").config_value;
string live_urls = db.settings.FirstOrDefault(c => c.config_name == "live_url").config_value;
string pwd = db.settings.FirstOrDefault(c => c.config_name == "live_password").config_value;
string[] urls = live_urls.Split(';');
string json = "{\"truncate\":\"yes\"," +
"\"password\":\"" + pwd + "\"}";
foreach (string oneUrl in urls)
{
string url_truncate = oneUrl + live_entries;
//make request
StringContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url_truncate, httpContent);
try
{
response.EnsureSuccessStatusCode();
}
catch
{
MessageBox.Show("ERR EnsureSuccessStatusCode truncate");
return;
}
string info = await response.Content.ReadAsStringAsync();
MessageBox.Show("API response: " + info);
}
}
}
public static async Task PostEntries(int team = -1)
{
int i = 0;
using (var db = new klc01())
{
List<int> AllTeams;
if(team == -1)
{
AllTeams = db.teams.Where(s => s.team_did_start == true)
.Select(s => s.team_id).ToList();
}
else
{
AllTeams = db.teams.Where(s => s.team_did_start == true && s.team_id == team)
.Select(s => s.team_id).ToList();
}
if (AllTeams.Count > 0)
{
//send all entries
HttpClient client = new HttpClient();
string live_urls = db.settings.FirstOrDefault(c => c.config_name == "live_url").config_value;
string live_entries = db.settings.FirstOrDefault(c => c.config_name == "live_entries").config_value;
string[] urls = live_urls.Split(';');
string entry;
foreach (int team_id in AllTeams)
{
entry = db.get_one_entry_json(team_id).FirstOrDefault();
string filename = @"c:\temp\entry_post_" + team_id + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".json";
File.WriteAllText(filename, entry);
foreach (string oneUrl in urls)
{
string url_entries = oneUrl + live_entries;
//var data = new FormUrlEncodedContent(entry);
var entry_content = new StringContent(
entry,
System.Text.Encoding.UTF8,
"application/json"
);
HttpResponseMessage response = await client.PostAsync(url_entries, entry_content);
try
{
response.EnsureSuccessStatusCode();
}
catch
{
MessageBox.Show("ERR EnsureSuccessStatusCode post");
return;
}
var result = await response.Content.ReadAsStringAsync();
i++;
}
}
}
}
//return i;
}
public static async Task TruncateCompetitors()
{
using (var db = new klc01())
{
HttpClient client = new HttpClient();
string live_competitors = db.settings.FirstOrDefault(c => c.config_name == "live_competitors_truncate").config_value;
string live_urls = db.settings.FirstOrDefault(c => c.config_name == "live_url").config_value;
string pwd = db.settings.FirstOrDefault(c => c.config_name == "live_password").config_value;
string[] urls = live_urls.Split(';');
string json = "{\"truncate\":\"yes\"," +
"\"password\":\"" + pwd + "\"}";
foreach (string oneUrl in urls)
{
string url_truncate = oneUrl + live_competitors;
//make request
StringContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url_truncate, httpContent);
try
{
response.EnsureSuccessStatusCode();
}
catch
{
MessageBox.Show("ERR EnsureSuccessStatusCode truncate");
return;
}
string info = await response.Content.ReadAsStringAsync();
MessageBox.Show("API response: " + info);
}
}
}
public static async Task PostCompetitors(int comp = -1)
{
int i = 0;
using (var db = new klc01())
{
List<int> AllTeams;
if (comp == -1)
{
AllTeams = db.competitors.Where(s => s.comp_valid_flag == true)
.Select(s => s.comp_id).ToList();
}
else
{
AllTeams = db.competitors.Where(s => s.comp_valid_flag == true && s.comp_id == comp)
.Select(s => s.comp_id).ToList();
}
if (AllTeams.Count > 0)
{
//send all entries
HttpClient client = new HttpClient();
string live_urls = db.settings.FirstOrDefault(c => c.config_name == "live_url").config_value;
string live_competitors = db.settings.FirstOrDefault(c => c.config_name == "live_competitors").config_value;
string[] urls = live_urls.Split(';');
string entry;
foreach (int comp_id in AllTeams)
{
entry = db.get_one_competitor_json(comp_id).FirstOrDefault();
string filename = @"c:\temp\comp_post_" + comp_id + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".json";
File.WriteAllText(filename, entry);
foreach (string oneUrl in urls)
{
string url_competitors = oneUrl + live_competitors;
//var data = new FormUrlEncodedContent(entry);
var entry_content = new StringContent(
entry,
System.Text.Encoding.UTF8,
"application/json"
);
HttpResponseMessage response = await client.PostAsync(url_competitors, entry_content);
try
{
response.EnsureSuccessStatusCode();
}
catch
{
MessageBox.Show("ERR EnsureSuccessStatusCode post");
return;
}
var result = await response.Content.ReadAsStringAsync();
i++;
}
}
}
}
//return i;
}
public async static Task<string> OrisGetEntries()
{
string result;
using (var db = new klc01())
{
//get entries from Oris
HttpClient client = new HttpClient();
string url = db.settings.FirstOrDefault(c => c.config_name == "oris_entries").config_value;
//string entry;
HttpResponseMessage response = await client.GetAsync(url);
try
{
response.EnsureSuccessStatusCode();
}
catch
{
MessageBox.Show("ERR EnsureSuccessStatusCode post");
return "0";
}
result = await response.Content.ReadAsStringAsync();
string filename = @"c:\temp\oris_entries_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xml";
File.WriteAllText(filename, result);
}
return result;
}
public static string FormatXml(string xml)
{
try
{
XDocument doc = XDocument.Parse(xml);
return doc.ToString();
}
catch (Exception)
{
// Handle and throw if fatal exception here; don't just ignore them
return xml;
}
}
public static async Task<string> PostSlip(int readout_id)
{
string url;
string allResponses = "";
string oneResponse = "";
HttpClient client = new HttpClient();
//int i = 0;
using (var db = new klc01())
{
string OneSlip;
OneSlip = db.get_slip_json(readout_id).FirstOrDefault();
//write punch log
string filename = @"c:\temp\slip_post_" + readout_id + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".json";
File.WriteAllText(filename, OneSlip);
string live_urls = db.settings.FirstOrDefault(c => c.config_name == "live_url").config_value;
string url_slips = db.settings.FirstOrDefault(c => c.config_name == "live_slips").config_value;
string[] urls = live_urls.Split(';');
foreach (string oneUrl in urls)
{
url = oneUrl + url_slips;
var content = new StringContent(
OneSlip,
System.Text.Encoding.UTF8,
"application/json"
);
var response = await client.PostAsync(url, content);
try
{
response.EnsureSuccessStatusCode();
oneResponse = url + " " + await response.Content.ReadAsStringAsync();
}
catch
{
MessageBox.Show("ERR EnsureSuccessStatusCode post");
oneResponse = url + "ERR EnsureSuccessStatusCode post";
}
allResponses += oneResponse;
}
}
return allResponses;
}
private void SetTxtInfo(EnvironmentVariableTarget result)
{
FrmMain frmMain = new FrmMain();
frmMain.txtInfo.AppendText(result.ToString());
}
/* public DateTime GetStartTime(long competitor_id)
{
int prevRunnerId = this.GetPrevRunnerId(competitor_id);
Result prevRunnerResult = this.dao.GetResultByRunnerId(prevRunnerId);
Result prevTeamResult = this.dao.GetMaxResultByTeam(runner.Team.Id);
DateTime startTime = new DateTime();
if (prevRunnerResult == null && prevTeamResult == null)
{
startTime = Constants.ZeroTime;
}
else if ((prevTeamResult != null && prevRunnerResult == null) || (prevTeamResult.Id > prevRunnerResult.Id))
{
startTime = prevTeamResult.FinishTime;
}
else
{
startTime = prevRunnerResult.FinishTime;
}
return startTime;
}
*/
/*
private long GetPrevRunnerId(long competitor_id)
{
int prevRunnerId = 0;
Dictionary<int, int> positions = this.dao.GetRunnerPositions(runner.Team.Id);
prevRunnerId = this.CalculatePrevRunnerId(runner.Position, positions);
}
return prevRunnerId;
}
*/
public static async Task TruncateLegs()
{
using (var db = new klc01())
{
HttpClient client = new HttpClient();
string live_legs = db.settings.FirstOrDefault(c => c.config_name == "live_legs_truncate").config_value;
string live_urls = db.settings.FirstOrDefault(c => c.config_name == "live_url").config_value;
string[] urls = live_urls.Split(';');
string pwd = db.settings.FirstOrDefault(c => c.config_name == "live_password").config_value;
string json = "{\"truncate\":\"yes\"," +
"\"password\":\"" + pwd + "\"}";
foreach (string oneUrl in urls)
{
string url_truncate = oneUrl + live_legs;
//make request
StringContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url_truncate, httpContent);
try
{
response.EnsureSuccessStatusCode();
}
catch
{
MessageBox.Show("ERR EnsureSuccessStatusCode truncate");
return;
}
string info = await response.Content.ReadAsStringAsync();
MessageBox.Show("API response: " + info);
}
}
}
public static async Task StartEndRocService(bool start_service)
{
using (var db = new klc01())
{
HttpClient client = new HttpClient();
string service_config = "stop_roc_service";
if (start_service)
{
service_config = "start_roc_service";
}
string live_roc = db.settings.FirstOrDefault(c => c.config_name == service_config).config_value;
string live_urls = db.settings.FirstOrDefault(c => c.config_name == "live_url").config_value;
string[] urls = live_urls.Split(';');
string pwd = db.settings.FirstOrDefault(c => c.config_name == "live_password").config_value;
foreach (string oneUrl in urls)
{
string url_roc_service = oneUrl + live_roc;
string json = "{\"truncate\":\"yes\"," +
"\"password\":\"" + pwd + "\"}";
//make request
StringContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url_roc_service, httpContent);
try
{
response.EnsureSuccessStatusCode();
}
catch
{
MessageBox.Show("ERR EnsureSuccessStatusCode truncate");
return;
}
string info = await response.Content.ReadAsStringAsync();
MessageBox.Show("API response: " + info);
}
}
}
}
}