-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSampleCodeREST.cs
More file actions
3598 lines (3234 loc) · 180 KB
/
Copy pathSampleCodeREST.cs
File metadata and controls
3598 lines (3234 loc) · 180 KB
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
#region DISCLAIMER
/* Copyright (c) 2014 NAB, LLC. - All Rights Reserved.
*
* This software and documentation is subject to and made
* available only pursuant to the terms of an executed license
* agreement, and may be used only in accordance with the terms
* of said agreement. This software may not, in whole or in part,
* be copied, photocopied, reproduced, translated, or reduced to
* any electronic medium or machine-readable form without
* prior consent, in writing, from NAB, LLC.
*
* Use, duplication or disclosure by the U.S. Government is subject
* to restrictions set forth in an executed license agreement
* and in subparagraph (c)(1) of the Commercial Computer
* Software-Restricted Rights Clause at FAR 52.227-19; subparagraph
* (c)(1)(ii) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227-7013, subparagraph (d) of the Commercial
* Computer Software--Licensing clause at NASA FAR supplement
* 16-52.227-86; or their equivalent.
*
* Information in this software is subject to change without notice
* and does not represent a commitment on the part of NAB.
*
* Sample Code is for reference Only and is intended to be used for educational purposes. It's the responsibility of
* the software company to properly integrate into thier solution code that best meets thier production needs.
*/
#endregion DISCLAIMER
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using System.Text;
using System.Windows.Forms;
using SampleCodeREST;
namespace SampleCode
{
public partial class SampleCodeREST : Form
{
private string _IdentityToken = "PHNhbWw6QXNzZXJ0aW9uIE1ham9yVmVyc2lvbj0iMSIgTWlub3JWZXJzaW9uPSIxIiBBc3NlcnRpb25JRD0iXzNlYzc3M2FkLTExNzYtNDQzMi1hOGZmLTZiMjQyZDg2YzdlZiIgSXNzdWVyPSJJcGNBdXRoZW50aWNhdGlvbiIgSXNzdWVJbnN0YW50PSIyMDE0LTA2LTEwVDIxOjIxOjU5LjAwMFoiIHhtbG5zOnNhbWw9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjEuMDphc3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lObDZ0VUlwaUg3d0RaWVN2blpLNHRLeUJaRWhKODRCK1o1bkYxZlgwOVVpRnVFdHRyV0RKV1ErbHhkdmdaa09FYWxYMG5YNTRJK2pBVnBFOFlkcjlPTlZ0U0ltSmxqaFBTZ1FnMndYSU1DOEtWbzdtd1FRWDkwbGFXdWxzRXByd3hiQnpLVTgxaU9SQ0E1K3JUSnN1aHBoYU9VamY2RkZOTHBEM2htOHV1MWdCOVFXcGZYUDc3VXVqUGFUNHMzZTI5eDA2bFU4WGNOb2FON1BZSHY2ZHFzL3Arc2E5T1VBZWlLT2VleXk1bHQ4aUE5RE53eGM4bThKL3RZNk9VWEtoRnR5UlExTXJRZU9vVHRxU3o5NGxtdVVCY3NleWxoOFFPVmJRPT08L1NpZ25hdHVyZVZhbHVlPjxLZXlJbmZvPjxvOlNlY3VyaXR5VG9rZW5SZWZlcmVuY2UgeG1sbnM6bz0iaHR0cDovL2RvY3Mub2FzaXMtb3Blbi5vcmcvd3NzLzIwMDQvMDEvb2FzaXMtMjAwNDAxLXdzcy13c3NlY3VyaXR5LXNlY2V4dC0xLjAueHNkIj48bzpLZXlJZGVudGlmaWVyIFZhbHVlVHlwZT0iaHR0cDovL2RvY3Mub2FzaXMtb3Blbi5vcmcvd3NzL29hc2lzLXdzcy1zb2FwLW1lc3NhZ2Utc2VjdXJpdHktMS4xI1RodW1icHJpbnRTSEExIj5IY2cvdDBCSE1hSFdWeGs4c3EvelF5NHpySmc9PC9vOktleUlkZW50aWZpZXI+PC9vOlNlY3VyaXR5VG9rZW5SZWZlcmVuY2U+PC9LZXlJbmZvPjwvU2lnbmF0dXJlPjwvc2FtbDpBc3NlcnRpb24+";
//The following PTLS SocketId is used for Sandbox and Certification transactions. Once certified, the software company will
//receive a production PTLS SocketId. This value is intended to be compiled into the software application that was certified.
private string _PTLSSocketId =
@"MIIEwjCCA6qgAwIBAgIBEjANBgkqhkiG9w0BAQUFADCBsTE0MDIGA1UEAxMrSVAgUGF5bWVudHMgRnJhbW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1ld29yay5jb22CCQD/yDY5hYVsVzA9BglghkgBhvhCAQQEMBYuaHR0cHM6Ly93d3cuaXBwYXltZW50c2ZyYW1ld29yay5jb20vY2EtY3JsLnBlbTANBgkqhkiG9w0BAQUFAAOCAQEAFk/WbEleeGurR+FE4p2TiSYHMau+e2Tgi+L/oNgIDyvAatgosk0TdSndvtf9YKjCZEaDdvWmWyEMfirb5mtlNnbZz6hNpYoha4Y4ThrEcCsVhfHLLhGZZ1YaBD+ZzCQA7vtb0v5aQb25jX262yPVshO+62DPxnMiJevSGFUTjnNisVniX23NVouUwR3n12GO8wvzXF8IYb5yogaUcVzsTIxEFQXEo1PhQF7JavEnDksVnLoRf897HwBqcdSs0o2Fpc/GN1dgANkfIBfm8E9xpy7k1O4MuaDRqq5XR/4EomD8BWQepfJY0fg8zkCfkuPeGjKkDCitVd3bhjfLSgTvDg==";
private string _svcInfo = @"https://api.dev.nabcommerce.com/REST/2.0.18/SvcInfo";
private string _txn = @"https://api.dev.nabcommerce.com/REST/2.0.18/Txn";
private string _tms = @"https://api.dev.nabcommerce.com/REST/2.0.18/DataServices/TMS";
private string _SessionToken = "";
private DateTime _dtSessionToken;
//Save ServiceInformation obtails from calling getServiceInformation()
private readonly XmlDocument currentServiceInformation = new XmlDocument();
//Values required to process transactions
private string _ApplicationProfileId = "";
private string _WorkflowId = "";
private string _ServiceId = "";
private string _MerchantProfileId = "";
private string _AvailableWorkflowIds = "";
private response _LastResponse;
private bool _blnResponseMessage;
private IndustryTypeValues _industryTypeValues = new IndustryTypeValues("false", "OffPremises", "PINNotSupported", "KeyOnly", "Ecommerce", "Ecommerce", "Keyed");//Default to Ecommerce
//Ref Json to XML : http://msdn.microsoft.com/en-us/library/bb299886.aspx
// and http://www.json.org/
//Format JSON Online : http://jsonformat.com/#jsondataurllabel
public SampleCodeREST()
{
InitializeComponent();
//Current webservice releases available.
CboPTLSVersion.Items.Add(new item("1.17.18", "0"));
CboPTLSVersion.SelectedIndex = 0;
//Actions for Application Data - Typically only performed upon initial installation of software
//Note : Resultant variable to be stored : ApplicationProfileId
cboApplicationDataAction.Items.Add(new item("[Select Action]", "0"));
cboApplicationDataAction.Items.Add(new item("Get Application Data", "1"));
cboApplicationDataAction.Items.Add(new item("Save Application Data", "2"));
cboApplicationDataAction.Items.Add(new item("Delete Application Data", "3"));
cboApplicationDataAction.SelectedIndex = 0;
//Actions for managing Merchant Data - Depenging on number of merchants may or may not be commonly used
//Note : Resultant variable to be stored : MerchantProfileId
cboMerchantProfileAction.Items.Add(new item("[Select Action]", "0"));
cboMerchantProfileAction.Items.Add(new item("Get Merchant Profiles", "1"));
cboMerchantProfileAction.Items.Add(new item("Get Merchant Profile", "2"));
cboMerchantProfileAction.Items.Add(new item("Save Merchant Data", "3"));
cboMerchantProfileAction.Items.Add(new item("Delete Merchant Data", "4"));
cboMerchantProfileAction.SelectedIndex = 0;
TxtLoadIdentityToken.Text = _IdentityToken;
//Format the dateTimePicker for TMS queries
dtpStartTimeTMS.Format = DateTimePickerFormat.Custom;
dtpStartTimeTMS.CustomFormat = "dddd MM'/'dd'/'yyyy hh':'mm tt";
dtpStartTimeTMS.Value = DateTime.Now.AddHours(-2);
dtpEndTimeTMS.Format = DateTimePickerFormat.Custom;
dtpEndTimeTMS.CustomFormat = "dddd MM'/'dd'/'yyyy hh':'mm tt";
dtpEndTimeTMS.Value = DateTime.Now;
}
private void cmdPOST_Click(object sender, EventArgs e)
{
if (chkAlwaysCheckSessionToken.Checked)
checkTokenExpire();
if (txtReplaceInURL.Text.Length > 1)
txtUrl.Text = txtUrl.Text.Replace(txtReplaceInURL.Text, txtReplaceInURLWith.Text);
CreateRequest(txtUrl.Text, cboActionOrMethod.Text, txtRequest.Text, _SessionToken, "",
TransactionType.NotSet);
}
private void cmdSignOnWithToken_Click(object sender, EventArgs e)
{
SignOnWithToken();
}
public string RetrieveServiceKeyFromIdentityToken(string identityToken)
{
try
{
String clearToken = Encoding.UTF8.GetString(Convert.FromBase64String(identityToken));
//Now try and retrieve the Service Key from the XML
XmlDocument doc = new XmlDocument();
doc.LoadXml(clearToken);
XPathNavigator xnav = doc.CreateNavigator();
XmlNamespaceManager manager = new XmlNamespaceManager(xnav.NameTable);
manager.AddNamespace("SK", "urn:oasis:names:tc:SAML:1.0:assertion");
XPathNavigator node = xnav.SelectSingleNode("//SK:Attribute[@AttributeName='SAK']", manager);
return node.Value;
}
catch (Exception ex)
{
return "SK : Unknown";
}
}
private void cmdManageApplicationData_Click(object sender, EventArgs e)
{
checkTokenExpire();
item item = (item)cboApplicationDataAction.SelectedItem;
_ApplicationProfileId = txtApplicationProfileId.Text;
if (item.Value == "0")
{
MessageBox.Show("Please select an action");
return;
}
if (item.Value == "1")
{
//Get Application Data
if (_ApplicationProfileId.Length < 1)
{
MessageBox.Show("Please enter an ApplicationId");
return;
}
GetApplicationData();
return;
}
if (item.Value == "2")
{
//Save Application Data
SaveApplicationData();
return;
}
if (item.Value == "3")
{
//Delete Application Data
if (_ApplicationProfileId.Length < 1)
{
MessageBox.Show("Please enter an ApplicationId");
return;
}
DeleteApplicationData();
return;
}
}
private string CreateRequest(string _url, string _method, string _body, string _UserName, string _UserPassword,
TransactionType _transactionType)
{
//http://msdn.microsoft.com/en-us/library/bb969540(office.12).aspx
//http://www.daniweb.com/forums/thread241233.html
//http://stackoverflow.com/questions/897782/how-to-add-custom-http-header-for-c-web-service-client-consuming-axis-1-4-web-se
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = _method; //Valid values are "GET", "POST", "PUT" and "DELETE"
request.UserAgent =
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50215)";
request.ContentType = "text/xml; charset=utf-8";
request.Timeout = 1000 * 60;
//Authorization is made up of UserName and Password in the format [UserName]:[Password]. In this case the identity token is the only value set and is the [UserName]
String _Authorization = "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(_UserName + ":" + _UserPassword));
request.Headers.Add(HttpRequestHeader.Authorization, _Authorization);
//Capture the basical header information. Using a proxy sniffer would be prefered however this helps to capture most information.
string ContentLength = "";
if (request.ContentLength > 0)
ContentLength = "\r\nContent-Length: " + request.ContentLength;
string _HeaderInformation = _method + " " + request.Address.AbsolutePath + request.Address.Query +
"\r\n" + request.Headers.ToString().Trim() + "\r\nHost: " +
request.Address.Host + ContentLength + "\r\n\r\n";
if (_body.Length > 0)
{
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(_body);
writer.Close();
}
txtRequest.Text = _HeaderInformation + _body;
RTxtSummary.SelectionColor = Color.Blue;
RTxtSummary.AppendText("REQUEST : \r\n");
RTxtSummary.SelectionColor = Color.Black;
RTxtSummary.AppendText(_HeaderInformation + _body + "\r\n");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream data = response.GetResponseStream())
{
try
{
string text = new StreamReader(data).ReadToEnd();
//Log out request and response as well as process last response for follow-on messages.
//Diaplay in modal the request information?
if (ChkShowRequestModal.Checked)
{
ModalInformation mI = new ModalInformation();
mI.CallingForm("**** REQUEST****\r\n" + _HeaderInformation + _body +
"\r\n\r\n**** RESPONSE ****\r\n" + text);
//mI.CallingForm(_method + " " + request.Address.AbsolutePath + "\r\n" + request.Headers + "Host: " + request.Address.Host + "\r\n" + request.ContentLength + request.Expect + _body);
mI.ShowDialog(this);
}
else
{
//Confirm processing of last transaction
if (!_blnResponseMessage && TransactionType.NotSet != _transactionType)
{
MessageBox.Show("Successfully processed " + _transactionType +
" transaction. For more information about request and response check the show modal checkbox");
_blnResponseMessage = true;
}
}
txtResponse.Text = text;
RTxtSummary.SelectionColor = Color.Blue;
RTxtSummary.AppendText("\r\nRESPONSE : \r\n");
RTxtSummary.SelectionColor = Color.Black;
RTxtSummary.AppendText(text + "\r\n\r\n");
if (_transactionType != TransactionType.NotSet)
_LastResponse = ProcessResponse(text, _transactionType);
return text;
}
catch (Exception e)
{
throw e;
}
finally
{
data.Close();
}
}
}
catch (WebException ex2)
{
//Lets get the webException returned in the response
using (Stream data2 = ex2.Response.GetResponseStream())
{
try
{
string text = new StreamReader(data2).ReadToEnd();
txtResponse.Text = text;
RTxtSummary.SelectionColor = Color.Blue;
RTxtSummary.AppendText("\r\nRESPONSE : \r\n");
RTxtSummary.SelectionColor = Color.Black;
RTxtSummary.AppendText(text + "\r\n");
return text;
}
catch (Exception e)
{
throw e;
}
finally
{
data2.Close();
}
}
}
catch (Exception e)
{
return e.Message;
}
}
private string CreateRequest_Json(string _url, string _method, string _body, string _UserName, string _UserPassword,
TransactionType _transactionType)
{
//http://msdn.microsoft.com/en-us/library/bb969540(office.12).aspx
//http://www.daniweb.com/forums/thread241233.html
//http://stackoverflow.com/questions/897782/how-to-add-custom-http-header-for-c-web-service-client-consuming-axis-1-4-web-se
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = _method; //Valid values are "GET", "POST", "PUT" and "DELETE"
request.UserAgent =
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50215)";
request.ContentType = "application/json";
request.Timeout = 1000 * 60;
//Authorization is made up of UserName and Password in the format [UserName]:[Password]. In this case the identity token is the only value set and is the [UserName]
String _Authorization = "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(_UserName + ":" + _UserPassword));
request.Headers.Add(HttpRequestHeader.Authorization, _Authorization);
//Capture the basical header information. Using a proxy sniffer would be prefered however this helps to capture most information.
string ContentLength = "";
if (request.ContentLength > 0)
ContentLength = "\r\nContent-Length: " + request.ContentLength;
string _HeaderInformation = _method + " " + request.Address.AbsolutePath + request.Address.Query +
"\r\n" + request.Headers.ToString().Trim() + "\r\nHost: " +
request.Address.Host + ContentLength + "\r\n\r\n";
if (_body.Length > 0)
{
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(_body);
writer.Close();
}
txtRequest.Text = _HeaderInformation + _body;
RTxtSummary.SelectionColor = Color.Blue;
RTxtSummary.AppendText("REQUEST : \r\n");
RTxtSummary.SelectionColor = Color.Black;
RTxtSummary.AppendText(_HeaderInformation + _body + "\r\n");
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception e)
{
if (_method != "DELETE")
throw (e);
}
using (Stream data = response.GetResponseStream())
{
try
{
string text = new StreamReader(data).ReadToEnd();
//Log out request and response as well as process last response for follow-on messages.
//Diaplay in modal the request information?
if (ChkShowRequestModal.Checked)
{
ModalInformation mI = new ModalInformation();
mI.CallingForm("**** REQUEST****\r\n" + _HeaderInformation + _body +
"\r\n\r\n**** RESPONSE ****\r\n" + text);
//mI.CallingForm(_method + " " + request.Address.AbsolutePath + "\r\n" + request.Headers + "Host: " + request.Address.Host + "\r\n" + request.ContentLength + request.Expect + _body);
mI.ShowDialog(this);
}
else
{
//Confirm processing of last transaction
if (!_blnResponseMessage && TransactionType.NotSet != _transactionType)
{
MessageBox.Show("Successfully processed " + _transactionType +
" transaction. For more information about request and response check the show modal checkbox");
_blnResponseMessage = true;
}
}
txtResponse.Text = text;
RTxtSummary.SelectionColor = Color.Blue;
RTxtSummary.AppendText("\r\nRESPONSE : \r\n");
RTxtSummary.SelectionColor = Color.Black;
RTxtSummary.AppendText(text + "\r\n");
if (_transactionType != TransactionType.NotSet)
_LastResponse = ProcessResponse_Json(text, _transactionType);
return text;
}
catch (Exception e)
{
throw e;
}
finally
{
data.Close();
}
}
}
catch (System.Net.WebException ex2)
{
//Lets get the webException returned in the response
using (Stream data2 = ex2.Response.GetResponseStream())
{
try
{
string text = new StreamReader(data2).ReadToEnd();
txtResponse.Text = text;
RTxtSummary.SelectionColor = Color.Blue;
RTxtSummary.AppendText("\r\nRESPONSE : \r\n");
RTxtSummary.SelectionColor = Color.Black;
RTxtSummary.AppendText(text + "\r\n");
return text;
}
catch (Exception e)
{
throw e;
}
finally
{
data2.Close();
}
}
}
catch (Exception e)
{
return e.Message;
}
}
public void checkTokenExpire()
{
if (DateTime.UtcNow.Subtract(_dtSessionToken).TotalMinutes > 25)
//Use 25 as the baseline for renewing session tokens
{
try
{
_SessionToken = "";
string strResponse = "";
if (ChkUseJsonInstead.Checked)
{
strResponse = CreateRequest_Json(_svcInfo + @"/token", "GET", "", _IdentityToken.Trim(), "",
TransactionType.NotSet);
_SessionToken = strResponse.Substring(1, strResponse.Length - 2);
}
else
{
strResponse = CreateRequest(_svcInfo + @"/token", "GET", "", _IdentityToken.Trim(), "",
TransactionType.NotSet);
XmlDocument doc = new XmlDocument();
doc.LoadXml(strResponse);
_SessionToken = doc.FirstChild.InnerText;
}
_dtSessionToken = DateTime.UtcNow;
//At this point enable all steps
cmdManageApplicationData.Enabled = true;
cmdRetrieveServiceInformation.Enabled = true;
cmdPerformMerchantProfileAction.Enabled = true;
chkStep1.Checked = true;
}
catch (System.Net.WebException ex2)
{
//Lets get the webException returned in the response
using (Stream data2 = ex2.Response.GetResponseStream())
{
try
{
string text = new StreamReader(data2).ReadToEnd();
MessageBox.Show(text);
}
catch (Exception e)
{
throw e;
}
finally
{
data2.Close();
}
}
throw;
}
catch (Exception ex)
{
MessageBox.Show("Unable to Refresh a new Token\r\nError Message : " + ex.Message, "SignOn Failed",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
throw;
}
}
}
private void cmdClearResponse_Click(object sender, EventArgs e)
{
txtResponse.Text = "";
}
private void cmdClearRequest_Click(object sender, EventArgs e)
{
txtRequest.Text = "";
}
private void cboServiceIds_SelectedIndexChanged(object sender, EventArgs e)
{
item item = (item)cboServiceIds.SelectedItem;
_ServiceId = item.Value;
_WorkflowId = _ServiceId;
//based on serviceId selected, populate the proper operation types supported
//XmlNodeList nodes = doc.SelectNodes("ServiceInformation/BankcardServices/BankcardService");
XmlNodeList nodes = currentServiceInformation.GetElementsByTagName("BankcardService");
CboProcessString.Items.Clear();
CboProcessString.Text = "";
foreach (XmlNode node in nodes)
{
if (node["ServiceId"].InnerXml == _WorkflowId)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(node.OuterXml);
XmlNodeList nodes2 = doc.GetElementsByTagName("Operations");
if (nodes2[0].HasChildNodes)
{
foreach (XmlNode n in nodes2[0])
{
if (n.InnerText == "true" | n.InnerText == "Supported")
{
CboProcessString.Items.Add(new item(n.Name, n.Name));
}
}
}
//CboProcessString.Items.Add(new item(node["ServiceId"].InnerText, node["ServiceId"].InnerText));
}
}
if (_WorkflowId.Length > 0)
GetMerchantProfiles();
}
private void cboAvailableProfiles_SelectedIndexChanged(object sender, EventArgs e)
{
item item = (item)cboAvailableProfiles.SelectedItem;
_MerchantProfileId = item.Value;
}
private void cboAvailableWorkflowId_SelectedIndexChanged(object sender, EventArgs e)
{
item item = (item) cboWorkflowIds.SelectedItem;
_WorkflowId = item.Value;
}
#region Service Information Processing
private void SignOnWithToken()
{
TxtServiceKeyValue.Text = RetrieveServiceKeyFromIdentityToken(TxtLoadIdentityToken.Text);
if (_IdentityToken == null)
{
MessageBox.Show("Identity token is missing from the text box to the right");
return;
}
if (CboPTLSVersion.Text.Length < 1)
{
MessageBox.Show("Please select a PTLS version");
return;
}
if (_IdentityToken.Length < 1)
{
MessageBox.Show("Identity token is missing from the text box to the right");
return;
}
//Expire the current session token
_dtSessionToken = new DateTime();
checkTokenExpire();
//DeleteMerchantProfileId("746055", "214DF00001");
}
private void GetApplicationData()
{
/*
*URL https://api.dev.nabcommerce.com/REST/2.0.18/SvcInfo/appProfile/{applicationProfileId}
* Action GET
*/
if (_ApplicationProfileId.Length < 1)
{
MessageBox.Show("An ApplicationProfileId is required before calling Get Application Data");
return;
}
if (ChkUseJsonInstead.Checked)
{
CreateRequest_Json(_svcInfo + @"/appProfile/" + _ApplicationProfileId, "GET", "", _SessionToken, "",
TransactionType.NotSet);
}
else
{
CreateRequest(_svcInfo + @"/appProfile/" + _ApplicationProfileId, "GET", "", _SessionToken, "",
TransactionType.NotSet);
}
}
private void SaveApplicationData()
{
/*
*URL https://api.dev.nabcommerce.com/REST/2.0.18/SvcInfo/appProfile
* Action PUT
*/
try
{
checkTokenExpire(); //Always verify that a valid token exists
if (ChkUseJsonInstead.Checked)
{
string strApplicationData = @"{"
+ "\"ApplicationAttended\":" + _industryTypeValues.ApplicationAttended + ","
+ "\"ApplicationLocation\":\"" + _industryTypeValues.ApplicationLocation + "\","
+ "\"ApplicationName\":\"TestApp\","
+ "\"HardwareType\":\"PC\","
+ "\"PINCapability\":\"" + _industryTypeValues.PINCapability + "\","
+ "\"PTLSSocketId\":\"" + _PTLSSocketId + "\","
+ "\"ReadCapability\":\"" + _industryTypeValues.ReadCapability + "\","
+ "\"SerialNumber\":208093707,"
+ "\"SoftwareVersion\":1,"
+ "\"SoftwareVersionDate\":\"2014-05-20T00:00:00\","
//+ "\"DeviceSerialNumber\":\"TestApp\","
+ "\"EncryptionType\":\"MagneSafeV4V5Compatible\""//<!-- [Magensa : Valid Values 'IPADV1Compatible', 'MagneSafeV4V5Compatible', 'NotSet'] -->
+ "}"
;
string strResponse = CreateRequest_Json(_svcInfo + @"/appProfile", "PUT", strApplicationData, _SessionToken,
"", TransactionType.NotSet);
//ToDo: Temporary way to get the applciationProfileId
_ApplicationProfileId = strResponse.Substring(strResponse.IndexOf("appProfile") + 11, strResponse.LastIndexOf("\"") - (strResponse.IndexOf("appProfile") + 11));
}
else
{
string strApplicationData = @"<ApplicationData xmlns:i='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://schemas.ipcommerce.com/CWS/v2.0/ServiceInformation'>"
+ @"<ApplicationAttended>" + _industryTypeValues.ApplicationAttended + "</ApplicationAttended>"
+ @"<ApplicationLocation>" + _industryTypeValues.ApplicationLocation + "</ApplicationLocation>"
+ @"<ApplicationName>TestApp</ApplicationName>"
+ @"<DeveloperId>123</DeveloperId>"
+ @"<HardwareType>PC</HardwareType>"
+ @"<PINCapability>" + _industryTypeValues.PINCapability + "</PINCapability>"
+ @"<PTLSSocketId>" + _PTLSSocketId + "</PTLSSocketId>"
+ @"<ReadCapability>" + _industryTypeValues.ReadCapability + "</ReadCapability>"
+ @"<SerialNumber>208093707</SerialNumber>"
+ @"<SoftwareVersion>1.0</SoftwareVersion>"
+ @"<SoftwareVersionDate>2012-05-15T00:00:00</SoftwareVersionDate>"
+ @"<VendorId></VendorId>"
+ @"<EncryptionType>MagneSafeV4V5Compatible</EncryptionType>"//<!-- [Magensa : Valid Values 'IPADV1Compatible', 'MagneSafeV4V5Compatible', 'NotSet'] -->
//+ @"<DeviceSerialNumber>123</DeviceSerialNumber>"
+ @"</ApplicationData> "
;
string strResponse = CreateRequest(_svcInfo + @"/appProfile", "PUT", strApplicationData, _SessionToken,
"", TransactionType.NotSet);
XmlDocument doc = new XmlDocument();
doc.LoadXml(strResponse);
XPathNavigator xnav = doc.CreateNavigator();
//http://shaunedonohue.blogspot.com/2007/03/selectsinglenode-with-default-namespace.html
XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable);
nsm.AddNamespace("Nsm", "http://schemas.ipcommerce.com/CWS/v2.0/ServiceInformation/Rest");
XPathNavigator node = xnav.SelectSingleNode(@"//Nsm:id", nsm);
if (node == null)
{
MessageBox.Show("Application Profile could not be retrieved");
return;
}
_ApplicationProfileId = node.Value;
}
chkStep2.Checked = true;
txtApplicationProfileId.Text = _ApplicationProfileId;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
private void DeleteApplicationData()
{
/*URL https://api.dev.nabcommerce.com/REST/2.0.18/SvcInfo/appProfile/{applicationProfileId}
* Action DELETE
*/
checkTokenExpire(); //Always verify that a valid token exists
if (_ApplicationProfileId.Length < 1)
{
MessageBox.Show("An ApplicationProfileId is required before deleting application data");
return;
}
if (ChkUseJsonInstead.Checked)
{
CreateRequest_Json(_svcInfo + @"/appProfile/" + _ApplicationProfileId, "DELETE", "", _SessionToken, "",
TransactionType.NotSet);
}
else
{
CreateRequest(_svcInfo + @"/appProfile/" + _ApplicationProfileId, "DELETE", "", _SessionToken, "",
TransactionType.NotSet);
}
}
private void cmdRetrieveServiceInformation_Click(object sender, EventArgs e)
{
GetServiceInformation();
}
private void GetServiceInformation()
{
try
{
checkTokenExpire(); //Always verify that a valid token exists
//ToDo: Need to find a way to parse Json so that the XML approach doesn't have to be used to populate dropdowns
#region TEMPORARY APPROACH
//Reset the dropdown
cboServiceIds.Items.Clear(); //Reset The Services Dropdown
cboServiceIds.Text = "";
cboAvailableProfiles.Items.Clear(); //Reset The Services Dropdown
cboAvailableProfiles.Text = "";
cboWorkflowIds.Items.Clear();
cboWorkflowIds.Text = "";
cboMerchantProfileAction.SelectedIndex = 0;
string strResponse = CreateRequest(_svcInfo + @"/serviceInformation", "GET", "", _SessionToken, "", TransactionType.NotSet);
currentServiceInformation.LoadXml(strResponse);
//XmlNodeList nodes = doc.SelectNodes("ServiceInformation/BankcardServices/BankcardService");
XmlNodeList nodes = currentServiceInformation.GetElementsByTagName("BankcardService");
foreach (XmlNode node in nodes)
{
cboServiceIds.Items.Add(new item("[" + node["ServiceId"].InnerText + "] " + node["ServiceName"].InnerXml, node["ServiceId"].InnerText));
}
//Pull all WorkflowId's
//_AvailableWorkflowIds
XmlNodeList nodesWorkflow = currentServiceInformation.GetElementsByTagName("Workflow");
_AvailableWorkflowIds = "";
foreach (XmlNode node in nodesWorkflow)
{//[A007400011] ReD TEST HOST - Vantiv - D806000001
cboWorkflowIds.Items.Add(new item("[" + node["WorkflowId"].InnerText + "] " + node["Name"].InnerText + " - " + node["ServiceId"].InnerText, node["WorkflowId"].InnerText));
_AvailableWorkflowIds += "[" + node["WorkflowId"].InnerText + "] " + node["Name"].InnerText + " - " + node["ServiceId"].InnerText + "\r\n";
}
#endregion TEMPORARY APPROACH
if (ChkUseJsonInstead.Checked)
{
CreateRequest_Json(_svcInfo + @"/serviceInformation", "GET", "", _SessionToken, "", TransactionType.NotSet);
}
chkStep3.Checked = true;
}
catch (System.Net.WebException ex2)
{
//Lets get the webException returned in the response
using (Stream data2 = ex2.Response.GetResponseStream())
{
try
{
string text = new StreamReader(data2).ReadToEnd();
MessageBox.Show(text);
}
catch (Exception e)
{
throw e;
}
finally
{
data2.Close();
}
}
}
catch (Exception e)
{
txtResponse.Text = e.Message;
RTxtSummary.SelectionColor = Color.Red;
RTxtSummary.AppendText("ERROR : \r\n" + e.Message + "\r\n");
}
}
private void cmdPerformMerchantProfileAction_Click(object sender, EventArgs e)
{
item item = (item)cboMerchantProfileAction.SelectedItem;
if (item.Value == "0")
{
MessageBox.Show("Please select an action");
return;
}
if (item.Value == "1")
{
//Get Merchant Data
if (_MerchantProfileId.Length < 1)
{
MessageBox.Show("Please select a Merchant Profile");
return;
}
GetMerchantProfiles();
return;
}
if (item.Value == "2")
{
//Get Merchant Data
GetMerchantProfile();
return;
}
if (item.Value == "3")
{
//Save Merchant Data
if (cboAvailableProfiles.Text.Length < 1)
{
MessageBox.Show("Please type into the dropdown a MerchantProfileId");
return;
}
if (_WorkflowId.Length < 1)
{
MessageBox.Show("Plesae select a valid ServiceId");
return;
}
_MerchantProfileId = cboAvailableProfiles.Text;
SaveMerchantProfile();
//Reset the dropdown
GetServiceInformation();
return;
}
if (item.Value == "4")
{
//Delete Merchant Data
if (_MerchantProfileId.Length < 1)
{
MessageBox.Show("Please select a Merchant Profile");
return;
}
if (_WorkflowId.Length < 1)
{
MessageBox.Show("Please select a ServiceId");
return;
}
DeleteMerchantProfileId(_MerchantProfileId, _WorkflowId);
//Reset the dropdown
GetServiceInformation();
return;
}
}
private void GetMerchantProfile()
{
/*
*URL https://api.dev.nabcommerce.com/REST/2.0.18/SvcInfo/merchProfile/{merchantProfileId}?serviceId={serviceId}
* Action GET
*/
try
{
checkTokenExpire(); //Always verify that a valid token exists
if (_MerchantProfileId.Length < 1)
{
MessageBox.Show("A MerchantProfileId is required before calling Get Merchant Profile");
return;
}
if (ChkUseJsonInstead.Checked)
{
CreateRequest_Json(_svcInfo + @"/merchProfile/" + _MerchantProfileId + "?serviceId=" + _WorkflowId, "GET", "",
_SessionToken, "", TransactionType.NotSet);
}
else
{
CreateRequest(_svcInfo + @"/merchProfile/" + _MerchantProfileId + "?serviceId=" + _WorkflowId, "GET", "",
_SessionToken, "", TransactionType.NotSet);
}
}
catch (System.Net.WebException ex2)
{
//Lets get the webException returned in the response
using (Stream data2 = ex2.Response.GetResponseStream())
{
try
{
string text = new StreamReader(data2).ReadToEnd();
MessageBox.Show(text);
}
catch (Exception e)
{
throw e;
}
finally
{
data2.Close();
}
}
}
catch (Exception e)
{
txtResponse.Text = e.Message;
RTxtSummary.SelectionColor = Color.Red;
RTxtSummary.AppendText("ERROR : \r\n" + e.Message + "\r\n");
}
}
private void GetMerchantProfiles()
{
/*
*URL To return all Merchant Profiles by serviceId:
https://api.dev.nabcommerce.com/REST/2.0.18/SvcInfo/merchProfile?serviceId={serviceId}
To return all Merchant Profiles by merchantProfileId (across multiple services):
https://api.dev.nabcommerce.com/REST/2.0.18/SvcInfo/merchProfile?merchantProfileId={merchantProfileId}
Action GET
*/
try
{
checkTokenExpire(); //Always verify that a valid token exists
//Reset the dropdown
cboAvailableProfiles.Items.Clear(); //Reset The Services Dropdown
cboAvailableProfiles.Text = "";
if (_WorkflowId.Length < 1)
{
MessageBox.Show("A ServiceId is required before calling GetMerchantProfiles");
return;
}
string strResponse = "";
//else - Moved up from the if statement below
//ToDo : until I we can figure out how to convert JSon to an Object, using the older XML approach to populate the dropdowns.
//{
strResponse = CreateRequest(_svcInfo + @"/merchProfile?serviceId=" + _WorkflowId, "GET", "", _SessionToken, "", TransactionType.NotSet);
XmlDocument doc = new XmlDocument();
doc.LoadXml(strResponse);
//XmlNodeList nodes = doc.SelectNodes("ServiceInformation/BankcardServices/BankcardService");
XmlNodeList nodes = doc.GetElementsByTagName("MerchantProfileId");
foreach (XmlNode node in nodes)
{
cboAvailableProfiles.Items.Add(new item(node["id"].InnerXml, node["id"].InnerText));
}
//}
if (ChkUseJsonInstead.Checked)
{
CreateRequest_Json(_svcInfo + @"/merchProfile?serviceId=" + _WorkflowId, "GET", "", _SessionToken, "", TransactionType.NotSet);
}
chkStep3.Checked = true;