-
Notifications
You must be signed in to change notification settings - Fork 2
/
NewCard.cs
1438 lines (1258 loc) · 56.4 KB
/
NewCard.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 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;
using Serilog;
using System.Data.Entity;
using System.Runtime.Remoting.Contexts;
using System.Reflection;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Security.Policy;
using Microsoft.Reporting.WebForms;
namespace h24
{
public class NewCard
{
//klc01 db;
private static List<string> _errors = new List<string>();
public static string get_config_item(string cofnig_name)
{
var db = new klc01();
string config_value = "";
/*var config = db.settings.FirstOrDefault(c => c.config_name == cofnig_name);
if (config != null)
{
config_value = config.config_value;
}*/
config_value = SettingsManager.GetSetting(cofnig_name);
return config_value;
}
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(x => x.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 a = ApplyLegException(leg_id);
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 static bool IsASubsequenceOfB(List<int> A, List<int> B)
{
int aIndex = 0;
int bIndex = 0;
while (aIndex < A.Count && bIndex < B.Count)
{
if (A[aIndex] == B[bIndex])
{
aIndex++;
bIndex++;
}
else
{
bIndex++;
}
}
return aIndex == A.Count;
}
public static bool IsBInCorrectOrder(List<int> A, List<int> B)
{
int aIndex = 0;
int bIndex = 0;
while (bIndex < B.Count)
{
if (aIndex < A.Count && A[aIndex] == B[bIndex])
{
aIndex++;
bIndex++;
}
else
{
bIndex++;
}
}
return aIndex == A.Count;
}
*/
public List<int> GuessCourse(int readout_id)
{
using (var db = new klc01())
{
//TODO rewwrite here
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
{
course_id = 0;
}
while (course_id == 0)
{
using (var db = new klc01())
{
int course_id_from_slips = db.slips.Where(b => b.readout_id == readout_id).Select(s => s.course_id).FirstOrDefault();
//unknown course
frmCourseNotFound frm = new frmCourseNotFound(competitor_id, readout_id, course_id_from_slips);
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 UpsertLeg( int readout_id, int competitor_id, int course_id, int guessed_course, string action)
{
int dsk_penalty = int.Parse(get_config_item("dsk_penalty"));
using (var db = new klc01())
{
//
var query = from co in db.competitors
join t in db.teams on co.team_id equals t.team_id
join ca in db.categories on t.cat_id equals ca.cat_id
where co.comp_id == competitor_id
select new {
ca.force_order,
ca.cat_start_time,
t.team_id
};
var result = query.FirstOrDefault();
bool force_order = (bool)result.force_order;
DateTime start_time = (DateTime)result.cat_start_time;
int team_id = (int)result.team_id;
//previous finish + previous competitor
/*var query_legs_teams = from l in db.legs
join co in db.competitors on l.comp_id equals co.comp_id
where co.team_id == team_id;
//if force_order
*/
/*
INSERT INTO dbo.legs
(
INSERT INTO dbo.legs
(
comp_id,
course_id,
readout_id,
start_dtime,
start_time,
finish_dtime,
finish_time,
leg_status,
dsk_penalty,
valid_flag
)
*/
}
int leg_id = 0;
return leg_id;
}
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 static int ApplyLegException(int leg_id)
{
int i = 0;
using (var db = new klc01())
{
//legs leg = db.legs.Where(x => x.leg_id == leg_id).FirstOrDefault();
var legsUpdate = from l in db.legs
join le in db.leg_exceptions
on l.leg_id equals le.leg_id
where l.leg_id == leg_id
select new { Legs = l, ex_leg_status = le.ex_leg_status, ex_dsk_penalty = le.ex_dsk_penalty, ex_valid_flag = le.ex_valid_flag };
foreach(var item in legsUpdate)
{
item.Legs.leg_status = item.ex_leg_status;
item.Legs.dsk_penalty = item.ex_dsk_penalty;
item.Legs.valid_flag = item.ex_valid_flag;
i++;
}
db.SaveChanges();
}
return i;
}
public static int UpdateTeamRaceEnd(int competitor_id)
{
using (var db = new klc01())
{
try
{
int cnt = int.Parse(db.update_team_race_end(competitor_id).ToString());
//int cnt = int.Parse(db.update_team_race_end_increment(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 = get_config_item("live_url");
string uid = get_config_item("live_user");
string pwd = get_config_item("live_password");
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 = get_config_item("live_url");
string pwd = get_config_item("live_password");
string uid = get_config_item("live_user");
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 = get_config_item("live_token");
if (result != null)
{
result = token;
db.SaveChanges();
}
// Set the authentication header.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return token != null ? token : null;
}
}
public async Task TruncateEntries()
{
using (var db = new klc01())
{
HttpClient client = new HttpClient();
string live_entries_truncate = get_config_item("live_entries_truncate");
string live_urls = get_config_item("live_url");
string pwd = get_config_item("live_password");
string q_status_in_progress = get_config_item("q_status_in_progress");
string q_status_failed = get_config_item("q_status_failed");
string[] urls = live_urls.Split(';');
string json = "{\"truncate\":\"yes\"," +
"\"password\":\"" + pwd + "\"}";
foreach (string oneUrl in urls)
{
int q_id = Insert_api_queue(oneUrl + live_entries_truncate, json, q_status_in_progress, null);
try
{
api_queue api_queue_request = db.api_queue.FirstOrDefault(a => a.q_id == q_id);
//fire queue processing
bool success = await SendApiRequest(api_queue_request);
}
catch (Exception e)
{
UpdateApiRequestStatus(q_id, q_status_failed);
}
}
}
}
public async Task PostEntries(int team = -1)
{
int i = 0;
//int q_id = 0;
string json_log_path = get_config_item("json_log_path") == "" ? @"c:\temp\" : get_config_item("json_log_path");
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 = get_config_item("live_url");
string live_entries = get_config_item("live_entries");
string q_status_in_progress = get_config_item("q_status_in_progress");
string q_status_failed = get_config_item("q_status_failed");
string[] urls = live_urls.Split(';');
string entry;
foreach (int team_id in AllTeams)
{
entry = db.get_one_entry_json(team_id).FirstOrDefault();
string filename = json_log_path + @"entry_post_" + team_id + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".json";
File.WriteAllText(filename, entry);
foreach (string oneUrl in urls)
{
int q_id = Insert_api_queue(oneUrl + live_entries, entry != null ? entry : "", q_status_in_progress, null);
Insert_api_queue_link(q_id, "entry", team_id);
try
{
api_queue api_queue_request = db.api_queue.FirstOrDefault(a => a.q_id == q_id);
//fire queue processing
bool success = await SendApiRequest(api_queue_request);
}
catch (Exception e)
{
UpdateApiRequestStatus(q_id, q_status_failed);
}
}
}
}
}
//return i;
}
public async Task TruncateCompetitors()
{
using (var db = new klc01())
{
HttpClient client = new HttpClient();
string live_competitors_truncate = get_config_item("live_competitors_truncate");
string live_urls = get_config_item("live_url");
string pwd = get_config_item("live_password");
string q_status_in_progress = get_config_item("q_status_in_progress");
string q_status_failed = get_config_item("q_status_failed");
string[] urls = live_urls.Split(';');
string json = "{\"truncate\":\"yes\"," +
"\"password\":\"" + pwd + "\"}";
foreach (string oneUrl in urls)
{
int q_id = Insert_api_queue(oneUrl + live_competitors_truncate, json, q_status_in_progress, null);
try
{
api_queue api_queue_request = db.api_queue.FirstOrDefault(a => a.q_id == q_id);
//fire queue processing
bool success = await SendApiRequest(api_queue_request);
}
catch (Exception e)
{
UpdateApiRequestStatus(q_id, q_status_failed);
}
}
}
}
public static async Task PostCompetitors(int comp = -1)
{
int i = 0;
string json_log_path = get_config_item("json_log_path") == "" ? @"c:\temp\" : get_config_item("json_log_path");
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 = get_config_item("live_url");
string live_competitors = get_config_item("live_competitors");
string[] urls = live_urls.Split(';');
string entry;
foreach (int comp_id in AllTeams)
{
entry = db.get_one_competitor_json(comp_id).FirstOrDefault();
string filename = json_log_path + @"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;
string json_log_path = get_config_item("json_log_path") == "" ? @"c:\temp\" : get_config_item("json_log_path");
using (var db = new klc01())
{
//get entries from Oris
HttpClient client = new HttpClient();
string url = get_config_item("oris_entries");
//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 = json_log_path + @"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;
}
}
//API
public static List<api_queue> GetPendingApiRequestsFromDatabase()
{
Log.Information("GetPendingApiRequestsFromDatabase");
var db = new klc01();
string status_new = NewCard.get_config_item("q_status_new");
string status_done = NewCard.get_config_item("q_status_completed");
int queue_timeout = Int32.Parse(NewCard.get_config_item("api_queue_timeout"));
DateTime latest = DateTime.Now.AddSeconds(-queue_timeout);
var olderThanSeconds = db.api_queue
.Where(a => a.q_status == status_new || (a.q_status != status_done && a.as_of_date < latest))
.ToList();
return olderThanSeconds; // Replace with actual implementation
}
public async void CheckApiRequests(object state)
{
Log.Information("CheckApiRequests");
//check new ROC punches
string a = CheckNewROC();
// Check the database for pending requests
List<api_queue> pendingRequests = GetPendingApiRequestsFromDatabase();
Log.Information("pendingRequests:" + pendingRequests.Count());
foreach (api_queue apiRequest in pendingRequests)
{
Log.Information("CheckApiRequests - process " + apiRequest.q_id);
try
{
// Attempt to send the request to the API
bool success = await SendApiRequest(apiRequest);
Log.Information("SendApiRequest finished " + apiRequest.q_id);
}
catch (Exception e)
{
WriteLog($"CheckApiRequests: {e.Message}\n q_id={apiRequest.q_id}", "CheckApiRequests");
Log.Error($"CheckApiRequests E: {e.Message}\n q_id={apiRequest.q_id}");
}
// Update the status based on the result
//UpdateApiRequestStatus(apiRequest.q_id, success ? "Sent" : "Failed");
/* if (!success)
{
// If the request fails, you can re-enqueue it or implement retry logic
// For simplicity, let's assume requests are removed on failure
MessageBox.Show("API request failed. Please check your internet connection.");
}*/
}
}
// Implement your method to send API requests here
public async Task<bool> SendApiRequest(api_queue request)
{
Log.Information("SendApiRequest " + request.q_id);
// Your API request implementation logic here
// Return true if the request was successful, false if it failed
string q_status_in_progress = get_config_item("q_status_in_progress");
string q_status_failed = get_config_item("q_status_failed");
string q_status_completed = get_config_item("q_status_completed");
UpdateApiRequestStatus(request.q_id, q_status_in_progress);
Log.Information("request "+ request.q_content);
//send
//HttpClientHandler _httpHandler = new HttpClientHandler();
//var _httpHandler = new HttpClientHandler();
/*_httpHandler.Proxy = null;
_httpHandler.UseProxy = false;
_httpHandler.AutomaticDecompression = System.Net.DecompressionMethods.GZip;*/
//HttpClient client = new HttpClient(_httpHandler);
HttpClient client = new HttpClient();
HttpContent content = new StringContent(
request.q_content,
System.Text.Encoding.UTF8,
"application/json"
);
string oneResponse = "";
if (request.q_header != "")
{
client.DefaultRequestHeaders.Add("Accept", "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");//.Add("Content-Type", "application/json");
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", request.q_header);
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", request.q_header);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", request.q_header);
}
//Log.Information("client: " + content.ToString());
var response = await client.PostAsync(request.q_url, content);
try
{
response.EnsureSuccessStatusCode();
oneResponse = await response.Content.ReadAsStringAsync();
UpdateApiResponse(request.q_id, oneResponse, q_status_completed);
return true;
}
catch (Exception e)
{
oneResponse = response.Content.ReadAsStringAsync().Result;
Log.Error(request.q_url + " " + response.Content.ReadAsStringAsync().Result + "; " + $"Sending error: {e.Message}");
UpdateApiResponse(request.q_id, oneResponse, q_status_failed);
return false;
}
}
private void UpdateApiRequestStatus(int requestId, string status)
{
Log.Information("UpdateApiRequestStatus " + requestId );
using (var db = new klc01())
{
var result = db.api_queue.SingleOrDefault(b => b.q_id == requestId);
if (result != null)
{
result.q_status = status;
result.as_of_date = DateTime.Now;
db.SaveChanges();
}
}
}
private void UpdateApiResponse(int requestId, string response, string status)
{
Log.Information("UpdateApiResponse " + requestId + " " + response);
string q_response;
using (var db = new klc01())
{
try
{
var result = db.api_queue.SingleOrDefault(b => b.q_id == requestId);
if (result != null)
{
q_response = response + "; " + result.q_response;
result.q_response = q_response.Left(3990);
result.q_status = status;
db.SaveChanges();
}
}
catch (Exception e)
{
MessageBox.Show("UpdateApiResponse " + e.Message);
}
}
}
public async Task<string> PostSlip(int readout_id)
{
Log.Information("PostSlip " + readout_id);
string json_log_path = get_config_item("json_log_path") == "" ? @"c:\temp\" : get_config_item("json_log_path");
//insert record to queue
using (var db = new klc01())
{
string OneSlip;
int q_id = 0;
OneSlip = db.get_slip_json(readout_id).FirstOrDefault();
//write punch log
string filename = json_log_path + @"slip_post_" + readout_id + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".json";
File.WriteAllText(filename, OneSlip);
string live_urls = get_config_item("live_url");
string url_slips = get_config_item("live_slips");
string q_status_in_progress = get_config_item("q_status_in_progress");
string q_status_failed = get_config_item("q_status_failed");
string[] urls = live_urls.Split(';');
foreach (string oneUrl in urls)
{
q_id = Insert_api_queue(oneUrl + url_slips, OneSlip != null ? OneSlip : "", q_status_in_progress, null);
Insert_api_queue_link(q_id, "readout", readout_id);
try
{
api_queue api_queue_request = db.api_queue.FirstOrDefault(a => a.q_id == q_id);
//fire queue processing
bool success = await SendApiRequest(api_queue_request);
}
catch (Exception e)
{
UpdateApiRequestStatus(q_id, q_status_failed);
}
}
return "";
}
}
public string CheckNewROC()
{
Log.Information("CheckNewROC");
string json_log_path = get_config_item("json_log_path") == "" ? @"c:\temp\" : get_config_item("json_log_path");
//insert record to queue
using (var db = new klc01())
{
//write punch log
string filename;
string sms_url = get_config_item("sms_url");
string url_roc = get_config_item("live_roc");
string q_status_completed = get_config_item("q_status_completed");
string q_status_new = get_config_item("q_status_new");
var new_punches = db.v_new_roc_punches.ToList();
/* TODO: this query works, but I don't know how to pass the result to Insert_queue_SMS
* var query = from p in db.roc_punches
join c in db.competitors on p.ChipNr equals c.comp_chip_id
join t in db.teams on c.team_id equals t.team_id
join ca in db.categories on t.cat_id equals ca.cat_id
where p.status == null && DbFunctions.AddMinutes(p.as_of_date, 5) > DateTime.Now
select new
{
record_id = p.p_id,
control_code = p.CodeNr,
chip_id = p.ChipNr,
punch_date = p.PunchTime,
ca.cat_name,
t.team_nr,
t.team_name,
c.comp_name,
c.bib,
t.phone_number
};
var resultList = query.ToList();*/
int i = 0;
foreach (var punch in new_punches)
{
//sms
string sms_send = get_config_item("sms_send");
if (sms_send == "true")
{
Insert_queue_SMS(punch);
}
//online results
string content = "{\"record_id\":" + punch.record_id +
", \"control_code\":" + punch.control_code +
", \"chip_id\":" + punch.chip_id +
",\"punch_date\":\"" + punch.punch_date.Value.ToString("yyyy-MM-dd HH:mm:ss") +
"\", \"cat_name\":\"" + punch.cat_name +
"\", \"team_nr\":" + punch.team_nr +
", \"team_name\":\"" + punch.team_name +
"\", \"comp_name\":\"" + punch.comp_name +
"\", \"comp_bib\":\"" + punch.bib + "\"}";
filename = json_log_path + @"roc_post_" + i + "_" + punch.chip_id + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".json";
if (File.Exists(filename))
filename = json_log_path + @"roc_post_" + i + "_" + punch.chip_id + "a_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".json";
//File.Delete(filename);
try
{
File.WriteAllText(filename, content);
}
catch (Exception e)
{
Log.Error("ERROR: CheckNewROC " + e.Message);
//MessageBox.Show("CheckNewROC " + e.Message);
}
//different servers
string live_urls = get_config_item("live_url");
string[] urls = live_urls.Split(';');
foreach (string oneUrl in urls)
{
try