-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathGS1Encoder.cs
More file actions
1039 lines (932 loc) · 42 KB
/
Copy pathGS1Encoder.cs
File metadata and controls
1039 lines (932 loc) · 42 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
using System;
using System.Runtime.InteropServices;
namespace GS1.Encoders
{
/*
* Copyright (c) 2021-2026 GS1 AISBL.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/// <summary>
/// Main class for processing GS1 barcode data, including validation, format conversion, and generation of outputs such as GS1 Digital Link URIs and Human-Readable Interpretation text.
/// </summary>
/// <remarks>
/// The library is thread-safe provided that each thread operates on its
/// own GS1Encoder instance. This applies also to the property getters,
/// which mutate internal buffers of the native context.
/// </remarks>
public class GS1Encoder : IDisposable
{
/// <summary>
/// Recognised GS1 barcode formats ("symbologies") for processing scan data.
/// </summary>
public enum Symbology
{
/// <summary>None defined</summary>
NONE = -1,
/// <summary>GS1 DataBar Omnidirectional</summary>
DataBarOmni = 0,
/// <summary>GS1 DataBar Truncated</summary>
DataBarTruncated = 1,
/// <summary>GS1 DataBar Stacked</summary>
DataBarStacked = 2,
/// <summary>GS1 DataBar Stacked Omnidirectional</summary>
DataBarStackedOmni = 3,
/// <summary>GS1 DataBar Limited</summary>
DataBarLimited = 4,
/// <summary>GS1 DataBar Expanded (Stacked)</summary>
DataBarExpanded = 5,
/// <summary>UPC-A</summary>
UPCA = 6,
/// <summary>UPC-E</summary>
UPCE = 7,
/// <summary>EAN-13</summary>
EAN13 = 8,
/// <summary>EAN-8</summary>
EAN8 = 9,
/// <summary>GS1-128 with CC-A or CC-B</summary>
GS1_128_CCA = 10,
/// <summary>GS1-128 with CC</summary>
GS1_128_CCC = 11,
/// <summary>(GS1) QR Code</summary>
QR = 12,
/// <summary>(GS1) Data Matrix</summary>
DM = 13,
/// <summary>(GS1) DotCode</summary>
DotCode = 14,
/// <summary>Value is the number of symbologies</summary>
NUMSYMS = 15,
};
/// <summary>
/// Optional AI validation procedures that may be applied to detect invalid inputs.
/// </summary>
/// <remarks>
/// <para>
/// These validation procedures are applied when AI data is provided using
/// <see cref="AIdataStr"/>, <see cref="DataStr"/> or <see cref="ScanData"/>.
/// </para>
/// <para>
/// Only AI validation procedures whose "enabled" status can be updated (i.e. not "locked") are described.
/// </para>
/// </remarks>
public enum Validation
{
/// <summary>Mutually exclusive AIs (locked: always enabled)</summary>
MutexAIs = 0,
/// <summary>Mandatory associations between AIs</summary>
RequisiteAIs = 1,
/// <summary>Repeated AIs having same value (locked: always enabled)</summary>
RepeatedAIs = 2,
/// <summary>Serialisation qualifier AIs must be present with Digital Signature (locked: always enabled)</summary>
DigSigSerialKey = 3,
/// <summary>Unknown AIs not permitted as GS1 DL URI data attributes</summary>
UnknownAInotDLattr = 4,
/// <summary>Value is the number of validations</summary>
NUMVALIDATIONS = 5,
};
/// <summary>
/// The expected name of the GS1 Barcode Syntax Engine dynamic-link library
/// </summary>
private const String gs1_dll = "gs1encoders.dll";
/// <summary>
/// An opaque handle used by the native code to represent an
/// "instance" of the library. It is hidden behind the object
/// interface that is provided to users of this wrapper.
/// </summary>
/// <remarks>
/// P/Invoke marshalling of a SafeHandle keeps the native context
/// alive for the duration of each native call and throws
/// ObjectDisposedException once the handle has been closed.
/// </remarks>
private readonly GS1EncoderHandle ctx;
private sealed class GS1EncoderHandle : SafeHandle
{
public GS1EncoderHandle() : base(IntPtr.Zero, true) { }
public override bool IsInvalid => handle == IntPtr.Zero;
protected override bool ReleaseHandle()
{
gs1_encoder_free(handle);
return true;
}
}
/// <summary>
/// Initialisation options for the GS1Encoder.
/// New properties may be added in future versions without breaking existing code.
/// </summary>
public class InitOptions
{
/// <summary>
/// Path to a GS1 Syntax Dictionary file. If null, the embedded AI table is used.
/// </summary>
public string SyntaxDictionary { get; set; } = null;
/// <summary>
/// Fall back to the embedded AI table if the Syntax Dictionary cannot be loaded.
/// </summary>
public bool FallbackOnSyndictError { get; set; } = false;
/// <summary>
/// Refuse to use the embedded AI table. Initialisation fails if no other AI table can be loaded.
/// </summary>
public bool NoEmbedded { get; set; } = false;
}
[StructLayout(LayoutKind.Sequential)]
private struct NativeInitOpts
{
public UIntPtr structSize;
public int flags;
public IntPtr status;
public IntPtr msgBuf;
public UIntPtr msgBufSize;
public IntPtr syntaxDictionary;
}
private const int iNO_EMBEDDED = 1 << 1;
private const int iFALLBACK_ON_SYNDICT_ERROR = 1 << 2;
private const int INIT_FALLBACK_TO_EMBEDDED_TABLE = 1;
private const int MsgBufSize = 256;
/*
* Functions imported from the native GS1 Barcode Syntax Engine dynamic-link library
*
*/
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_init_ex", CallingConvention = CallingConvention.Cdecl)]
private static extern GS1EncoderHandle gs1_encoder_init_ex(IntPtr mem, ref NativeInitOpts opts);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getVersion", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr gs1_encoder_getVersion();
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getErrMsg", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr gs1_encoder_getErrMsg(GS1EncoderHandle ctx);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getErrMarkup", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr gs1_encoder_getErrMarkup(GS1EncoderHandle ctx);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getSym", CallingConvention = CallingConvention.Cdecl)]
private static extern int gs1_encoder_getSym(GS1EncoderHandle ctx);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_setSym", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_setSym(GS1EncoderHandle ctx, int sym);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getAddCheckDigit", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_getAddCheckDigit(GS1EncoderHandle ctx);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_setAddCheckDigit", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_setAddCheckDigit(GS1EncoderHandle ctx, [MarshalAs(UnmanagedType.U1)] bool addCheckDigit);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getIncludeDataTitlesInHRI", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_getIncludeDataTitlesInHRI(GS1EncoderHandle ctx);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_setIncludeDataTitlesInHRI", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_setIncludeDataTitlesInHRI(GS1EncoderHandle ctx, [MarshalAs(UnmanagedType.U1)] bool includeDataTitlesInHRI);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getPermitUnknownAIs", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_getPermitUnknownAIs(GS1EncoderHandle ctx);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_setPermitUnknownAIs", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_setPermitUnknownAIs(GS1EncoderHandle ctx, [MarshalAs(UnmanagedType.U1)] bool permitUnknownAIs);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getPermitZeroSuppressedGTINinDLuris", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_getPermitZeroSuppressedGTINinDLuris(GS1EncoderHandle ctx);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_setPermitZeroSuppressedGTINinDLuris", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_setPermitZeroSuppressedGTINinDLuris(GS1EncoderHandle ctx, [MarshalAs(UnmanagedType.U1)] bool permitZeroSuppressedGTINinDLuris);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getValidationEnabled", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_getValidationEnabled(GS1EncoderHandle ctx, int validation);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_setValidationEnabled", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_setValidationEnabled(GS1EncoderHandle ctx, int validation, [MarshalAs(UnmanagedType.U1)] bool enabled);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getDataStr", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr gs1_encoder_getDataStr(GS1EncoderHandle ctx);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_setDataStr", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_setDataStr(GS1EncoderHandle ctx, string dataStr);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_setAIdataStr", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_setAIdataStr(GS1EncoderHandle ctx, string aiData);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getAIdataStr", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr gs1_encoder_getAIdataStr(GS1EncoderHandle ctx);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getScanData", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr gs1_encoder_getScanData(GS1EncoderHandle ctx);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_setScanData", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
private static extern bool gs1_encoder_setScanData(GS1EncoderHandle ctx, string scanData);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getDLuri", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr gs1_encoder_getDLuri(GS1EncoderHandle ctx, string stem);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getHRI", CallingConvention = CallingConvention.Cdecl)]
private static extern int gs1_encoder_getHRI(GS1EncoderHandle ctx, ref IntPtr hri);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_getDLignoredQueryParams", CallingConvention = CallingConvention.Cdecl)]
private static extern int gs1_encoder_getDLignoredQueryParams(GS1EncoderHandle ctx, ref IntPtr qp);
[DllImport(gs1_dll, EntryPoint = "gs1_encoder_free", CallingConvention = CallingConvention.Cdecl)]
private static extern void gs1_encoder_free(IntPtr ctx);
/*
* Methods to provide a wrapper around the functional interface imported from the native library
*
*/
// This C# wrapper library throws an exception containing the error message whenever
// an error is returned by the native library. Therefore direct access to the native
// error message is not necessary.
private string ErrMsg
{
get
{
return Marshal.PtrToStringAnsi(gs1_encoder_getErrMsg(ctx));
}
}
/// <summary>
/// Initialises a new instance of the GS1Encoder class.
/// </summary>
/// <exception cref="GS1EncoderGeneralException">Thrown when the library fails to initialise</exception>
public GS1Encoder() : this((InitOptions)null) { }
/// <summary>
/// Initialises a new instance of the GS1Encoder class with the given options.
/// </summary>
/// <param name="options">Initialisation options, or null for defaults.</param>
/// <exception cref="GS1EncoderGeneralException">Thrown when the library fails to initialise</exception>
public GS1Encoder(InitOptions options)
{
NativeInitOpts opts = new NativeInitOpts();
opts.structSize = (UIntPtr)Marshal.SizeOf<NativeInitOpts>();
IntPtr syntaxDictPtr = IntPtr.Zero;
IntPtr msgBufPtr = Marshal.AllocHGlobal(MsgBufSize);
IntPtr statusPtr = Marshal.AllocHGlobal(sizeof(int));
try
{
Marshal.WriteByte(msgBufPtr, 0);
Marshal.WriteInt32(statusPtr, 0);
opts.msgBuf = msgBufPtr;
opts.msgBufSize = (UIntPtr)MsgBufSize;
opts.status = statusPtr;
if (options != null)
{
if (options.FallbackOnSyndictError) opts.flags |= iFALLBACK_ON_SYNDICT_ERROR;
if (options.NoEmbedded) opts.flags |= iNO_EMBEDDED;
if (options.SyntaxDictionary != null)
{
syntaxDictPtr = Marshal.StringToHGlobalAnsi(options.SyntaxDictionary);
opts.syntaxDictionary = syntaxDictPtr;
}
}
ctx = gs1_encoder_init_ex(IntPtr.Zero, ref opts);
if (ctx.IsInvalid)
{
string msg = Marshal.PtrToStringAnsi(msgBufPtr);
throw new GS1EncoderGeneralException(
!string.IsNullOrEmpty(msg) ? msg : "Failed to initialise the native library");
}
if (Marshal.ReadInt32(statusPtr) == INIT_FALLBACK_TO_EMBEDDED_TABLE)
{
string warning = Marshal.PtrToStringAnsi(msgBufPtr);
if (!string.IsNullOrEmpty(warning))
InitFallbackWarning = warning;
}
}
finally
{
if (syntaxDictPtr != IntPtr.Zero)
Marshal.FreeHGlobal(syntaxDictPtr);
Marshal.FreeHGlobal(msgBufPtr);
Marshal.FreeHGlobal(statusPtr);
}
}
/// <summary>
/// The warning message produced when initialisation fell back to the embedded AI
/// table because the supplied Syntax Dictionary could not be loaded
/// (only when <see cref="InitOptions.FallbackOnSyndictError"/> was set).
/// <c>null</c> on plain success.
/// </summary>
public string InitFallbackWarning { get; private set; } = null;
/// <summary>
/// Get the version string of the library.
/// </summary>
/// <value>
/// A string containing the Semantic Version of the library, in MAJOR.MINOR.PATCH form.
/// </value>
public string Version
{
get
{
return Marshal.PtrToStringAnsi(gs1_encoder_getVersion());
}
}
/// <summary>
/// Get/set the symbology type.
/// </summary>
/// <value>
/// The current symbology type.
/// </value>
/// <remarks>
/// <para>
/// This might be set manually or automatically when processing scan data with <see cref="ScanData"/>.
/// </para>
/// </remarks>
/// <exception cref="GS1EncoderParameterException">Thrown when the setter is provided with an invalid symbology type.</exception>
/// <seealso cref="Symbology"/>
/// <seealso cref="ScanData"/>
public Symbology Sym
{
get
{
return (Symbology)gs1_encoder_getSym(ctx);
}
set
{
if (!gs1_encoder_setSym(ctx, (int)value))
throw new GS1EncoderParameterException(ErrMsg);
}
}
/// <summary>
/// Get/set the "add check digit" mode for EAN/UPC and GS1 DataBar symbols.
/// </summary>
/// <value>
/// <c>true</c> if check digits will be generated automatically; <c>false</c> if the data must include a valid check digit.
/// </value>
/// <remarks>
/// <para>
/// If <c>false</c> (default), then the data string must contain a valid check digit.
/// If <c>true</c>, then the data string must not contain a check digit as one will
/// be generated automatically.
/// </para>
/// <para>
/// This option is only valid for symbologies that accept fixed-length data,
/// specifically EAN/UPC and GS1 DataBar except Expanded (Stacked).
/// </para>
/// </remarks>
/// <exception cref="GS1EncoderParameterException">Thrown when the setter is provided with an invalid value.</exception>
public bool AddCheckDigit
{
get
{
return gs1_encoder_getAddCheckDigit(ctx);
}
set
{
if (!gs1_encoder_setAddCheckDigit(ctx, value))
throw new GS1EncoderParameterException(ErrMsg);
}
}
/// <summary>
/// Get/set the "include data titles in HRI" flag.
/// </summary>
/// <value>
/// <c>true</c> if data titles should be included in HRI; otherwise <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// When set to <c>true</c>, data titles from the GS1 General Specification will be
/// included in the HRI text.
/// </para>
/// <para>
/// Default: <c>false</c>
/// </para>
/// </remarks>
public bool IncludeDataTitlesInHRI
{
get
{
return gs1_encoder_getIncludeDataTitlesInHRI(ctx);
}
set
{
if (!gs1_encoder_setIncludeDataTitlesInHRI(ctx, value))
throw new GS1EncoderParameterException(ErrMsg);
}
}
/// <summary>
/// Get/set the "permit unknown AIs" mode.
/// </summary>
/// <value>
/// <c>true</c> if unknown AIs are permitted; otherwise <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// If <c>false</c> (default), then all AIs represented by the input data must be
/// known.
/// </para>
/// <para>
/// If <c>true</c>, then unknown AIs (those not in this library's static AI table)
/// will be accepted.
/// </para>
/// <para>
/// <strong>Note:</strong> The option only applies to parsed input data, specifically bracketed AI data
/// supplied with <see cref="AIdataStr"/> and GS1 Digital Link URIs supplied
/// with <see cref="DataStr"/>. Unbracketed AI element strings containing
/// unknown AIs cannot be parsed because it is not possible to differentiate the
/// AI from its data value when the length of the AI is uncertain.
/// </para>
/// <para>
/// Default: <c>false</c>
/// </para>
/// </remarks>
public bool PermitUnknownAIs
{
get
{
return gs1_encoder_getPermitUnknownAIs(ctx);
}
set
{
if (!gs1_encoder_setPermitUnknownAIs(ctx, value))
throw new GS1EncoderParameterException(ErrMsg);
}
}
/// <summary>
/// Get/set the "permit zero-suppressed GTIN in GS1 DL URIs" mode.
/// </summary>
/// <value>
/// <c>true</c> if zero-suppressed GTINs are permitted in GS1 Digital Link URIs; otherwise <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// If <c>false</c> (default), then the value of a path component for AI (01) must
/// be provided as a full GTIN-14.
/// </para>
/// <para>
/// If <c>true</c>, then the value of a path component for AI (01) may contain the
/// GTIN-14 with zeros suppressed, in the format of a GTIN-13, GTIN-12 or GTIN-8.
/// </para>
/// <para>
/// This option only applies to parsed input data, specifically GS1 Digital Link
/// URIs. Since zero-suppressed GTINs are deprecated, this option should only be
/// enabled when it is necessary to accept legacy GS1 Digital Link URIs having
/// zero-suppressed GTIN-14.
/// </para>
/// <para>
/// Default: <c>false</c>
/// </para>
/// </remarks>
public bool PermitZeroSuppressedGTINinDLuris
{
get
{
return gs1_encoder_getPermitZeroSuppressedGTINinDLuris(ctx);
}
set
{
if (!gs1_encoder_setPermitZeroSuppressedGTINinDLuris(ctx, value))
throw new GS1EncoderParameterException(ErrMsg);
}
}
/// <summary>
/// Enable or disable the given AI validation procedure.
/// </summary>
/// <param name="validation">A validation procedure to set the enabled status of</param>
/// <param name="enabled"><c>true</c> to enable the validation; <c>false</c> to disable</param>
/// <remarks>
/// <para>
/// This determines whether certain checks are enforced when data is provided using
/// <see cref="AIdataStr"/>, <see cref="DataStr"/> or <see cref="ScanData"/>.
/// </para>
/// <para>
/// If enabled is <c>true</c> (default), then the corresponding validation will be enforced.
/// If enabled is <c>false</c>, then the corresponding validation will not be enforced.
/// </para>
/// <para>
/// <strong>Note:</strong> The option only applies to AI input data.
/// </para>
/// </remarks>
public void SetValidationEnabled(Validation validation, bool enabled)
{
if (!gs1_encoder_setValidationEnabled(ctx, (int)validation, enabled))
throw new GS1EncoderParameterException(ErrMsg);
}
/// <summary>
/// Get the current enabled status of the provided AI validation procedure.
/// </summary>
/// <param name="validation">A validation procedure to check the status of</param>
/// <returns><c>true</c> if the AI validation procedure is currently enabled; <c>false</c> otherwise</returns>
public bool GetValidationEnabled(Validation validation)
{
return gs1_encoder_getValidationEnabled(ctx, (int)validation);
}
/// <summary>
/// Get/set the "validate AI associations" flag.
/// </summary>
/// <value>
/// <c>true</c> if the <see cref="Validation.RequisiteAIs"/> validation procedure is enabled; otherwise <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// <strong>Deprecated:</strong> Use <see cref="SetValidationEnabled(Validation, bool)"/>
/// and <see cref="GetValidationEnabled(Validation)"/> instead.
/// </para>
/// <para>
/// This property is equivalent to using the <see cref="GetValidationEnabled(Validation)"/> and
/// <see cref="SetValidationEnabled(Validation, bool)"/> methods with the
/// <see cref="Validation.RequisiteAIs"/> validation procedure.
/// </para>
/// </remarks>
[Obsolete]
public bool ValidateAIassociations
{
get
{
return GetValidationEnabled(Validation.RequisiteAIs);
}
set
{
SetValidationEnabled(Validation.RequisiteAIs, value);
}
}
/// <summary>
/// Get/set the raw data that would be directly encoded within a GS1 barcode message.
/// </summary>
/// <value>
/// The raw barcode data input buffer.
/// </value>
/// <remarks>
/// <para>
/// A <c>"^"</c> character at the start of the input indicates that the data is in GS1
/// Application Identifier syntax. In this case, all subsequent instances of the
/// <c>"^"</c> character represent the FNC1 non-data characters that are used to
/// separate fields that are not specified as being pre-defined length from
/// subsequent fields.
/// </para>
/// <para>
/// Inputs beginning with <c>"^"</c> will be validated against certain data syntax
/// rules for GS1 AIs. If the input is invalid then this setter will throw
/// a <see cref="GS1EncoderParameterException"/>.
/// In the case that the data is unacceptable due to invalid AI content then
/// a marked up version of the offending AI can be retrieved using <see cref="ErrMarkup"/>.
/// </para>
/// <para>
/// <strong>Note:</strong> It is strongly advised that GS1 data input is instead specified using
/// <see cref="AIdataStr"/> which takes care of the AI encoding rules
/// automatically, including insertion of FNC1 characters where required. This
/// can be used for all symbologies that accept GS1 AI syntax data.
/// </para>
/// <para>
/// Inputs beginning with <c>"http://"</c> or <c>"https://"</c> will be parsed as a GS1
/// Digital Link URI during which the corresponding AI element string is
/// extracted and validated.
/// </para>
/// <para>
/// EAN/UPC, GS1 DataBar and GS1-128 support a Composite Component. The
/// Composite Component must be specified in AI syntax. It must be separated
/// from the primary linear components with a <c>"|"</c> character and begin with an
/// FNC1 in first position, for example:
/// </para>
/// <code>
/// encoder.DataStr = "^0112345678901231|^10ABC123^11210630";
/// </code>
/// <para>
/// The above specifies a linear component representing "(01)12345678901231"
/// together with a composite component representing "(10)ABC123(11)210630".
/// </para>
/// <para>
/// <strong>Note:</strong> For GS1 data it is simpler and less error prone to specify the input
/// in human-friendly GS1 AI syntax using <see cref="AIdataStr"/>.
/// </para>
/// </remarks>
/// <exception cref="GS1EncoderParameterException">Thrown when the setter is provided with invalid data.</exception>
/// <seealso cref="AIdataStr"/>
/// <seealso cref="ErrMarkup"/>
public string DataStr
{
get
{
return Marshal.PtrToStringAnsi(gs1_encoder_getDataStr(ctx));
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (!gs1_encoder_setDataStr(ctx, value))
throw new GS1EncoderParameterException(ErrMsg);
}
}
/// <summary>
/// Get/set the barcode data input buffer using GS1 Application Identifier syntax.
/// </summary>
/// <value>
/// The barcode data in human-friendly GS1 AI syntax, or <c>null</c> if the input data does not contain AI data.
/// </value>
/// <remarks>
/// <para>
/// The input is provided in human-friendly format <strong>without</strong> FNC1 characters
/// which are inserted automatically, for example:
/// </para>
/// <para>
/// <c>(01)12345678901231(10)ABC123(11)210630</c>
/// </para>
/// <para>
/// This syntax harmonises the format for the input accepted by all symbologies.
/// For example, the following input is acceptable for EAN-13, UPC-A, UPC-E, any
/// variant of the GS1 DataBar family, GS1 QR Code and GS1 DataMatrix:
/// </para>
/// <para>
/// <c>(01)00031234000054</c>
/// </para>
/// <para>
/// The input is immediately parsed and validated against certain rules for GS1 AIs, after
/// which the resulting encoding for valid inputs is available via <see cref="DataStr"/>.
/// If the input is invalid then an exception will be thrown.
/// </para>
/// <para>
/// Any <c>"("</c> characters in AI element values must be escaped as <c>"\\("</c> to avoid
/// conflating them with the start of the next AI.
/// </para>
/// <para>
/// For symbologies that support a composite component (all except Data Matrix, QR Code,
/// and DotCode), the data for the linear and 2D components can be separated by a
/// <c>"|"</c> character, for example:
/// </para>
/// <para>
/// <c>(01)12345678901231|(10)ABC123(11)210630</c>
/// </para>
/// </remarks>
public string AIdataStr
{
get
{
return Marshal.PtrToStringAnsi(gs1_encoder_getAIdataStr(ctx));
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (!gs1_encoder_setAIdataStr(ctx, value))
throw new GS1EncoderParameterException(ErrMsg);
}
}
/// <summary>
/// Process scan data received from a barcode reader or return the expected scan data string.
/// </summary>
/// <value>
/// The scan data string that a reader should return when scanning the current data.
/// </value>
/// <exception cref="GS1EncoderScanDataException">
/// Getting: if no symbology is selected or the current data cannot be represented in the selected symbology.
/// Setting: if the scan data is invalid.
/// </exception>
/// <remarks>
/// <para>
/// <strong>Setting:</strong> Process normalised scan data received from a barcode reader with
/// reporting of AIM symbology identifiers enabled to extract the message data and perform
/// syntax checks in the case of GS1 Digital Link and AI data input.
/// </para>
/// <para>
/// This function will process scan data (such as the output of a barcode reader) and process
/// the received data, setting the data input buffer to the message received and setting the
/// selected symbology to something that is able to carry the received data.
/// </para>
/// <para>
/// <strong>Note:</strong> In some instances the symbology determined by this library will not match
/// that of the image that was scanned. The AIM symbology identifier prefix of the
/// scan data does not always uniquely identify the symbology that was scanned.
/// For example GS1-128 Composite symbols share the same symbology identifier as
/// the GS1 DataBar family, and will therefore be detected as such.
/// </para>
/// <para>
/// A literal <c>"|"</c> character may be included in the scan data to indicate the
/// separation between the first and second messages that would be transmitted
/// by a reader that is configured to return the composite component when
/// reading EAN/UPC symbols.
/// </para>
/// <para>
/// Example scan data input: <c>]C1011231231231233310ABC123{GS}99TESTING</c>
/// where {GS} represents ASCII character 29.
/// </para>
/// <para>
/// <strong>Getting:</strong> Returns the string that should be returned by scanners when reading a
/// symbol that is an instance of the selected symbology and contains the same input data.
/// </para>
/// <para>
/// The output will be prefixed with the appropriate AIM symbology identifier.
/// </para>
/// </remarks>
public string ScanData
{
get
{
string outStr = Marshal.PtrToStringAnsi(gs1_encoder_getScanData(ctx));
if (outStr == null)
throw new GS1EncoderScanDataException(ErrMsg);
return outStr;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (!gs1_encoder_setScanData(ctx, value))
throw new GS1EncoderScanDataException(ErrMsg);
}
}
/// <summary>
/// Get the error markup generated when parsing AI data fails due to a linting failure.
/// </summary>
/// <value>
/// Marked up instance of the AI that failed validation, or empty string if no linting failure.
/// </value>
/// <remarks>
/// <para>
/// When a setter function returns <c>false</c> (indicating an error), if that failure is due to
/// AI-based data being invalid, a marked up instance of the AI that failed will be generated.
/// </para>
/// <para>
/// Where it is meaningful to identify offending characters in the input data, these characters
/// will be surrounded by <c>"|"</c> characters. Otherwise the entire AI value will be surrounded by
/// <c>"|"</c> characters.
/// </para>
/// </remarks>
public string ErrMarkup
{
get
{
return Marshal.PtrToStringAnsi(gs1_encoder_getErrMarkup(ctx));
}
}
/// <summary>
/// Get a GS1 Digital Link URI that represents the AI-based input data.
/// </summary>
/// <param name="stem">A URI "stem" used as a prefix for the URI. If <c>null</c>, the GS1 canonical stem (https://id.gs1.org/) will be used.</param>
/// <returns>A string representing the GS1 Digital Link URI for the input data</returns>
/// <exception cref="GS1EncoderDigitalLinkException">Thrown when invalid input was provided</exception>
/// <remarks>
/// <para>
/// This method converts AI-based input data into a GS1 Digital Link URI format.
/// </para>
/// <para>
/// Example: <c>(01)12345678901231(10)ABC123(11)210630</c> with stem
/// <c>https://id.example.com/stem</c> might produce:
/// <c>https://id.example.com/stem/01/12345678901231?10=ABC123&11=210630</c>
/// </para>
/// </remarks>
public string GetDLuri(string stem)
{
string uri = Marshal.PtrToStringAnsi(gs1_encoder_getDLuri(ctx, stem));
if (uri == null)
throw new GS1EncoderDigitalLinkException(ErrMsg);
return uri;
}
/// <summary>
/// Get the Human-Readable Interpretation ("HRI") text for the current data input buffer.
/// </summary>
/// <value>
/// An array of null-terminated strings representing the HRI text.
/// </value>
/// <remarks>
/// <para>
/// For composite symbols, a separator "--" will be included in the array to distinguish
/// between the linear and 2D components.
/// </para>
/// <para>
/// Example output for <c>^011231231231233310ABC123|^99XYZ(TM) CORP</c>:
/// </para>
/// <para>
/// <c>(01) 12312312312333</c><br/>
/// <c>(10) ABC123</c><br/>
/// <c>--</c><br/>
/// <c>(99) XYZ(TM) CORP</c>
/// </para>
/// </remarks>
public string[] HRI
{
get
{
IntPtr p = IntPtr.Zero;
int numAIs = gs1_encoder_getHRI(ctx, ref p);
IntPtr[] pAI = new IntPtr[numAIs];
Marshal.Copy(p, pAI, 0, numAIs);
string[] hri = new string[numAIs];
for (int i = 0; i < numAIs; i++)
{
hri[i] = Marshal.PtrToStringAnsi(pAI[i]);
}
return hri;
}
}
/// <summary>
/// Get the non-numeric (ignored) query parameters from a GS1 Digital Link URI.
/// </summary>
/// <value>
/// An array of strings containing the non-numeric query parameters that were ignored when processing a GS1 Digital Link URI.
/// </value>
/// <remarks>
/// <para>
/// For example, if the input data buffer contains:
/// <c>https://a/01/12312312312333/22/ABC?name=Donald%2dDuck&99=ABC&testing&type=cartoon</c>
/// </para>
/// <para>
/// Then this property returns:
/// <c>name=Donald%2dDuck</c>, <c>testing</c>, <c>type=cartoon</c>
/// </para>
/// <para>
/// The returned strings are not URI decoded. The expected use for this property is to
/// present which sections of a given GS1 Digital Link URI have been ignored.
/// </para>
/// </remarks>
public string[] DLignoredQueryParams
{
get
{
IntPtr p = IntPtr.Zero;
int numAIs = gs1_encoder_getDLignoredQueryParams(ctx, ref p);
IntPtr[] pAI = new IntPtr[numAIs];
Marshal.Copy(p, pAI, 0, numAIs);
string[] qp = new string[numAIs];
for (int i = 0; i < numAIs; i++)
{
qp[i] = Marshal.PtrToStringAnsi(pAI[i]);
}
return qp;
}
}
/// <summary>
/// Releases the resources used by this GS1Encoder instance.
/// </summary>
/// <param name="disposing">True if called from Dispose; false if called from a finalizer.</param>
protected virtual void Dispose(bool disposing)
{
ctx.Dispose();
}
/// <summary>
/// Releases the resources used by this GS1Encoder instance.
/// </summary>
/// <remarks>
/// Disposal is idempotent. Any other member used after disposal
/// throws <see cref="ObjectDisposedException"/>. The native context
/// is owned by a SafeHandle, so no finalizer is required on this
/// class and the context cannot be reclaimed while a native call
/// is in flight.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
/// <summary>
/// A custom exception class that is thrown to indicate a general problem
/// initialising the library, such as when the dynamic-link library isn't accessible.
/// </summary>
public class GS1EncoderGeneralException : Exception
{
/// <summary>
/// Error constructor.
/// </summary>
/// <param name="message">
/// Description of the error.
/// </param>
public GS1EncoderGeneralException(string message)
: base(message)
{
}
}
/// <summary>
/// A custom exception class that is thrown to indicate a problem with barcode
/// options that are being set.
/// </summary>
public class GS1EncoderParameterException : Exception
{
/// <summary>
/// Error constructor.
/// </summary>
/// <param name="message">
/// Description of the error.
/// </param>
public GS1EncoderParameterException(string message)
: base(message)
{
}