-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
PayloadGenerator.cs
3154 lines (2791 loc) · 148 KB
/
PayloadGenerator.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.Linq;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
#if NETSTANDARD1_3
using System.Reflection;
#endif
namespace QRCoder
{
public static class PayloadGenerator
{
public abstract class Payload
{
public virtual int Version { get { return -1; } }
public virtual QRCodeGenerator.ECCLevel EccLevel { get { return QRCodeGenerator.ECCLevel.M; } }
public virtual QRCodeGenerator.EciMode EciMode { get { return QRCodeGenerator.EciMode.Default; } }
public abstract override string ToString();
}
public class WiFi : Payload
{
private readonly string ssid, password, authenticationMode;
private readonly bool isHiddenSsid;
/// <summary>
/// Generates a WiFi payload. Scanned by a QR Code scanner app, the device will connect to the WiFi.
/// </summary>
/// <param name="ssid">SSID of the WiFi network</param>
/// <param name="password">Password of the WiFi network</param>
/// <param name="authenticationMode">Authentification mode (WEP, WPA, WPA2)</param>
/// <param name="isHiddenSSID">Set flag, if the WiFi network hides its SSID</param>
/// <param name="escapeHexStrings">Set flag, if ssid/password is delivered as HEX string. Note: May not be supported on iOS devices.</param>
public WiFi(string ssid, string password, Authentication authenticationMode, bool isHiddenSSID = false, bool escapeHexStrings = true)
{
this.ssid = EscapeInput(ssid);
this.ssid = escapeHexStrings && isHexStyle(this.ssid) ? "\"" + this.ssid + "\"" : this.ssid;
this.password = EscapeInput(password);
this.password = escapeHexStrings && isHexStyle(this.password) ? "\"" + this.password + "\"" : this.password;
this.authenticationMode = authenticationMode.ToString();
this.isHiddenSsid = isHiddenSSID;
}
public override string ToString()
{
return
$"WIFI:T:{this.authenticationMode};S:{this.ssid};P:{this.password};{(this.isHiddenSsid ? "H:true" : string.Empty)};";
}
public enum Authentication
{
WEP,
WPA,
nopass,
WPA2
}
}
public class Mail : Payload
{
private readonly string mailReceiver, subject, message;
private readonly MailEncoding encoding;
/// <summary>
/// Creates an email payload with subject and message/text
/// </summary>
/// <param name="mailReceiver">Receiver's email address</param>
/// <param name="subject">Subject line of the email</param>
/// <param name="message">Message content of the email</param>
/// <param name="encoding">Payload encoding type. Choose dependent on your QR Code scanner app.</param>
public Mail(string mailReceiver = null, string subject = null, string message = null, MailEncoding encoding = MailEncoding.MAILTO)
{
this.mailReceiver = mailReceiver;
this.subject = subject;
this.message = message;
this.encoding = encoding;
}
public override string ToString()
{
var returnVal = string.Empty;
switch (this.encoding)
{
case MailEncoding.MAILTO:
var parts = new List<string>();
if (!string.IsNullOrEmpty(this.subject))
parts.Add("subject=" + Uri.EscapeDataString(this.subject));
if (!string.IsNullOrEmpty(this.message))
parts.Add("body=" + Uri.EscapeDataString(this.message));
var queryString = parts.Any() ? $"?{string.Join("&", parts.ToArray())}" : "";
returnVal = $"mailto:{this.mailReceiver}{queryString}";
break;
case MailEncoding.MATMSG:
returnVal = $"MATMSG:TO:{this.mailReceiver};SUB:{EscapeInput(this.subject)};BODY:{EscapeInput(this.message)};;";
break;
case MailEncoding.SMTP:
returnVal = $"SMTP:{this.mailReceiver}:{EscapeInput(this.subject, true)}:{EscapeInput(this.message, true)}";
break;
}
return returnVal;
}
public enum MailEncoding
{
MAILTO,
MATMSG,
SMTP
}
}
public class SMS : Payload
{
private readonly string number, subject;
private readonly SMSEncoding encoding;
/// <summary>
/// Creates a SMS payload without text
/// </summary>
/// <param name="number">Receiver phone number</param>
/// <param name="encoding">Encoding type</param>
public SMS(string number, SMSEncoding encoding = SMSEncoding.SMS)
{
this.number = number;
this.subject = string.Empty;
this.encoding = encoding;
}
/// <summary>
/// Creates a SMS payload with text (subject)
/// </summary>
/// <param name="number">Receiver phone number</param>
/// <param name="subject">Text of the SMS</param>
/// <param name="encoding">Encoding type</param>
public SMS(string number, string subject, SMSEncoding encoding = SMSEncoding.SMS)
{
this.number = number;
this.subject = subject;
this.encoding = encoding;
}
public override string ToString()
{
var returnVal = string.Empty;
switch (this.encoding)
{
case SMSEncoding.SMS:
var queryString = string.Empty;
if (!string.IsNullOrEmpty(this.subject))
queryString = $"?body={Uri.EscapeDataString(this.subject)}";
returnVal = $"sms:{this.number}{queryString}";
break;
case SMSEncoding.SMS_iOS:
var queryStringiOS = string.Empty;
if (!string.IsNullOrEmpty(this.subject))
queryStringiOS = $";body={Uri.EscapeDataString(this.subject)}";
returnVal = $"sms:{this.number}{queryStringiOS}";
break;
case SMSEncoding.SMSTO:
returnVal = $"SMSTO:{this.number}:{this.subject}";
break;
}
return returnVal;
}
public enum SMSEncoding
{
SMS,
SMSTO,
SMS_iOS
}
}
public class MMS : Payload
{
private readonly string number, subject;
private readonly MMSEncoding encoding;
/// <summary>
/// Creates a MMS payload without text
/// </summary>
/// <param name="number">Receiver phone number</param>
/// <param name="encoding">Encoding type</param>
public MMS(string number, MMSEncoding encoding = MMSEncoding.MMS)
{
this.number = number;
this.subject = string.Empty;
this.encoding = encoding;
}
/// <summary>
/// Creates a MMS payload with text (subject)
/// </summary>
/// <param name="number">Receiver phone number</param>
/// <param name="subject">Text of the MMS</param>
/// <param name="encoding">Encoding type</param>
public MMS(string number, string subject, MMSEncoding encoding = MMSEncoding.MMS)
{
this.number = number;
this.subject = subject;
this.encoding = encoding;
}
public override string ToString()
{
var returnVal = string.Empty;
switch (this.encoding)
{
case MMSEncoding.MMSTO:
var queryStringMmsTo = string.Empty;
if (!string.IsNullOrEmpty(this.subject))
queryStringMmsTo = $"?subject={Uri.EscapeDataString(this.subject)}";
returnVal = $"mmsto:{this.number}{queryStringMmsTo}";
break;
case MMSEncoding.MMS:
var queryStringMms = string.Empty;
if (!string.IsNullOrEmpty(this.subject))
queryStringMms = $"?body={Uri.EscapeDataString(this.subject)}";
returnVal = $"mms:{this.number}{queryStringMms}";
break;
}
return returnVal;
}
public enum MMSEncoding
{
MMS,
MMSTO
}
}
public class Geolocation : Payload
{
private readonly string latitude, longitude;
private readonly GeolocationEncoding encoding;
/// <summary>
/// Generates a geo location payload. Supports raw location (GEO encoding) or Google Maps link (GoogleMaps encoding)
/// </summary>
/// <param name="latitude">Latitude with . as splitter</param>
/// <param name="longitude">Longitude with . as splitter</param>
/// <param name="encoding">Encoding type - GEO or GoogleMaps</param>
public Geolocation(string latitude, string longitude, GeolocationEncoding encoding = GeolocationEncoding.GEO)
{
this.latitude = latitude.Replace(",",".");
this.longitude = longitude.Replace(",", ".");
this.encoding = encoding;
}
public override string ToString()
{
switch (this.encoding)
{
case GeolocationEncoding.GEO:
return $"geo:{this.latitude},{this.longitude}";
case GeolocationEncoding.GoogleMaps:
return $"http://maps.google.com/maps?q={this.latitude},{this.longitude}";
default:
return "geo:";
}
}
public enum GeolocationEncoding
{
GEO,
GoogleMaps
}
}
public class PhoneNumber : Payload
{
private readonly string number;
/// <summary>
/// Generates a phone call payload
/// </summary>
/// <param name="number">Phonenumber of the receiver</param>
public PhoneNumber(string number)
{
this.number = number;
}
public override string ToString()
{
return $"tel:{this.number}";
}
}
public class SkypeCall : Payload
{
private readonly string skypeUsername;
/// <summary>
/// Generates a Skype call payload
/// </summary>
/// <param name="skypeUsername">Skype username which will be called</param>
public SkypeCall(string skypeUsername)
{
this.skypeUsername = skypeUsername;
}
public override string ToString()
{
return $"skype:{this.skypeUsername}?call";
}
}
public class Url : Payload
{
private readonly string url;
/// <summary>
/// Generates a link. If the protocol is not specified, the http protocol will be added.
/// </summary>
/// <param name="url">Link url target</param>
public Url(string url)
{
this.url = url;
}
public override string ToString()
{
return (!this.url.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? "http://" + this.url : this.url);
}
}
public class WhatsAppMessage : Payload
{
private readonly string number, message;
/// <summary>
/// Let's you compose a WhatApp message and send it the receiver number.
/// </summary>
/// <param name="number">Receiver phone number where the <number> is a full phone number in international format.
/// Omit any zeroes, brackets, or dashes when adding the phone number in international format.
/// Use: 1XXXXXXXXXX | Don't use: +001-(XXX)XXXXXXX
/// </param>
/// <param name="message">The message</param>
public WhatsAppMessage(string number, string message)
{
this.number = number;
this.message = message;
}
/// <summary>
/// Let's you compose a WhatApp message. When scanned the user is asked to choose a contact who will receive the message.
/// </summary>
/// <param name="message">The message</param>
public WhatsAppMessage(string message)
{
this.number = string.Empty;
this.message = message;
}
public override string ToString()
{
var cleanedPhone = Regex.Replace(this.number, @"^[0+]+|[ ()-]", string.Empty);
return ($"https://wa.me/{cleanedPhone}?text={Uri.EscapeDataString(message)}");
}
}
public class Bookmark : Payload
{
private readonly string url, title;
/// <summary>
/// Generates a bookmark payload. Scanned by an QR Code reader, this one creates a browser bookmark.
/// </summary>
/// <param name="url">Url of the bookmark</param>
/// <param name="title">Title of the bookmark</param>
public Bookmark(string url, string title)
{
this.url = EscapeInput(url);
this.title = EscapeInput(title);
}
public override string ToString()
{
return $"MEBKM:TITLE:{this.title};URL:{this.url};;";
}
}
public class ContactData : Payload
{
private readonly string firstname;
private readonly string lastname;
private readonly string nickname;
private readonly string org;
private readonly string orgTitle;
private readonly string phone;
private readonly string mobilePhone;
private readonly string workPhone;
private readonly string email;
private readonly DateTime? birthday;
private readonly string website;
private readonly string street;
private readonly string houseNumber;
private readonly string city;
private readonly string zipCode;
private readonly string stateRegion;
private readonly string country;
private readonly string note;
private readonly ContactOutputType outputType;
private readonly AddressOrder addressOrder;
/// <summary>
/// Generates a vCard or meCard contact dataset
/// </summary>
/// <param name="outputType">Payload output type</param>
/// <param name="firstname">The firstname</param>
/// <param name="lastname">The lastname</param>
/// <param name="nickname">The displayname</param>
/// <param name="phone">Normal phone number</param>
/// <param name="mobilePhone">Mobile phone</param>
/// <param name="workPhone">Office phone number</param>
/// <param name="email">E-Mail address</param>
/// <param name="birthday">Birthday</param>
/// <param name="website">Website / Homepage</param>
/// <param name="street">Street</param>
/// <param name="houseNumber">Housenumber</param>
/// <param name="city">City</param>
/// <param name="stateRegion">State or Region</param>
/// <param name="zipCode">Zip code</param>
/// <param name="country">Country</param>
/// <param name="addressOrder">The address order format to use</param>
/// <param name="note">Memo text / notes</param>
/// <param name="org">Organisation/Company</param>
/// <param name="orgTitle">Organisation/Company Title</param>
public ContactData(ContactOutputType outputType, string firstname, string lastname, string nickname = null, string phone = null, string mobilePhone = null, string workPhone = null, string email = null, DateTime? birthday = null, string website = null, string street = null, string houseNumber = null, string city = null, string zipCode = null, string country = null, string note = null, string stateRegion = null, AddressOrder addressOrder = AddressOrder.Default, string org = null, string orgTitle = null)
{
this.firstname = firstname;
this.lastname = lastname;
this.nickname = nickname;
this.org = org;
this.orgTitle = orgTitle;
this.phone = phone;
this.mobilePhone = mobilePhone;
this.workPhone = workPhone;
this.email = email;
this.birthday = birthday;
this.website = website;
this.street = street;
this.houseNumber = houseNumber;
this.city = city;
this.stateRegion = stateRegion;
this.zipCode = zipCode;
this.country = country;
this.addressOrder = addressOrder;
this.note = note;
this.outputType = outputType;
}
public override string ToString()
{
string payload = string.Empty;
if (outputType == ContactOutputType.MeCard)
{
payload += "MECARD+\r\n";
if (!string.IsNullOrEmpty(firstname) && !string.IsNullOrEmpty(lastname))
payload += $"N:{lastname}, {firstname}\r\n";
else if (!string.IsNullOrEmpty(firstname) || !string.IsNullOrEmpty(lastname))
payload += $"N:{firstname}{lastname}\r\n";
if (!string.IsNullOrEmpty(org))
payload += $"ORG:{org}\r\n";
if (!string.IsNullOrEmpty(orgTitle))
payload += $"TITLE:{orgTitle}\r\n";
if (!string.IsNullOrEmpty(phone))
payload += $"TEL:{phone}\r\n";
if (!string.IsNullOrEmpty(mobilePhone))
payload += $"TEL:{mobilePhone}\r\n";
if (!string.IsNullOrEmpty(workPhone))
payload += $"TEL:{workPhone}\r\n";
if (!string.IsNullOrEmpty(email))
payload += $"EMAIL:{email}\r\n";
if (!string.IsNullOrEmpty(note))
payload += $"NOTE:{note}\r\n";
if (birthday != null)
payload += $"BDAY:{((DateTime)birthday).ToString("yyyyMMdd")}\r\n";
string addressString = string.Empty;
if(addressOrder == AddressOrder.Default)
{
addressString = $"ADR:,,{(!string.IsNullOrEmpty(street) ? street + " " : "")}{(!string.IsNullOrEmpty(houseNumber) ? houseNumber : "")},{(!string.IsNullOrEmpty(zipCode) ? zipCode : "")},{(!string.IsNullOrEmpty(city) ? city : "")},{(!string.IsNullOrEmpty(stateRegion) ? stateRegion : "")},{(!string.IsNullOrEmpty(country) ? country : "")}\r\n";
}
else
{
addressString = $"ADR:,,{(!string.IsNullOrEmpty(houseNumber) ? houseNumber + " " : "")}{(!string.IsNullOrEmpty(street) ? street : "")},{(!string.IsNullOrEmpty(city) ? city : "")},{(!string.IsNullOrEmpty(stateRegion) ? stateRegion : "")},{(!string.IsNullOrEmpty(zipCode) ? zipCode : "")},{(!string.IsNullOrEmpty(country) ? country : "")}\r\n";
}
payload += addressString;
if (!string.IsNullOrEmpty(website))
payload += $"URL:{website}\r\n";
if (!string.IsNullOrEmpty(nickname))
payload += $"NICKNAME:{nickname}\r\n";
payload = payload.Trim(new char[] { '\r', '\n' });
}
else
{
var version = outputType.ToString().Substring(5);
if (version.Length > 1)
version = version.Insert(1, ".");
else
version += ".0";
payload += "BEGIN:VCARD\r\n";
payload += $"VERSION:{version}\r\n";
payload += $"N:{(!string.IsNullOrEmpty(lastname) ? lastname : "")};{(!string.IsNullOrEmpty(firstname) ? firstname : "")};;;\r\n";
payload += $"FN:{(!string.IsNullOrEmpty(firstname) ? firstname + " " : "")}{(!string.IsNullOrEmpty(lastname) ? lastname : "")}\r\n";
if (!string.IsNullOrEmpty(org))
{
payload += $"ORG:" + org + "\r\n";
}
if (!string.IsNullOrEmpty(orgTitle))
{
payload += $"TITLE:" + orgTitle + "\r\n";
}
if (!string.IsNullOrEmpty(phone))
{
payload += $"TEL;";
if (outputType == ContactOutputType.VCard21)
payload += $"HOME;VOICE:{phone}";
else if (outputType == ContactOutputType.VCard3)
payload += $"TYPE=HOME,VOICE:{phone}";
else
payload += $"TYPE=home,voice;VALUE=uri:tel:{phone}";
payload += "\r\n";
}
if (!string.IsNullOrEmpty(mobilePhone))
{
payload += $"TEL;";
if (outputType == ContactOutputType.VCard21)
payload += $"HOME;CELL:{mobilePhone}";
else if (outputType == ContactOutputType.VCard3)
payload += $"TYPE=HOME,CELL:{mobilePhone}";
else
payload += $"TYPE=home,cell;VALUE=uri:tel:{mobilePhone}";
payload += "\r\n";
}
if (!string.IsNullOrEmpty(workPhone))
{
payload += $"TEL;";
if (outputType == ContactOutputType.VCard21)
payload += $"WORK;VOICE:{workPhone}";
else if (outputType == ContactOutputType.VCard3)
payload += $"TYPE=WORK,VOICE:{workPhone}";
else
payload += $"TYPE=work,voice;VALUE=uri:tel:{workPhone}";
payload += "\r\n";
}
payload += "ADR;";
if (outputType == ContactOutputType.VCard21)
payload += "HOME;PREF:";
else if (outputType == ContactOutputType.VCard3)
payload += "TYPE=HOME,PREF:";
else
payload += "TYPE=home,pref:";
string addressString = string.Empty;
if(addressOrder == AddressOrder.Default)
{
addressString = $";;{(!string.IsNullOrEmpty(street) ? street + " " : "")}{(!string.IsNullOrEmpty(houseNumber) ? houseNumber : "")};{(!string.IsNullOrEmpty(zipCode) ? zipCode : "")};{(!string.IsNullOrEmpty(city) ? city : "")};{(!string.IsNullOrEmpty(stateRegion) ? stateRegion : "")};{(!string.IsNullOrEmpty(country) ? country : "")}\r\n";
}
else
{
addressString = $";;{(!string.IsNullOrEmpty(houseNumber) ? houseNumber + " " : "")}{(!string.IsNullOrEmpty(street) ? street : "")};{(!string.IsNullOrEmpty(city) ? city : "")};{(!string.IsNullOrEmpty(stateRegion) ? stateRegion : "")};{(!string.IsNullOrEmpty(zipCode) ? zipCode : "")};{(!string.IsNullOrEmpty(country) ? country : "")}\r\n";
}
payload += addressString;
if (birthday != null)
payload += $"BDAY:{((DateTime)birthday).ToString("yyyyMMdd")}\r\n";
if (!string.IsNullOrEmpty(website))
payload += $"URL:{website}\r\n";
if (!string.IsNullOrEmpty(email))
payload += $"EMAIL:{email}\r\n";
if (!string.IsNullOrEmpty(note))
payload += $"NOTE:{note}\r\n";
if (outputType != ContactOutputType.VCard21 && !string.IsNullOrEmpty(nickname))
payload += $"NICKNAME:{nickname}\r\n";
payload += "END:VCARD";
}
return payload;
}
/// <summary>
/// Possible output types. Either vCard 2.1, vCard 3.0, vCard 4.0 or MeCard.
/// </summary>
public enum ContactOutputType
{
MeCard,
VCard21,
VCard3,
VCard4
}
/// <summary>
/// define the address format
/// Default: European format, ([Street] [House Number] and [Postal Code] [City]
/// Reversed: North American and others format ([House Number] [Street] and [City] [Postal Code])
/// </summary>
public enum AddressOrder
{
Default,
Reversed
}
}
public class BitcoinLikeCryptoCurrencyAddress : Payload
{
private readonly BitcoinLikeCryptoCurrencyType currencyType;
private readonly string address, label, message;
private readonly double? amount;
/// <summary>
/// Generates a Bitcoin like cryptocurrency payment payload. QR Codes with this payload can open a payment app.
/// </summary>
/// <param name="currencyName">Bitcoin like cryptocurrency address of the payment receiver</param>
/// <param name="address">Bitcoin like cryptocurrency address of the payment receiver</param>
/// <param name="amount">Amount of coins to transfer</param>
/// <param name="label">Reference label</param>
/// <param name="message">Referece text aka message</param>
public BitcoinLikeCryptoCurrencyAddress(BitcoinLikeCryptoCurrencyType currencyType, string address, double? amount, string label = null, string message = null)
{
this.currencyType = currencyType;
this.address = address;
if (!string.IsNullOrEmpty(label))
{
this.label = Uri.EscapeDataString(label);
}
if (!string.IsNullOrEmpty(message))
{
this.message = Uri.EscapeDataString(message);
}
this.amount = amount;
}
public override string ToString()
{
string query = null;
var queryValues = new KeyValuePair<string,string>[]{
new KeyValuePair<string, string>(nameof(label), label),
new KeyValuePair<string, string>(nameof(message), message),
new KeyValuePair<string, string>(nameof(amount), amount.HasValue ? amount.Value.ToString("#.########", CultureInfo.InvariantCulture) : null)
};
if (queryValues.Any(keyPair => !string.IsNullOrEmpty(keyPair.Value)))
{
query = "?" + string.Join("&", queryValues
.Where(keyPair => !string.IsNullOrEmpty(keyPair.Value))
.Select(keyPair => $"{keyPair.Key}={keyPair.Value}")
.ToArray());
}
return $"{Enum.GetName(typeof(BitcoinLikeCryptoCurrencyType), currencyType).ToLower()}:{address}{query}";
}
public enum BitcoinLikeCryptoCurrencyType
{
Bitcoin,
BitcoinCash,
Litecoin
}
}
public class BitcoinAddress : BitcoinLikeCryptoCurrencyAddress
{
public BitcoinAddress(string address, double? amount, string label = null, string message = null)
: base(BitcoinLikeCryptoCurrencyType.Bitcoin, address, amount, label, message) { }
}
public class BitcoinCashAddress : BitcoinLikeCryptoCurrencyAddress
{
public BitcoinCashAddress(string address, double? amount, string label = null, string message = null)
: base(BitcoinLikeCryptoCurrencyType.BitcoinCash, address, amount, label, message) { }
}
public class LitecoinAddress : BitcoinLikeCryptoCurrencyAddress
{
public LitecoinAddress(string address, double? amount, string label = null, string message = null)
: base(BitcoinLikeCryptoCurrencyType.Litecoin, address, amount, label, message) { }
}
public class SwissQrCode : Payload
{
//Keep in mind, that the ECC level has to be set to "M" when generating a SwissQrCode!
//SwissQrCode specification:
// - (de) https://www.paymentstandards.ch/dam/downloads/ig-qr-bill-de.pdf
// - (en) https://www.paymentstandards.ch/dam/downloads/ig-qr-bill-en.pdf
//Changes between version 1.0 and 2.0: https://www.paymentstandards.ch/dam/downloads/change-documentation-qrr-de.pdf
private readonly string br = "\r\n";
private readonly string alternativeProcedure1, alternativeProcedure2;
private readonly Iban iban;
private readonly decimal? amount;
private readonly Contact creditor, ultimateCreditor, debitor;
private readonly Currency currency;
private readonly DateTime? requestedDateOfPayment;
private readonly Reference reference;
private readonly AdditionalInformation additionalInformation;
/// <summary>
/// Generates the payload for a SwissQrCode v2.0. (Don't forget to use ECC-Level=M, EncodingMode=UTF-8 and to set the Swiss flag icon to the final QR code.)
/// </summary>
/// <param name="iban">IBAN object</param>
/// <param name="currency">Currency (either EUR or CHF)</param>
/// <param name="creditor">Creditor (payee) information</param>
/// <param name="reference">Reference information</param>
/// <param name="debitor">Debitor (payer) information</param>
/// <param name="amount">Amount</param>
/// <param name="requestedDateOfPayment">Requested date of debitor's payment</param>
/// <param name="ultimateCreditor">Ultimate creditor information (use only in consultation with your bank - for future use only!)</param>
/// <param name="alternativeProcedure1">Optional command for alternative processing mode - line 1</param>
/// <param name="alternativeProcedure2">Optional command for alternative processing mode - line 2</param>
public SwissQrCode(Iban iban, Currency currency, Contact creditor, Reference reference, AdditionalInformation additionalInformation = null, Contact debitor = null, decimal? amount = null, DateTime? requestedDateOfPayment = null, Contact ultimateCreditor = null, string alternativeProcedure1 = null, string alternativeProcedure2 = null)
{
this.iban = iban;
this.creditor = creditor;
this.ultimateCreditor = ultimateCreditor;
this.additionalInformation = additionalInformation != null ? additionalInformation : new AdditionalInformation();
if (amount != null && amount.ToString().Length > 12)
throw new SwissQrCodeException("Amount (including decimals) must be shorter than 13 places.");
this.amount = amount;
this.currency = currency;
this.requestedDateOfPayment = requestedDateOfPayment;
this.debitor = debitor;
if (iban.IsQrIban && reference.RefType != Reference.ReferenceType.QRR)
throw new SwissQrCodeException("If QR-IBAN is used, you have to choose \"QRR\" as reference type!");
if (!iban.IsQrIban && reference.RefType == Reference.ReferenceType.QRR)
throw new SwissQrCodeException("If non QR-IBAN is used, you have to choose either \"SCOR\" or \"NON\" as reference type!");
this.reference = reference;
if (alternativeProcedure1 != null && alternativeProcedure1.Length > 100)
throw new SwissQrCodeException("Alternative procedure information block 1 must be shorter than 101 chars.");
this.alternativeProcedure1 = alternativeProcedure1;
if (alternativeProcedure2 != null && alternativeProcedure2.Length > 100)
throw new SwissQrCodeException("Alternative procedure information block 2 must be shorter than 101 chars.");
this.alternativeProcedure2 = alternativeProcedure2;
}
public class AdditionalInformation
{
private readonly string unstructuredMessage, billInformation, trailer;
/// <summary>
/// Creates an additional information object. Both parameters are optional and must be shorter than 141 chars in combination.
/// </summary>
/// <param name="unstructuredMessage">Unstructured text message</param>
/// <param name="billInformation">Bill information</param>
public AdditionalInformation(string unstructuredMessage = null, string billInformation = null)
{
if (((unstructuredMessage != null ? unstructuredMessage.Length : 0) + (billInformation != null ? billInformation.Length : 0)) > 140)
throw new SwissQrCodeAdditionalInformationException("Unstructured message and bill information must be shorter than 141 chars in total/combined.");
this.unstructuredMessage = unstructuredMessage;
this.billInformation = billInformation;
this.trailer = "EPD";
}
public string UnstructureMessage
{
get { return !string.IsNullOrEmpty(unstructuredMessage) ? unstructuredMessage.Replace("\n", "") : null; }
}
public string BillInformation
{
get { return !string.IsNullOrEmpty(billInformation) ? billInformation.Replace("\n", "") : null; }
}
public string Trailer
{
get { return trailer; }
}
public class SwissQrCodeAdditionalInformationException : Exception
{
public SwissQrCodeAdditionalInformationException()
{
}
public SwissQrCodeAdditionalInformationException(string message)
: base(message)
{
}
public SwissQrCodeAdditionalInformationException(string message, Exception inner)
: base(message, inner)
{
}
}
}
public class Reference
{
private readonly ReferenceType referenceType;
private readonly string reference;
private readonly ReferenceTextType? referenceTextType;
/// <summary>
/// Creates a reference object which must be passed to the SwissQrCode instance
/// </summary>
/// <param name="referenceType">Type of the reference (QRR, SCOR or NON)</param>
/// <param name="reference">Reference text</param>
/// <param name="referenceTextType">Type of the reference text (QR-reference or Creditor Reference)</param>
public Reference(ReferenceType referenceType, string reference = null, ReferenceTextType? referenceTextType = null)
{
this.referenceType = referenceType;
this.referenceTextType = referenceTextType;
if (referenceType == ReferenceType.NON && reference != null)
throw new SwissQrCodeReferenceException("Reference is only allowed when referenceType not equals \"NON\"");
if (referenceType != ReferenceType.NON && reference != null && referenceTextType == null)
throw new SwissQrCodeReferenceException("You have to set an ReferenceTextType when using the reference text.");
if (referenceTextType == ReferenceTextType.QrReference && reference != null && (reference.Length > 27))
throw new SwissQrCodeReferenceException("QR-references have to be shorter than 28 chars.");
if (referenceTextType == ReferenceTextType.QrReference && reference != null && !Regex.IsMatch(reference, @"^[0-9]+$"))
throw new SwissQrCodeReferenceException("QR-reference must exist out of digits only.");
if (referenceTextType == ReferenceTextType.QrReference && reference != null && !ChecksumMod10(reference))
throw new SwissQrCodeReferenceException("QR-references is invalid. Checksum error.");
if (referenceTextType == ReferenceTextType.CreditorReferenceIso11649 && reference != null && (reference.Length > 25))
throw new SwissQrCodeReferenceException("Creditor references (ISO 11649) have to be shorter than 26 chars.");
this.reference = reference;
}
public ReferenceType RefType {
get { return referenceType; }
}
public string ReferenceText
{
get { return !string.IsNullOrEmpty(reference) ? reference.Replace("\n", "") : null; }
}
/// <summary>
/// Reference type. When using a QR-IBAN you have to use either "QRR" or "SCOR"
/// </summary>
public enum ReferenceType
{
QRR,
SCOR,
NON
}
public enum ReferenceTextType
{
QrReference,
CreditorReferenceIso11649
}
public class SwissQrCodeReferenceException : Exception
{
public SwissQrCodeReferenceException()
{
}
public SwissQrCodeReferenceException(string message)
: base(message)
{
}
public SwissQrCodeReferenceException(string message, Exception inner)
: base(message, inner)
{
}
}
}
public class Iban
{
private string iban;
private IbanType ibanType;
/// <summary>
/// IBAN object with type information
/// </summary>
/// <param name="iban">IBAN</param>
/// <param name="ibanType">Type of IBAN (normal or QR-IBAN)</param>
public Iban(string iban, IbanType ibanType)
{
if (ibanType == IbanType.Iban && !IsValidIban(iban))
throw new SwissQrCodeIbanException("The IBAN entered isn't valid.");
if (ibanType == IbanType.QrIban && !IsValidQRIban(iban))
throw new SwissQrCodeIbanException("The QR-IBAN entered isn't valid.");
if (!iban.StartsWith("CH") && !iban.StartsWith("LI"))
throw new SwissQrCodeIbanException("The IBAN must start with \"CH\" or \"LI\".");
this.iban = iban;
this.ibanType = ibanType;
}
public bool IsQrIban
{
get { return ibanType == IbanType.QrIban; }
}
public override string ToString()
{
return iban.Replace("-", "").Replace("\n", "").Replace(" ","");
}
public enum IbanType
{
Iban,
QrIban
}
public class SwissQrCodeIbanException : Exception
{
public SwissQrCodeIbanException()
{
}
public SwissQrCodeIbanException(string message)
: base(message)
{
}
public SwissQrCodeIbanException(string message, Exception inner)
: base(message, inner)
{
}
}
}
public class Contact
{
private static readonly HashSet<string> twoLetterCodes = ValidTwoLetterCodes();
private string br = "\r\n";
private string name, streetOrAddressline1, houseNumberOrAddressline2, zipCode, city, country;
private AddressType adrType;
/// <summary>
/// Contact type. Can be used for payee, ultimate payee, etc. with address in structured mode (S).
/// </summary>
/// <param name="name">Last name or company (optional first name)</param>
/// <param name="zipCode">Zip-/Postcode</param>
/// <param name="city">City name</param>
/// <param name="country">Two-letter country code as defined in ISO 3166-1</param>
/// <param name="street">Streetname without house number</param>
/// <param name="houseNumber">House number</param>
[Obsolete("This constructor is deprecated. Use WithStructuredAddress instead.")]
public Contact(string name, string zipCode, string city, string country, string street = null, string houseNumber = null) : this (name, zipCode, city, country, street, houseNumber, AddressType.StructuredAddress)
{
}
/// <summary>
/// Contact type. Can be used for payee, ultimate payee, etc. with address in combined mode (K).
/// </summary>
/// <param name="name">Last name or company (optional first name)</param>
/// <param name="country">Two-letter country code as defined in ISO 3166-1</param>
/// <param name="addressLine1">Adress line 1</param>
/// <param name="addressLine2">Adress line 2</param>
[Obsolete("This constructor is deprecated. Use WithCombinedAddress instead.")]
public Contact(string name, string country, string addressLine1, string addressLine2) : this(name, null, null, country, addressLine1, addressLine2, AddressType.CombinedAddress)
{
}
public static Contact WithStructuredAddress(string name, string zipCode, string city, string country, string street = null, string houseNumber = null)
{
return new Contact(name, zipCode, city, country, street, houseNumber, AddressType.StructuredAddress);
}
public static Contact WithCombinedAddress(string name, string country, string addressLine1, string addressLine2)
{
return new Contact(name, null, null, country, addressLine1, addressLine2, AddressType.CombinedAddress);
}
private Contact(string name, string zipCode, string city, string country, string streetOrAddressline1, string houseNumberOrAddressline2, AddressType addressType)
{
//Pattern extracted from https://qr-validation.iso-payments.ch as explained in https://github.com/codebude/QRCoder/issues/97
var charsetPattern = @"^([a-zA-Z0-9\.,;:'\ \+\-/\(\)?\*\[\]\{\}\\`´~ ^|]|[!""#%&<>÷=@_$£¡¢¤¥¦§¨©ª«¬®¯°±²³µ¶·¸¹º»¼½¾¿×Ø€]|[àáâäãåāăąçćĉċčďđèéêëēĕėęěĝğġģĥħìíîïĩīĭįıijķĸĺļľŀłñńņňʼnŋòóôöōŏőõŕŗřśŝşšșţťŧțùúûüũūŭůűųŵýÿŷźżžßÀÁÂÄÃÅĀĂĄÇĆĈĊČĎĐÈÉÊËĒĔĖĘĚĜĞĠĢĤĦÌÍÎÏĨĪĬĮİIJĴĵĶĹĻĽĿŁÑŃŅŇŊÒÓÔÖÕŌŎŐŔŖŘŚŜŞŠȘŢŤŦȚÙÚÛÜŨŪŬŮŰŲŴÝŶŸŹŻŽÆÐÞæðøþŒœſ])*$";
this.adrType = addressType;
if (string.IsNullOrEmpty(name))
throw new SwissQrCodeContactException("Name must not be empty.");
if (name.Length > 70)
throw new SwissQrCodeContactException("Name must be shorter than 71 chars.");
if (!Regex.IsMatch(name, charsetPattern))
throw new SwissQrCodeContactException($"Name must match the following pattern as defined in pain.001: {charsetPattern}");
this.name = name;