Home
Procedure for Calling C# PER Encode Methods
Contents
1. lt title gt lt IA5String gt Director lt IA5String gt lt title gt lt dateOfHire gt 114 Event Handler Interface lt IA5String gt 19710917 lt IA5String gt lt dateOfHire gt lt nameOfSpouse gt lt givenName gt lt IA5String gt Mary lt IA5String gt lt givenName gt lt initial gt lt IA5String gt T lt IA5String gt lt initial gt lt familyName gt lt IA5String gt Smith lt IA5String gt lt familyName gt lt nameOfSpouse gt lt children gt lt element gt lt name gt lt givenName gt lt IA5String gt Ralph lt IA5String gt lt givenName gt lt initial gt lt IA5String gt T lt IA5String gt lt initial gt lt familyName gt lt IA5String gt Smith lt IA5String gt lt familyName gt lt name gt lt dateOfBirth gt lt IA5String gt 19571111 lt IA5String gt lt dateOfBirth gt lt element gt lt element gt lt name gt lt givenName gt lt IA5String gt Susan lt IA5String gt lt givenName gt lt initial gt lt IA5String gt B lt IA5String gt lt initial gt lt familyName gt lt IA5String gt Jones lt IA5String gt lt familyName gt lt name gt lt dateOfBirth gt lt IA5String gt 19590717 lt TIA5String gt lt dateOfBirth gt lt element gt lt children gt lt PersonnelRecord gt Add an XML document header and you should be able to display this data in XML enabled browser
2. ENUMERATED The ASN 1 ENUMERATED type is converted into a C class that inherits the Asn Enumerated run time class In version 6 1 the generated code was changed to conform to Joshua Bloch s static enumeration pattern as explained in Effective Java Enumerated values are created as singletons to allow for lazy initialization A specially named object dec is created to hold decoded values In combination these changes improve application performance since only a fixed number of objects are allocated for any execution of the application The following shows the basic mapping from ASN 1 type to C class definition ASN 1 Production lt name gt ENUMERATED lt el gt lt e2 gt Pai OTS is XSD Types Any type with an lt xsd enumeration gt restriction Generated C class public class lt name gt AsnlEnume protected lt name gt int value_ base value_ public static lt name gt lt el gt if _ lt el gt null _ lt el gt ne a return _ lt el gt public static lt name gt ValueOf lt public override void Decode private static lt name gt _ lt el gt nul private static lt name gt _ lt e2 gt null private static lt name gt _dec new e public override int Encode lt code gt public override void Print lt code gt rated r L lt name gt 1 w lt n me gt lt v1 gt
3. This would be reduced to the following equivalent ASN 1 productions TestChoice c SEQUENCE aa IA5String bb NULL TestChoice CHOICE a INTE b BOOLI E Test Qa DQ D E Z this case the embedded constructed element for option c was pulled out to form the TestChoice c production and then this new production is referenced in the original definition Populating Generated Choice Structures for Encoding The only way a CHOICE construct can be populated for encoding is by using one the generated Set_ lt element gt methods It is necessary to do it this way because the base class contains two protected member variables choiceID and element that must be set consistently This is the only instance of a mapped type where the mapped element values do not have public access The following demonstrates setting a variable of the TestChoice structure defined above to use the first option TestChoice testChoice new TestChoice 51 ASN 1 Type to C Class Mappings testChoice Set_a new AsnlInteger 222 Accessing the Choice Element Value after Decoding To access the element in a choice construct after decoding the following two methods can be used both are defined in the Asn1 Choice base class 1 ChoicelD this returns an identifier equal to one the generated choice identifier constants and 2 GetElement this returns a reference to the decoded element object
4. public EmployeeNumber long value_ base value_ 31 Generated C Source Code Overview public override void Decode AsnlBerDecodeBuffer buffer bool explicitTagging int implicitLength int llen explicitTagging MatchTag buffer _TAG implicitLength base Decode buffer false llen public override int Encode AsnlBerEncodeBuffer buffer bool explicitTagging ncode buffer false GI int _aal base if explicitTagging _aal buffer EncodeTagAndLength _TAG _aal return _aal The following sections discuss the various sections of the generated C source file Namespace Specification The namespace specification is the second item in the file and is declared using the namespace keyword By default this is set to the name of the ASN 1 module that is being compiled However this can be modified by using the nspfx and namespace command line options The nspfx option adds the specified prefix before the module name For example if an ASN 1 module named Employee is being compiled and nspfx test is specified on the command line the namespace name in the generated source files would be test Employee The namespace switch takes this a step further It allows specification of the full namespace name In the sample specification above nspfx sample_ber was specified on the compiler command line Standard using statements are
5. Chapter 8 Generated PER Decode Methods For each ASN 1 production defined in the ASN 1 source file a C decode method may be generated This method will decode an ASN 1 message into public member variables within the C object As was the case for encode methods a decode method is only generated if it is required to alter the default method in the base class The C model is built on inheritance from a set of common run time base classes These run time classes contain default implementations of encode decode methods that handle the encoding decoding of the basic types For primitive types a custom PER decode method is only generated if one or more of the following is true 1 The type contains a PER visible constraint 2 The generation of event handlers was specified The exception to this rule is the ENUMERATED primitive type or likewise INTEGER type with a named number list that will always cause a decode method to be generated Constructed types will always cause custom PER decode methods to be generated Generated C Method Format and Calling Parameters The signature for a C PER decode method is as follows public override void Decode AsnlPerDecodeBuffer buffer The buffer argument is a reference of an Asn PerDecodeBuffer object that describes the message that is being decoded This must be created and initialized before calling any decode method See the description of this class in the C Run Time Classes section
6. In this case the generation of temporary types results in the following equivalent type definitions X a aa SEQUENCE x INTEGER y BOOLEAN X a SEQUENCE aa X a aa bb INTEGER X SEQUENCE X a a Note that the name for the aa element type is X a aa It contains both the name for a at level 1 and aa at level 2 This is a change from v5 1x and lower where only the production name and last element name would be used i e X aa The change was made to ensure uniqueness of the generated names when multiple nesting levels are used OPTIONAL keyword Elements within a sequence can be declared to be optional using the OPTIONAL keyword This indicates that the element is not required in the encoded message Optional elements are accounted for in the C version of the compiler by simply using null object references to denote the absence of an element Remember that even the simplest primitive ASN 1 type definitions are wrapped in a C class definition Therefore an object must be created for any type defined as an element within a SEQUENCE To populate a SEQUENCE object for encoding that contains optional elements the special constructor s for required elements only can be used The default constructor also can be used followed by the manual creation and setting of the individual element values The default constructor will initialize all element object references to null so
7. PARAMETER NamedType empty NamedType identifier type type END In this definition an error is assigned an identifying number as well as on optional parameter type to hold parameters associated with the error An example of a reference to this MACRO for the authenticationFailure error in the login operation defined earlier would be as follows applicationError ERROR PARAMETER SEQUENCE errorText IA5String y 1 The ASN1C90 compiler will generate a type definition for the error parameter and a value constant for the error value The format of the name of the type generated will be lt name gt _PARAMETER where lt name gt is the ERROR name 120 ASN1C90 applicationError in this case with the first letter set to uppercase The name of the value will simply be the ERROR name SNMP OBJECT TYPE The SNMP OBJECT TYPE MACRO is one of several MACROs used in Management Information Base MIB definitions It is the only MACRO of interest to ASNIC because it is the one that specifies the object identifiers and data that are contained in the MIB The version of the MACRO currently supported by this version of ASNIC can be found in the SMI Version 2 RFC RFC 2578 The compiler generates code for two of the items specified in this MACRO definition 1 The ASN 1 type that is specified using the SYNTAX command and 2 The assigned OBJECT IDENTIFIER value For an example of the generated code we
8. Step 1 create a decode message buffer object to describe the message to be decoded This example will use a file input stream to decode a message directly from a binary file Create an input file stream object System IO FileStream ins new System 10 FileStream filename System IO FileMode Open System IO FileAccess Read Create a decode buffer object AsnlBerDecodeBuffer decodeBuffer new AsnlBerDecodeBuffer ins Step 2 create an object of the generated type and invoke the decode method PersonnelRecord personnelRecord new PersonnelRecord personnelRecord Decode decodeBuffer Step 3 process the data if trace System Console Out WriteLine Decode was successful personnelRecord Print personnelRecord catch Exception e System Console Out WriteLine e Message AsnlUtil WriteStackTrace e Console Error return Reuse of C Decoding Objects The sample above showed the BER decoding of a single message In a typical application a loop would be involved to decode a series of messages While it would be possible to use the code shown above in a loop it would not be the most efficient way to decode the messages Objects should be reused where possible to avoid the overhead of excessive memory allocations and garbage collection A single decode buffer object can be used to process a stream of messages If the d
9. System Console Out WriteLine The Characters method simply indents and prints the stringified value public void Characters string svalue short typeCode Indent System Console Out WriteLine svalue That completes the PrintHandler class implementation Next we need to create an object of the class and register it prior to invoking the decode method In the Reader cs program the following lines do this Register event handler object PrintHandler printHandler new PrintHandler personnelRecord decodeBuffer AddNamedEventHandler printHandler The addEventHandler method defined in the Asn DecodeBuffer base class is the mechanism used to do this Note that event handler objects can be stacked Several can be registered before invoking the decode function When this is done the entire list of event handler objects is iterated through and the appropriate event handling callback function invoked whenever a defined event is encountered The implementation is now complete The program can now be compiled and run When this is done the resulting output is as follows employee name givenName John initial pr familyName Smith This can certainly be improved For one thing it can be changed to print primitive values out in a name value format 1 e without the braces But this should provide the general idea of how it is done Example 2 An XML
10. base public lt name gt lt typel gt lt argl gt lt type24 gt lt arg2 gt base lt elementl name gt lt argl gt lt element2 name gt lt arg2 gt public lt name gt lt basetypel gt lt argl gt lt basetype2 gt lt arg2 gt base lt elementl name gt new lt typel gt lt argl gt lt element2 name gt new lt type2 gt lt arg2 gt private void Init public override void Decode public override int Encode public override void Print 44 ASN 1 Type to C Class Mappings Notes 1 The notation used in the ASN 1 definition above does not represent the ASN 1 extensibility notation It is used to show a continuation of the sequence elements 2 The lt typel gt lt type2 gt etc items denote the equivalent C types generated from the ASN 1 lt element typel gt lt element type2 gt etc definitions 3 The public and private methods that are generated are shown without arguments or function bodies for brevity The compiler first generates a public member variable for each of the elements defined in the SEQUENCE The decision was made to make these variables public to make them easier to populate for encoding The alternative was to use protected or private variables with get set methods for setting or examining the values It was felt that this approach would be too cum
11. The following shows the basic mapping from ASN 1 type to C class definition int nbytes base data offset nbytes 52 ASN 1 Production lt name gt lt openType gt Generated C class public class lt name gt AsnlOpenType public lt name gt base public lt name gt byte data base data public lt name gt byte data int offset ASN 1 Type to C Class Mappings public lt name gt AsnlEncodeBuffer buffer base The lt openType gt placeholder is to be replaced with any type of open type specification It could be the ANY or ANY DEFINED BY keywords from the X 208 specification or an open type from X 681 for example TYPEIDENTIFIER amp Type The last form of the constructor shown above is for an optimized form of Open Type encoding When encoding is done using BER an open type header can be directly added to the beginning of an encoded message component By using this form of the constructor you are indicating to the run time encoder that the encoded message component onto which a header is to be added is already present in the message buffer The advantage is that binary copies of the encoded message components are avoided both from the encode buffer to the open type object and from the open type object back to the encode buffer For XER a new class derived from the Asn OpenType class was created This is the Asnl XerOpenType clas
12. ma B txt R Making a copy of the furnished ASN1CWizard vsz file and editing the copy is recommended 16 Using the Compiler You then would copy your modified ASN1CWizard vsz file into the appropriate Visual Studio folder You would also copy the ASN1CWizard ico file and the ASN1CWizard vsdir file from the vswizard folder of your ASNIC distribution into the same location Now when you invoke the New Project dialog in Visual Studio and click on Visual C you ll see a template named ASNIC Note that for C projects Visual Studio segregates user written templates into a different collection from the templates that come with Visual Studio New Project Project types Templates NET Framework 3 5 b Visual C Visual Studio installed templates Visual C asnic gt Other Languages Templ gt Other Project Types a 4 Search Online Templates ASNIC Project Wizard Name ASN1C1 Location C mydocs temp y Solution Name ASN1C1 Create directory for solution 7 Add to Source Control LA lu In this example Visual Studio 2008 is used and the dialog is invoked without a solution currently loaded So Visual Studio suggests ASNICI as both the project name and the solution If however the new project dialog is invoked from within the context of a currently loaded solution Visual Studio will default to adding the project to the current solution Also note that for this example we assum
13. The methods corresponding to these events are defined in Asn NamedEventHandler interface The start and end element methods are invoked when an element is parsed within a constructed type The start method is invoked as soon as the tag length is parsed in a BER or DER message The end method is invoked after the contents of the field are processed The signature of these methods is as follows void StartElement string name int index 109 Event Handler Interface void EndElement string name int index The name argument is used pass the element name The index argument is used for SEQUENCE OF SET OF constructs only It is used to pass the index of the item in the array This argument is set to 1 for all other constructs The Characters method is used to pass out ASN 1 primitive data This is a departure from the C event handler methodology in which separate methods are defined for all of the different data types This implementation is more closely aligned with the standard SAX implementation for XML The reason it is done this way in C and not C is because it is much easier to stringify values Since memory management is built in to C it is easy to create a string and pass it out This is a problem in C because it becomes a performance issue if too many malloc s are done and it also places a burden on the user to free the memory for the allocated strings The signature for the Characters method is as foll
14. oid OBJECT IDENTIFIER ccitt b 5 10 This would result in the following C constant being generated public static readonly int oid 0 5 10 ENUMERATED Value Specification An ENUMERATED value specification causes a reference to an enumerated singleton to be generated ASN 1 production lt name gt lt enumtype gt lt enumitem gt Generated C constants public static readonly lt enumtype gt lt name gt lt enumtime gt ValueOf lt enumvalue enumvalue will be the sequential integer value corresponding to the enumitem in enumtype REAL Value Specification A REAL value specification causes a C double constant to be generated ASN 1 production lt name gt REAL lt value gt Generated C constants public static readonlyreadonly double lt name gt lt value gt SEQUENCE Value Specification A SEQUENCE value specification causes a readonly static instance of the C class generated for the SEQUENCE to be generated ASN 1 production 58 ASN 1 Type to C Class Mappings lt name gt lt SequenceType gt lt value gt Generated C constants public static readonly lt SequenceType gt lt name gt new lt SequenceType gt new lt ElemlType gt lt elemlvalue gt new lt Elem2Type gt lt elem2value gt i For example consider the following declaration SeqType SEQUENCE oid OBJECT IDENTIFIE
15. 30 Chapter 3 Generated C Source Code Overview A separate C source file with extension cs is generated for each production encountered within an ASN 1 source file Every ASN 1 type is mapped to a C class This is true even at the lowest levels types such as BOOLEAN INTEGER and NULL all have wrapper classes The following items may be present in a generated C file e Using statements e Namespace specification e Class declaration e A tag constant object declaration e Public member variables e Constructors e Public Decode method Public Encode method Other methods Inner SAX Handler class XER only Additional specialized items may be present as well depending on the base type of the target production These specialized items are discussed in the sections on ASN 1 to C mappings for the various ASN 1 types A complete generated C source file for the EmployeeNumber production within the production within the ASN 1 sample file employee asn can be found on the following page The ASN 1 production from which this file was generated is as follows EmployeeNumber APPLICATION 2 IMPLICIT INTEGER The generated code is as follows using System using Com Objsys Asnl Runtime namespace Test public class EmployeeNumber AsnlInteger public new readonly static AsnlTag _TAG new AsnlTag AsnlTag APPL AsnlTag PRIM 2 public EmployeeNumber base
16. 77 Chapter 9 Generated XML Methods Overview X 693 specifies XER XML Encoding Rules There are three variants of XER given BASIC XER often just XER for short canonical XER and EXTENDED XER Into this mix Objective Systems has added its own encoding rules which we ll call OSys XER OSys XER is very similar to XER but has a few variations that are meant to produce XML documents more closely aligned with what you might get if you were using XML Schema to specify your abstract syntax Generally OSys XER produces fewer tags The differences between these two sets of encoding rules are discussed in more detail below ASNIC supports BASIC XER canonical XER and OSys XER It has for some time supported EXTENDED XER via direct compilation of XSD In version 6 5 0 we have begun to add direct support for EXTENDED XER by adding support for some of the XER encoding instructions Nonetheless EXTENDED XER is most fully support today via direct compilation of XSD By compiling XSD you can obtain behavior much the same as with OSys XER and more ASNIC has two runtimes for XML The XER runtime This is used for basic and canonical XER e The XML runtime This is used for OSys XER and for EXTENDED XER whether compiling XSD or compiling ASN 1 with XER encoding instructions Because these two runtimes are so similar they are discussed in this chapter together As you read this chapter it is important to keep in mind when each of thes
17. Do not generate indefinite length processing code Do not generate code to save restore unknown extensions and Do not generate types for items embedded in information objects may all be used to reduce the amount of generated code Generate compact code cannot be used in conjunction with Generate compatible code If XML validation is not needed check Do not generate XML namespaces for ASN 1 modules This will result in a smaller codebase as well as smaller output XML data Check Generate short form of type names if generated type names are too long for the target language The following tab provides options for generating utility functions and applications 11 Using the Compiler Common Code Generation Options Language Options Function Options Utity Options Sample Program Generation Generate writer sample program writer Generate reader sample program reader Generate code for populating data structures test tocol Data Units PDUs Treat all types as Protocol Data Units PDU s pdu Specify a PDU for the sample programs usepdu Debugging and Event Handlers Generate code to invoke event handler callback functions events Generate pure parser event handler callbacks with no types notypes Add tracing diagnostic messages to code trace Other Options Y Automatically create unigue names for duplicate items Do not add date stamp to generated files nodatestamp Enter c
18. It is known as this because if you go back to the original class specification you will see that operationCode is defined to be of a specific type namely a choice between a local and global value The generated typedef for this field will contain a reference to the type from the class definition The argument field is an example of a variable type field In this case if you refer back to the class definition you will see that no type is provided This means that this field can contain an instance of any encoded type note in practice table constraints can be used with Information Object Sets to limit the message types that can be placed in this field The generated typedef for this field contains an open type C Asn1 OpenType class reference to hold a previously encoded component to be specified in the final message Simple Form Code Generation In the simple form of information object code generation the Invoke type above would result in the following C typedefs being generated public class Invoke AsnlType public AsnlInteger invokelD public OPERATION_operationCode opcode public AsnlOpenType argument The following would be the procedure to add the Invoke header type to an ASN 1 message body 1 Encode the body type 2 Get the message bytes and length of the encoded body 3 Plug the bytes into the data argument of the open type constructor in the Invoke type variable 4 Populate the remaining Invoke type fie
19. It is of type Asn Type but it can be upcast to the correct element type using information from the ChoicelD call In addition the compiler generates a ElemName property that can be used to get the textual name of the decoded element XSD lt xsd union gt Type Mapping The lt xsd union gt type is handled in a similar fashion to a choice type The main difference is that the items in a union are not tagged As per X 694 special element names are generated for these items for use in an ASN 1 CHOICE type These names are based on the base name alt and progress with sequential digits added for each addional union item alt 1 alt 2 etc XML decoding is accomplished by attempting to decode the content of each alternative in the union and setting the value to the first alternative that can be decoded successfully Open Type Note The X 680 Open Type replaces the X 208 ANY or ANY DEFINED BY constructs An ANY or ANY DEFINED BY encountered within an ASN 1 module will result in the generation of code corresponding to the Open Type described below The ASN 1 Open Type is converted into a C class that inherits the Asn OpenType class This class in turn inherits the AsnlOctetString class and provides the following public member variable for storing the encoded message component public byte mValue The number of octets to be encoded or that were decoded is specified in the built in length component of the array object i e mValue length
20. is informative only to provide a better understanding of how the compiler handles table constraints An equals method will be generated for Sequence Set Sequence Of Set Of or Choice types if required for table constraint processing This method will be an implementation of the Asn1 Type equals virtual method These methods are used by the generated code to verify that data in a generated structure to be encoded or data that has just been decoded matches the table constraint values 101 Table Constraint Processing An additional table constraint check method is also generated for each type that contains table constraints These functions have the following prototypes BER DER void CheckTC bool decode PER void CheckTC bool decode bool aligned The decode argument is used to decide if this method is to used for encoding or decoding The aligned argument is for PER and specifies whether aligned or unaligned encoding decoding is in effect The purpose of these methods is to verify that the fixed values within the table constraints are what they should be and to encode or decode the open type fields using the encoder or decoder methods from the Asn1 Type objects assigned to the given table row Calls to these functions are automatically built into the standard encode or decode functions for the given type They should be considered hidden functions not for use within an application that uses the API The CheckTC method wi
21. lt Type gt Here ObjectName is replaced with name of the Object Assignment If Object is defined in ObjectSet then ObjectName is replaced with the name of the ObjectSet Assignment FieldName is replaced with name of this type field Type is the type definition in Object s typefield This type is used as Defined Type in the information object definition for type field It is also useful for the user to generate value for related OpenType definition in table constraint Information Object Set NOTE Information Object Set code generation is only done when the tables option is selected This additional code is generated to support the processing required to verify table constraints which is intended for use only in compiler generated code Therefore it is not necessary for the average user to understand the mappings in order to use the product The information presented here is informative only to provide a better understanding of how the compiler handles table constraints Information Object code will be generated in a C source file with a special class to hold the values The name of the source file and class is of the following format _ lt ModuleName gt Values cs In this definition lt ModuleName gt would be replaced with the name of the ASN 1 module in which the Information Object Sets are defined Each Information Object Set specification causes a C constant to be generated containing an array of Information Object values Each
22. or object set and the object set is NOT extensible then a table constraint violation exception will be thrown Populating OpenType Variables for Encoding When the tables option is used open type fields are generated as Asn Type fields The general procedure to populate the values for these fields is as follows 1 Check the possible type in the object set from the indexed element value 2 Populate the value for this type and assign it to the open type member variable 3 Follow the common encode procedure A complete example showing how to assign open type values when table constraint code is generated is as follows ATTRIBUTE CLASS amp Type amp id OBJECT IDENTIFIER UNIQUE WITH SYNTAX WITH SYNTAX amp Type ID amp id name ATTRIBUTE WITH SYNTAX VisibleString ID 011 commonName ATTRIBUTE WITH SYNTAX INTEGER ID 0 1 2 3 SupportedAttributes ATTRIBUTE name commonName Invoke SEQUENCE opcode ATTRIBUTE amp id SupportedAttributes argument ATTRIBUTE amp Type SupportedAttributes opcode In the above example the Invoke type contains a relative table constraint Its element opcode refers to the ATTRIBUTE class s id field and the argument element refers to ATTRIBUTE class s Type field The opcode element is the index 103 Table Constraint Processing element into the SupportedAttributes
23. this method must be invoked from within a try catch block to catch the possible Asn Exception that may be thrown Alternatively the method from which the encode method is called can declare that it throws an Asn Exception leaving it to be dealt with at a higher level Finally encode buffer methods can be called to access the encoded message component The encode method itself returns the length of the component so this item is already known however there is a MsgLength property available if you want to access this length from a different location Unlike C or C a pointer to where the message starts in the encode buffer cannot be returned recall that BER encoding is done from back to front so a message rarely starts at the beginning of a buffer However the C API provides an object called a ByteArrayInputStream that provides a way to look at the encoded component as a stream The encode buffer object therefore provides a property called ByteArrayInputStream which is the preferred way to access the encoded component In addition to ByteArrayInputStream there is a MsgCopy property that will retrieve a copy of the generated message into a byte array object This is somewhat slower because a copy needs to be done The encode buffer class also contains other methods for operating directly on the encoded component for example the write method can be used to write it to a file or other medium And of course one could derive their own special enc
24. 1 source file a decode method may be generated This method will decode an ASN 1 message into public member variables within the C object As was the case for encode methods a decode method is only generated if it is required to alter the behavior of the base class The C model is built on inheritance from a set of common run time base classes MDER supports only a few primitive types and most of these are subsets of ASN 1 built in types Therefore in most cases there is not an applicable MDER decode method in the common run time base class and so a decode method will be generated Generated Method Format and Calling Parameters The signature for an MDER decode method is as follows public virtual void Decode AsniMderDecodeBuffer buffer The buffer argument is an Asn MderDecodeBuffer object which provides the message to be decoded This must be created and initialized before calling any decode method See the description of this class in the C Run Time Classes section for details on how this class is used As you can see the decode method returns void the data is decoded into the instance on which decode is invoked and an exception is thrown if an error occurs All ASNIC exceptions are derived from Asn Exception See the section on exceptions for a complete list and description of the various ASNIC exceptions that can be thrown Procedure for Calling MDER Decode Methods The general procedure to decode an ASN 1 MDER message i
25. 115 Chapter 16 IMPORT EXPORT of Types ASNIC allows productions to be shared between different modules through the ASN 1 IMPORT EXPORT mechanism The compiler parses but ignores the EXPORTS declaration within a module As far as it is concerned any type defined within a module is available for import by another module When ASNIC sees an IMPORT statement it first checks its list of loaded modules to see if the module has already been loaded into memory If not it will attempt to find and parse another source file containing the module The logic for locating the source file is as follows 1 The configuration file 1f specified is checked for a lt sourceFile gt element containing the name of the source file for the module 2 If this element is not present the compiler looks for a file with the name lt ModuleName gt asn where module name is the name of the module specified in the IMPORT statement In both cases the I command line option can be used to tell the compiler where to look for the files The other way of specifying multiple modules is to include them all within a single ASN 1 source file It is possible to have an ASN 1 source file containing multiple module definitions in which modules IMPORT definitions from other modules An example of this would be the following ModuleA DEFINITIONS BEGIN IMPORTS B From ModuleB A B END oduleB DEFINITIONS BEGIN B INTEGER END This
26. ASN 1 Type to C Class Mappings RELATIVE OID The ASN 1 RELATIVE OID type is converted to a C class that inherits the Asn RelativeOID run time class This class inherits the Asn Objectldentifier class defined above The storage of the relative OID value is the same as described for OBJECT IDENTIFIER The only difference is the extended class defines different implementations of the encode decode methods that apply the rules associated with the RELATIVE OID type REAL The ASN 1 REAL type is converted to a C class that inherits the Asn Real run time class This base class encapsulates the following public member variable public double mValue This is where the real value to be encoded is stored It also contains the result of a decode operation Since it is public it can be accessed directly to get or set the value The generated constructors can also be used to set the value The following shows the basic mapping from ASN 1 type to C class definition ASN 1 Production lt name gt REAL XSD Types lt xsd float gt lt xsd double gt Generated C class public class lt name gt AsnlReal public lt name gt base public lt name gt double value_ base value_ This shows the class generated for a simple REAL assignment If a tagged or constrained type is specified specific encode and decode methods will be generated as well REAL Base 10 The ASN 1 Base 10 REAL typ
27. ASN 1 production definition is represented by the generated tag constant Public Member Variables The next section of the file would be public member variables In our example above no member variables are present This is because INTEGER is a primitive type so the member variable in which the integer value is stored can be found in the AsnJ Integer base class from which this class is derived This is true for all primitive types the value will be contained within the run time base class Constructed types will contain public member variables to represent the elements that make up the type For example the following SEQUENCE production Name APPLICATION 1 IMPLICIT SEQUENCE givenNamelA5String initial IA5String familyNamelA5String zJ will result in the following public member variables being added to the generated class public AsnlIA5String givenName public AsnlIA5String initial public AsnlIA5String familyName Note that the member variables are public They were declared this way to make access easier A trade off existed between ease of use and secure encapsulation The ease of use approach was chosen because it was felt that the repeated use of get set methods within deeply nested structures would be too clumsy and bulky in most applications Therefore the variables were made public to make the encapsulated values easier to set and retrieve Consistency checks have been added in some methods to make
28. Null run time class This base class does not contain a public member variable for a value because the NULL type has no associated value The following shows the basic mapping from ASN 1 type to C class definition ASN 1 Production lt name gt NULL Generated C class public class lt name gt pub lic lt name gt 9 base AsnlNull This shows the class generated for a simple NULL assignment If a tagged type is specified specific encode and decode methods will be generated as well OBJECT IDENTIFIER The ASN 1 OBJECT IDENTIFIER type is converted to a C class that inherits the Asn1 Objectldentifier run time class This base class encapsulates the following public member variable public int mValue The number of subidentifiers to be encoded or that were decoded is specified in the built in length component of the array object i e mValue length The following shows the basic mapping from ASN 1 type to C class definition ASN 1 Production Generated C class OBJECT IDENTIFIER lt name gt public class lt name gt AsnlObjectIdentifier public lt name gt base public lt name gt int value_ base value_ This shows the class generated for a simple OBJECT IDENTIFIER assignment If a tagged or constrained type is specified specific encode and decode methods will be generated as well 42
29. See the description of the Asn PerEncodeBuffer class in the runtime section for a full description of the available methods A complete example showing how to invoke a PER encode method is as follows Note personnelRecord object was previously populated with data Step 1 Create a message buffer object This object uses the 72 Generated PER Encode Methods default size increment for buffer expansion AsnlPerEncodeBuffer ncodeBuff Step 2 Invoke t from within a try catch block h ncode m r new AsnlPerEncodeBuffer thod Note that it must be done try personnelRecord if trace System Consol System Consol ncodeBuffer System Consol encodeBuffer Step 3 Acces Encod encodeBuffer e Out WriteLine Encoding was successful e Out WriteLine Hex dump of encoded record HexDump e Out WriteLine Binary dump BinDump personnelRecord s th ncod case we use to a file and PILAS d message component In this methods in the class to write the component output a formatted dump to the message dmp Write th ncoded record to a file encodeBuffer Wri filename Sys Generate a du mp file for te new System 10 FileStream tem I10 FileMode Create comparisons System 10 StreamWriter messagedmp new System IO message d messagedmp AutoF m
30. T X 691 standard e XML Encoding Rules XER as published in the ITU T X 693 standard e XML Schema to ASN 1 translation as published in the ITU T X 694 standard The compiler is capable of parsing all ASN 1 syntax as defined in the standards It is capable of parsing advanced syntax including Information Object Specifications as defined in the ITU T X 681 standard as well as Parameterized Types as defined in ITU T X 683 Note that XER support does not include support for the EXTENDED XER syntax This is accomplished through direct compilation of XSD files An internal translation of XSD to ASN 1 based on the rules in the X 694 standard is done within the compiler and the resulting ASN 1 syntax is compiled into C classes This release of the compiler contains a special compiler option 1990 that is backward compatible with deprecated features from the older X 208 and X 209 standards These include the ANY data type and unnamed fields in SEQUENCE SET and CHOICE types This version can also parse type syntax from common macro definitions such as ROSE and SNMP Chapter 2 Using the Compiler The ASNIC compiler distribution contains command line compiler executables as well as a graphical user interface GUD wizard that can aid in the specification of compiler options Please refer to the ASN1C C C Compiler User s Manual for instructions on how to run the compiler The remaining sections describe options and configuration items specific
31. added for the ASN1C C run time classes and CF utility classes Using statements may also be added for items imported from other ASN 1 modules if they don t exist within the namespace being generated Class Declaration Next comes the class declaration It is of the following form public class lt ProdName gt lt BaseClass gt lt ProdName gt is the name of the production in the ASN 1 source file lt BaseClass gt is a class from which the type is derived This can either be a standard run time or compiler generated class In our example the EmployeeNumber is an INTEGER so we can directly inherit the Asn1 Integer run time base class If we had a declaration such as the following EmployeeSSNumber APPLICATION 22 EmployeeNumber 32 Generated C Source Code Overview Our EmployeeSSNumber class would be inherited from the compiler generated EmployeeNumber class as follows public class EmployeeSSNumber EmployeeNumber Note the preceding example is not true if compact is specified In that case all intermediate classes would be removed so EmployeeSSNumber would inherit Asn Integer as in the first case Tag Constant The next item in the generated source file is a tag constant This is only generated if the production is tagged The runtime class Asn Tag is used for this constant This class contains methods for operating on ASN 1 tag values In the sample above the APPLICATION 2 tag that is present in the
32. are presented with the Common Code Generation Options screen 21 Using the Compiler Common Code Generation Options Language Options Input File Type Modern ASN 1 1997 based on X 680 standard Legacy ASN 1 based on obsolete X 208 standard with ROSE or SNMP macros XML Schema XSD E Lax Syntax Check Additional Translations E Generate equivalent XML schema XSD file E Generate HTML files for input ASN 1 Generate ASN 1 file based on X 694 XSD input only Application Language Type O c O C Java C 9 None syntax check only Encoding Rules Meer Foer Acer F perR A xer 5 xm oer 5 mDER select aligned or unaligned PER at run time Code Options E Generate code for all dependent imported type definitions E Generate code compatible with compiler version Notice that the option to generate Java code is disabled because the ASN1C GUI knows that it s generating a Visual Studio project The options to generate C and C are enabled because Visual Studio can work with both of those languages The C and C wizard capability is discussed in the ASNIC C C User s Manual For the purposes of this example let s assume you choose to generate C code for BER 22 Using the Compiler ASN ASNIC coro Common Code Generation Options Language Options Input File Type Modern ASN 1 1997 based on X 680 standard O Legacy ASN 1 based on obsol
33. array object i e mValue length The following shows the basic mapping from ASN 1 type to C class definition ASN 1 Production lt name gt OCTET STRING XSD Types lt xsd hexBinary gt lt xsd base64Binary gt 39 ASN 1 Type to C Class Mappings int offset int nbytes base data offset nbytes public lt name gt string value_ base This shows the class generated for a simple OCTET STRING assignment If a tagged or constrained type is specified specific encode and decode methods will be generated as well The constructors generated for this type provide additional options for populating the member variables in the base class In addition to passing the string directly using the data argument the string form can be used The string is passed in ASN 1 value notation format for either a binary string i e xxxx B hexadecimal string i e xxxx H or a character string i e xxxx A constructor also exists that allows a portion of a byte array starting at a given offset and consisting of a given number of bytes to be used to populate the variable Character String Types The C version of the compiler contains support for the various ASN 1 character string types including the BMP Universal and UTF 8 string types All character strings in C are based on 16 bit Unicode characters except for UniversalString which is based on a 32 bit character
34. base run time classes except Asn Null contain public member variables In practically all cases there is a single variable called value that is of the base type that needs to be populated For example the Asn1 Integer base class contains the following item 88 Generated MDER Encode Methods public long mValue So for the following assignment X INTEGER 0 255 you may populate a variable of this type either using the constructor X x new X 25 or via direct access of the member variable X x new X x mValue 25 The only primitive type that does not have a single member called mValue to represent its value is BIT STRING The Asn1BitString class also contains a second variable called numbits to specify the number of bits in the string Procedure for Calling MDER Encode Methods Once an object s member variables have been populated the object s encode method can be invoked to encode the value The general procedure to do this involves the following three steps 1 Create an encode output stream into which the value will be encoded 2 Invoke the encode method 3 Close the output stream The first step is the creation of an encode output stream an Asn MderOutputStream There is a single constructor which accepts a System IO Stream As usual you may use a buffered output stream file output stream byte array output stream etc or some combination thereof The second step is the invocation of
35. classes Similarly Asn XmlEncoder is an interface to a pure XML version of these base classes There is no difference which encode method is used output stream or message buffer The generated logic is the same the difference is only in the first parameter of the encode method This must be created and initialized before calling any encode method See the description of this class in the C Run Time Reference Manual for details on how this class is used The elemName argument is a reference to a string containing the element name text This text is used to form the standard XML angle bracketed wrapper that is applied to each element in a message Note the name passed must not contain the angle brackets i e the lt gt characters These will be added by the encode method The elemName can be passed in different ways to control how the name is applied The normal way is to pass a name that is applied as the element name of the element If null is passed then the default element name for the referenced ASN 1 built in type is used For example lt BOOLEANS is the default element name for the ASN 1 BOOLEAN type The complete list of default element names can be found in the X 693 standard If an empty string is passed i e this tells the encode method to omit the element name string all together and just encode the value this is similar to implicit tagging in the BER case The XER or XML encode methods do not return a value This is differen
36. encoding of ASN 1 by using XER encoding instructions ASN1C supports EXTENDED XER in two different ways by compiling XSD and by compiling ASN 1 with XER encoding instructions Support for XER encoding instructions in ASN 1 is limited This section relates to our support for XER encoding instructions If some features you need are not supported you might consider using direct compilation of XSD How to Generate Code for EXTENDED XER If your ASN 1 contains XER encoding instructions ASNIC will automatically generate code for EXTENDED XER instead of BASIC XER This is true whether you use xer or xm1 on the command line If however any unsupported encoding instructions are found ASNIC will ignore all XER encoding instructions since 1t would not be capable of supporting EXTENDED XER for that specification Supported Instructions and Brief Summary ASNIC supports these instructions ATTRIBUTE and BASE64 Very brief summaries of the effects of these instructions follow e ATTRIBUTE This instruction causes a component of a sequence to be encoded as an XML attribute e BASE64 This instruction causes octet strings to be encoded in a base64 representation rather than a hexadecimal one Limitations The following are limitations related to EXTENDED XER e For BASE64 ASNIC only supports BASE 64 on octet strings Using BASE64 with octet stings having contents constraints open types or restricted character strings is not
37. entire fragment of code would be present in a single ASN 1 source file 116 Chapter 17 Compact Code Generation The compact command line switch can be used to reduce the amount of source code generated for a given ASN 1 specification This is done by generating the code for simple definitions inline within structured type definitions instead of creating separate classes For example consider the following definition X APPLICATION 1 INTEGER Y APPLICATION 2 OCTET STRING SIZE 1 32 Z APPLICATION 3 SEQUENCE x 0 X y 1 Y In normal mode the compiler would generate three classes for these productions one corresponding to X Y and Z respectively But in compact mode it is recognized that a user would normally not be interested in encoding or decoding X and Y on their own They would primarily be interested in encoding or decoding the more complex structured types i e the PDU s that make up fully formed messages Taking this into account when compact is specified the compiler will not generate separate classes for X and Y in the above definition Instead it will include only the base types for X and Y in the generated code for the SEQUENCE Z All logic to handle the tags and constraints will be built directly into the Z encode and decode methods So the result will be only a single class generated Z that will contain an Asn1Integer object to represent X and an Asn1OctetS
38. is a C option that allows the entire C namespace to be changed Instead of the module name the full name specified using this option will be used This option cannot be used in conjunction with nsptx option This option suppresses the generation of encode functions nodecode None This option suppresses the generation of decode functions noIndefLen None This option instructs the compiler to omit indefinite length tests in generated decode functions These tests result in the generation of a large amount of code If you know that your application only uses definite length encoding this option can result in a much smaller code base size noOpenExt None This option instructs the compiler to not add an open extension element in constructs that contain extensibility markers The purpose of the element is to collect any unknown items in a message If an application does not care about these unknown items it can use this option to reduce the size of the generated code Using the Compiler Option Argument Description nspfx lt prefixName gt lt directory gt This is a C option for adding a prefix in front of the assigned C namespace name By default the C namespace name is set to the module name If the namespace is embedded within a hierarchy this option can be used to set the prefix that must be added to allow C to find the class definition This
39. object in the array is an instance of the equivalent C class representing the corresponding ASN 1 information object As of this writing a static array is used to hold the objects but this could be changed to something like a linked list or hash ASN 1 definition 98 Table Constraint Processing lt name gt lt ClassName gt lt Information Object1 gt lt Information Object2 gt Generated C constants public static readonly lt ClassName gt lt name gt new lt ClassName gt lt Information Object1 gt lt Information Objectl gt For example consider the following Information Object Set declaration for above ATTRIBUTE definition SupportedAttributes ATTRIBUTE name commonName This would result in the following C constant being generated public static readonly ATTRIBUTE SupportedAttributes new ATTRIBUTE _TestValues name _TestValues commonName y Generated Information Object Table Structure Information Objects and Classes are used to define multi layer protocols in which holes are defined within ASN 1 types for passing message components to different layers for processing These items are also used to define the contents of various messages that are allowed in a particular exchange of messages The ASN1C compiler extracts the types involved in these message exchanges and generates encoders decoders for them The holes in the types are accounted for by adding op
40. only the items to be encoded need be populated DEFAULT keyword The DEFAULT keyword allows a default value to be specified for elements within the SEQUENCE ASNIC will parse this specification and treat it as it does an optional element Note that the value specification is only parsed in 46 ASN 1 Type to C Class Mappings simple cases for primitive values It is up to the programmer to provide the value in complex cases For BER encoding a value must be specified be it the default or other value For DER or PER it is a requirement that no value be present in the encoding for the default value For integer and boolean default values the compiler automatically generates code to handle this requirement based on the value in the structure For other values the default value is handled the same as an optional element i e a null object reference indicates that nothing should be transmitted The programmer must set the element object reference to null on the encode side to specify default value selected If this is done a value is not encoded into the message On the decode side the developer must test for a null object reference If this is the case the default value specified in the ASN 1 specification is used Extension Elements If the SEQUENCE type contains an open extension field i e a at the end of the specification or a in the middle a special element will be inserted to capture encoded extension elements
41. option is used to specify the name of a directory to which all of the generated files will be written pdu lt typeName gt Designate given type name to be a Protocol Definition Unit PDU type By default PDU types are determined to be types that are not referenced by any other types within a module This option allows that behavior to be overridden The wildcard character may be specified for lt typeName gt to indicate that all productions within an ASN 1 module should be treated as PDU types per None This option instructs the compiler to generate functions that implement the Packed Encoding Rules PER as specified in the ASN 1 standards genPrint print None This option specifies that print methods should be generated Print shortnames None This option is used to change the name generated by compiler for embedded types in constructed types This option is required to handle the limit on the size of filenames in certain situations With this option the generated code filenames would be shorter than without this option stream None This option instructs the compiler to generate stream based encoders decoders instead of memory buffer based This makes it possible to encode directly to or decode directly from a source or sink such as a file or socket In the case of BER it will also cause forward encoders to be generated which will use indefinite lengths f
42. public static lt name gt dec return dec code lt code gt Notes 1 The notation used in the ASN 1 definition above does not represent the ASN 1 extensibility notation It is used to show a continuation of the enumerated sequence of values 2 The lt el gt lt e2 gt etc items denote enumerated constants These can be in identifier only format or identifier value format The lt v1 gt lt v2 gt etc items denote the enumerated values These are sequential numbers starting at zero if no values are provided Otherwise the actual enumerated values are used 41 ASN 1 Type to C Class Mappings 3 The public methods that are generated are shown without arguments or function bodies for brevity In the case of the enumerated type encode decode methods are always generated These verify that the given value is within the defined set An AsnIInvalidEnumException is thrown if the value is not in the defined set unless the enumeration is extensible In this case no exception is thrown If an extensibility marker is present in the ASN 1 definition it will not affect the generated constants A constant will be generated for all options both root and extended However in the ValueOf method an undefined constant will be returned to indicate that the value is not in the original specification NULL The ASN 1 NULL type is converted into to a C class that inherits the Asn
43. supported 79 Generated XML Methods e For encoder s options ASN1C decoders do not support the following encoder s options allowed by EXTENDED XER e encoding named bits as empty elements e encoding named numbers as empty elements e Enforcement of Encoding Instruction Restrictions ASN1C does not check that you are using encoding instructions properly Misapplication of encoding instructions has undefined results For example X 693 does not generally allow ATTRIBUTE to be applied to a sequence type there are a few cases where it can be such an application produces malformed XML In particular when applying ATTRIBUTE to a restricted character string type the type should be restricted to exclude the control characters listed in X 680 15 15 5 since these control characters are encoded as empty elements Another solution would be to use ATTRIBUTE and BASE64 together except that ASNIC does not currently support BASE 64 for restricted character strings ASNIC will not enforce this rule but you will get malformed XML if you try to encode a string having control characters as an attribute e XSD Generation The xsd switch does not currently generate XSD that can be used to validate EXTENDED XER encodings Actually in the worst cases it is not possible to produce XSD that validates precisely the set of valid EXTENDED XER encodings the closest approximations would either fail to reject some invalid encodings or f
44. the elements populated directly Creation of Temporary Types Temporary types are created when a SEQUENCE or any other constructed type definition contains other embedded constructed types An example of this is as follows A SEQUENCE x SEQUENCE al INTEGER a2 BOOLEAN y OCTET STRING SIZE 10 In this example the production has two elements x and y The nested SEQUENCE x has two additional elements al and a2 The ASNIC compiler first recursively pulls all of the embedded constructed elements out of the SEQUENCE and forms new temporary types The names of the temporary types are of the form lt name gt _ lt element namel gt _ lt element 45 ASN 1 Type to C Class Mappings name2 gt _ lt element nameN gt Using this algorithm the ASN 1 type defined above would be reduced to the following equivalent ASN 1 types A x SEQUENCE al INTEGER a2 BOOLEAN A SEQUENCE x A x y OCTET STRING SIZE 10 The mapping of the ASN 1 types to C classes would then be done In the case of nesting levels greater than two all of the intermediate element names are used to form the final name For example consider the following type definition that contains three nesting levels X SEQUENCE a SEQUENCE aa SEQUENCE x INTEGER y BOOLEAN bb INTEGER
45. the option Generate equivalent XML schema XSD file will be inactive Checking Generate code for all dependent imported type definitions will cause the compiler to search and generate code for modules specified in the IMPORTS statement of an ASN 1 specification Basic encoding rules are selected by default Only one of BER DER and CER can be checked at any time XML and XER are also mutually exclusive options Generated function options are shown in the following tab 10 Using the Compiler Common Code Generation Options Language Options Function Options Utility Options Generated Function Types Y Encode al Print Functions Y Decode E Stream Print Format Constraints Do not generate constraint checks tax Enable strict constraint checks strict Generate code to handle table constraints tables legacy setting in C C Do not generate inline containing types noContaining Space Optimization Generate compact code compact E Do not generate indefinite length processing code noIndefLen E Do not generate code to save restore unknown extensions noOpenExt E Do not generate types for items embedded in information objects E Do not generate XML namespaces for ASN 1 modules noxmins Generate short form of type names shortnames The options in this tab control which functions are generated and what modifications are made to those functions By default
46. to the C version ASN1C C Command Line Options The following table shows a summary of the command line options that have meaning when C code generation is selected Option Argument Description allow ambig tags This option suppresses the check that is done for ambiguous tags within a SEQUENCE or SET type within a specification Special code is generated for the decoder that assigns values to ambiguous elements within a SET in much the same way as would be done if the elements were declared to be in a SEQUENCE asnstd x680 x208 mixed This option instructs the compiler to parse ASN 1 syntax conforming to the specified standard x680 the default refers to modern ASN 1 as specified in the ITU T X 680 X 690 series of standards x208 refers to the now deprecated X 208 and X 209 standards This syntax allowed the ANY construct as well as unnamed fields in SEQUENCE SET and CHOICE constructs This option also allows for parsing and generation of code for ROSE OPERATION and ERROR macros and SNMP OBJECT TYPE macros The mixed option is used to specify a source file that contains modules with both X 208 and X 680 based syntax ber None This option instructs the compiler to generate functions that implement the Basic Encoding Rules BER as specified in the ASN 1 standards c None Generate C source code cer None This option instructs the compiler to generate functions that implement the Canonical Encoding R
47. to the generated classes Generated C Method Format and Calling Parameters The signature for a C BER memory buffer encode method is as follows public override int Encode AsnlBerEncodeBuffer buffer bool explicitTagging 61 Generated BER DER CER Encode Methods The buffer argument is a reference to an Asn BerEncodeBuffer object that describes the buffer into which a message is being encoded This must be created and initialized before calling any encode method See the description of this class in the C Run Time Classes section for details on how this class is used The explicitTagging argument specifies whether or not an explicit tag should be applied to the encoded contents The average user will almost always want to set this argument to true The only time it would not be set to true is if a user wanted to just encode a contents field with no tag This argument is used primarily by the compiler when generating internal calls to properly handle implicit and explicit tagging The return value is the length in octets of the encoded message component Unlike the C C version a negative value is never returned to indicate an encoding failure That is handled by the exception mechanism All ASNIC CA exceptions are derived from the Asn Exception base class See the section on exceptions for a complete list and description of the various exceptions that can be thrown Populating Generated Variables for Encoding Populat
48. Converter Class The ASN1C XML Encoding Rules XER encode and decode capabilities were presented in an earlier section of this document An alternate way to create an XML document from ASN 1 data is through the event handler interface It turns out that with event handlers this conversion is fairly easy As the handler events fire all of the required symbolic data is passed out to generate an XML document The programmer is free to massage this data any way he or she wants to comply with whatever DTD or XML Schema is in use 112 Event Handler Interface The ToXML sample program demonstrates the conversion of ASN 1 data to XML using event handlers The sample is not intended to be a robust implementation it is merely designed to provide guidance in how one would go about doing this transformation The sample program can be found in the csharp sample_ber ToXML subdirectory within the ASNIC installation The complete class definition for the XMLHandler class is as follows class XMLHandler AsnlNamedEventHandler protected string mVarName protected int mIndentSpaces 0 public XMLHandler string varName mVarName varName System Console Out WriteLine lt mVarName gt mIndentSpaces 3 public void StartElement string name int index Indent System Console Out WriteLine lt name gt mIndentSpaces 3 public void EndElement string name int index mIndentsSpac
49. E OF type For example a simple and very common single level nested SEQUENCE OF construct might be as follows A SEQUENCE OF SEQUENCE INTEGER a BOOLEAN b In this case a temporary type is generated for the element of the SEQUENCE OF construct This results in the following two equivalent ASN 1 types A element SEQUENCE INTEGER a BOOLEAN b A SEQUENCE OF A element These types are then converted into the equivalent C classes using the standard mapping that was previously described SEQUENCE OF Type Elements in Other Constructed Types Frequently a SEQUENCE OF construct is used to define an array of some common type in an element in some other constructed type for example a SEQUENCE An example of this is as follows SomePDU SEQUENCE addresses SEQUENCE OF AliasAddress Normally this would result in the addresses element being pulled out and used to create a temporary type with a name equal to SomePDU addresses as follows SomePDU addresses SEQUENCE OF AliasAddress SomePDU SEQUENCE addresses SomePDU addresses However when the SEQUENCE OF element references a simple defined type as above with no additional tagging or constraint information an optimization is done to cut down on the size of the generated code This optimization is to
50. Generated C Method Format and Calling Parameters The signature for a C BER decode method is as follows public override void Decode AsnlBerDecodeBuffer buffer bool explicitTagging int implicitLength The buffer argument is a reference of an Asn 1 BerDecodeBuffer object that describes the message that is being decoded This must be created and initialized before calling any decode method See the description of this class in the C Run Time Classes section for details on how this class is used The explicitTagging and implicitLength arguments specify whether or not an explicit tag should be parsed from the encoded contents The average user will almost always want to set explicitTagging to true and implicitLength to zero The only time these arguments would not be set this way is if a user wanted to directly decode contents with no tag length information These arguments are used primarily by the compiler when generating internal calls to properly handle implicit and explicit tagging The decode method returns no result Unlike the C C version a negative status value is not returned to indicate a failure That is handled by the exception mechanism All ASN1C C exceptions are derived from the Asn1 Exception base class See the section on exceptions for a complete list and description of the various ASN 1 exceptions that can be thrown The System Exception that can be thrown is in the Read method within the decode buffer base class
51. Parts of the code will be reproduced here for reference but refer to this directory to see the full implementation The format for the printout will be simple Each element name will be printed followed by an equal sign and an open brace and newline The value will then be printed followed by another newline Finally a closing brace followed by another newline will terminate the printing of the element An indentation count will be maintained to allow for a properly indented printout We will first create a class called PrintHandler that implements the Asn NamedEventHandler interface and handles the formatted printing of the data The rule for the implementation of interfaces is that you must provide an implementation for each of the methods listed That is it You can add as many additional methods member variables etc that you like The PrintHandler implementation that we created is as follows class PrintHandler AsnlNamedEventHandler protected string mVarName protected int mIndentSpaces 0 110 Event Handler Interface public PrintHandler string varName mVarName varName System Console Out WriteLine mVarName mIndentSpaces 3 public void StartElement string name int index Indent System Console Out Write name if index gt 0 System Console Out Write index System Console Out WriteLine mIndentSpaces 3 public void EndEleme
52. R id INTEGE value SeqType oid 0 1 1 id 12 This would result in the following C constant being generated for value public static readonly SeqType value new SeqType new AsnlObjectIdentifier new int 0 1 1 new AsnlInteger 12 SET Value Specification The value code generation for the ASN 1 SET type is that same as that for SEQUENCE described above SEQUENCE OF Value Specification A SEQUENCE OF value specification causes a C array constant to be generated ASN 1 production lt name gt lt SequenceOfType gt lt value gt Generated C constants public static readonly lt SequenceOfType gt lt name gt new lt SequenceOfType gt new lt ElemType gt lt elemlvalue gt new lt ElemType gt lt elem2value gt y For example consider the following declaration SeqofType SEQUENCE OF INTEGER value SeqOfType 1 2 This would result in the following C constant being generated for value public static readonly SeqOfType value new SegqOfType new AsnlInteger 1 new AsnlInteger 2 59 ASN 1 Type to C Class Mappings y SET OF Value Specification The value code generation for the ASN 1 SET OF type is that same as that for SEQUENCE OF described above CHOICE Value Specification A CHOICE value specification causes a readonly static instance of the C class generated for the CHOICE to be genera
53. R UNIQUE amp Type WITH SYNTAX amp Type IDENTIFIED BY amp id The ASN 1 compiler is used to create a meta definition for this structure The definition will be generated in the file AsnlTypeldentifier cs or AsnlXerTypeldentifier cs for XER if needed by compiling ASN 1 definitions An object created from the resulting C class is populated just like any other compiler generated structure for working with ASN 1 data Information Object NOTE Information Object code generation is only done when the tables option is selected This additional code is generated to support the processing required to verify table constraints which is intended for use only in compiler generated code Therefore it is not necessary for the average user to understand the mappings in order to use the product The information presented here is informative only to provide a better understanding of how the compiler handles table constraints Information Object code will be generated in a C source file with a special class to hold the values The name of the source file and class is of the following format _ lt ModuleName gt Values cs In this definition lt ModuleName gt would be replaced with the name of the ASN 1 module in which the values are defined For each Information Object defined within a specification a C constant is generated which is an instance of the ASN 1 CLASS definition for the object Each Informa
54. System IO FileMode Create messagedmp AutoFlush true ncodeBuffer HexDump messagedmp catch Exception e System Console Out WriteLine e Message AsnlUtil WriteStackTrace e Console Error return Reuse of C Encoding Objects The simple example above showed the procedure to encode a single record But what if you had to decode a series of the same record over and over again This is a common occurrence in a BER encoding application You would not want to recreate the data holder and message buffer objects on each pass of the loop This would have an adverse effect on the performance of the application What you would want to do is only create the objects a single time and then reuse them to encode each message instance It turns out that this is an easy thing to do The public member variable access to the data holder object makes it easy to change the variables on each given pass And the encode buffer object contains a Reset method for resetting the encode buffer for subsequent encodings The use of this method has the advantage of not releasing any of the memory that had been accumulated to this point for previous encodings To show an example of object reuse suppose we were going to encode a series of names The ASN 1 type for the names would be as follows Name APPLICATION 1 IMPLICIT SEQUENCE givenNamelA5String initial IA5String familyNamelA5String 7 na The ge
55. Value declared in the base class BIT STRING The ASN 1 BIT STRING type is converted to a C class that inherits the Asn BitString run time class This base class encapsulates the following two public member variables public int numbits public byte mValue These describe the bit string to be encoded or decoded The following shows the basic mapping from ASN 1 type to C class definition ASN 1 Production lt name gt BIT STRING Generated C class public class lt name gt AsniBitString public lt name gt base 38 Generated C class public class lt name gt AsnlInteger public lt name gt base public lt name gt long value_ base value_ ASN 1 Type to C Class Mappings public lt name gt int numbits_ byte data base numbits_ data public lt name gt bool bitValues base bitValues public lt name gt string value_ base value_ This shows the class generated for a simple BIT STRING assignment If a tagged or constrained type is specified specific encode and decode methods will be generated as well The constructors generated for this type provide additional options for populating the member variables in the base class In addition to passing the string using the numbits and data arguments to specify a bit string in native format the string can be specified as an array of boolean values or as a s
56. a might be Data SEQUENCE first OCTET STRING second OCTET STRING third OCTET STRING The generated C class would contain public member variables for each of the octet strings public AsnlOctetString first public AsnlOctetString second public AsnlOctetString third The most efficient way to repopulate these variables within a loop would be simply to assign the data to be encoded to the public mValue field of the Asn OctetString objects You do not need to create new Asn1OctetString or Data objects each time A code snippet showing how this could be done is as follows Step 1 Create Data and AsnlMderOutputStream objects for use in the loop Data data new Data null null null creates empty octet string objects AsnlMderOutputStream encodeStream new AsnlMderO0utputStream outputStream FOr CPR A logic here to read name components from a DB or other medium populate octet strings assume first second third are byte arrays populated by the above logic 90 Generated MDER Encode Methods data first mValue first data second mValue second data third mValue third encode try name Encode encodeStream useCachedLength false perhaps write some non ASN 1 data to the stream catch AsnlException e handle error 91 Chapter 11 Generated MDER Decode Methods For each ASN 1 production defined in the ASN
57. a standard class within an XML parser that reads and parses an XML document The input source can either be a URI this can be a local filename or an in memory byte stream Encode Method The generated encode method for BER DER has the following general form public override int Encode AsnlBerEncodeBuffer buffer bool explicitTagging The Asn BerEncodeBuffer argument specifies the buffer into which the message will be encoded The explicitTagging argument is primarily for use by the compiler for generating internal calls to handle implicitly tagged elements in constructed types Users should always set this argument to t rue The encode method returns the length of the encoded component Unlike the C C version this return value does not double as a status value as well Any errors that occur in the encode process are reported by throwing an ASNIC exception A complete list of these exceptions can be found in the ASN1C Exceptions section 34 Generated C Source Code Overview The general form of a PER encode method is as follows public override void Encode AsnlPerEncodeBuffer buffer In this case the explicitTagging argument is not required since PER has no tagging The only required argument is a reference to an encode buffer object Also note that the return value is void instead of int No intermediate lengths are returned during the encoding of a PER message Any errors that occur are reported as an excep
58. add any extra code to check for these values so the parameter can be discarded After processing the Information Object Class references within the construct refer to the Information Objects section for information on how this is done the reduced definition for ProtocollE Field becomes the following ProtocolIE Field SEQUENCE id ProtocollIE ID criticality Criticality value ASN 1 OPEN TYPE References to the field are simply replaced with a reference to the generated ProtocolID Field class 55 ASN 1 Type to C Class Mappings Value Specifications The ASNIC compiler can parse any type of ASN 1 value specification however the basic version will only generate code for the following types of value specifications e BOOLEAN e INTEGER e ENUMERATED e Binary String e Hexadecimal String e Character String e OBJECT IDENTIFER The Pro version of the compiler will generate code for the following remaining types of value specifications e Enumerated e Real e Sequence e Set Sequence Of e Set Of e Choice If any of the above types of value specifications are detected in an ASN 1 module the compiler will generate a CH source file with a special class to hold the values The name of the source file and class is of the following format _ lt ModuleName gt Values In this definition lt ModuleName gt would be replaced with the name of the ASN 1 module in which the values are defi
59. aeeeeeeeeeeeseaeeeaeeeaes 61 Memory buffer Based Definite Length Encoders oocccoocccnnccnonccnnnccnonocnnnnccnnccnnnnccnnnrcnonccnnnncinnocnnnn 61 Generated C Method Format and Calling Parameter ccccceecnee nee e nsec eece ten eeneeeneeenees 61 Populating Generated Variables for Encoding oooonnnncnncnnnccnnccnnnonncnnncnnncnnnconrnnnrnnnrnnncnronirnnn 62 Procedure for Calling Memory Buffer Based BER Encode Methods n 62 Reuse Of CF DO TR TAN doesn ENEE EEE aeeu sen vote de os oem deeb EE TEE EEES EEEE 64 Stream Oriented Indefinite Length Encode Methods ooooocccccnnccnnccnocnnccnnconnconnccnnconnconnconncnnncnnannnronoss 65 Generated C Method Format and Calling Parameter cccccee cece cneeenee cece ten eeneeeueeenees 66 Procedure for Calling C BER Stream Oriented Encode Methods n 66 6 Generated BER DER CER Decode Methods 0 0 0c cece cece cece cece neceneceneceeeeeeeeeeeeeeseaeseaeeas seas eeae esas 68 Generated C Method Format and Calling Parameters 2 002 000 0000 cee cece cece eee ce eeca cece cece eene cea eeneeenneeneees 68 Procedure for Calling C BER Decode Methods 00 cee ciee cece ceeeceece teen teen eeca cena cena een eeneeeeeeeees 68 R usecot C Decoding Objects o ish ee ee A ere Mee Eee Eee N 69 T Generated PER Encode Methods rei sassss ydeces vis ce e EEE E E ROE Dispones reno a geese 71 Generated C Method Format and Calling Parameters coooconccnnccnnccnncnnncnnornnccnnconn
60. ail to accept some valid encodings This is a result of the encoder s options which can produce mixed content models and XML Schema s limited abilities to constrain mixed content models Working with generated EXTENDED XER code As noted above when generating code for EXTENDED XER you will be working with the XML runtime as oppposed to the XER runtime This makes coding for EXTENDED XER slightly different from coding for XER You will use Asn XmlEncoder instead of AsnlXerEncoder e You will supply the name of the element when encoding a value Typically this will be the name of the ASN 1 PDU type Finally there is a sample reader and writer program in csharp sample_xer EmployeeEXER should you need to see an example Generated Encode Methods The generation of methods to encode data in XML is similar to how methods were generated in the BER DER and PER cases discussed previously For each ASN 1 production defined in the ASN 1 source file a C encode method may be generated This function will convert a populated variable of the given type into an encoded ASN 1 message An encode method is only generated if it is required to alter the encoding of the base class method The C model is built on inheritance from a set of common run time base classes These run time classes contain default implementations of encode decode methods that handle the encoding decoding of the basic types For simple assignments the gener
61. any valid content to be present in that position in an XML document However an ASN 1 open type is not used to model an lt xsd any gt Instead a character string variable is used This stores the full XML text of the field in native XML form i e angle brackets and the like are not escaped Note that the XML text is not converted to different form when using binary encoding rules it is maintained as XML text External Type The ASN 1 EXTERNAL type is a useful type used to include non ASN 1 or other data within an ASN 1 encoded message The type is described using the following ASN 1 SEQUENCE EXTERNAL UNIVERSAL 8 IMPLICIT SEQUENCE direct reference OBJECT IDENTIFIER OPTIONAL indirect reference INTEGER OPTIONAL data value descriptor ObjectDescriptor OPTIONAL encoding CHOICE single ASN1 type 0 ANY octet aligned 1 IMPLICIT OCTET STRING arbitrary 2 IMPLICIT BIT STRING 53 ASN 1 Type to C Class Mappings The ASN 1 compiler is used to create a meta definition for this structure The definition will be generated in the file AsnlExternal cs or Asn1XerExternal cs for XER if needed by compiling ASN 1 file An object created from the resulting C class is populated just like any other compiler generated structure for working with ASN 1 data EmbeddedPDV Type The ASN 1 EMBEDDED PDV type is a useful type used to include non ASN 1 or other data withi
62. ary dump encodeBuffer BinDump catch Exception e System Console Out WriteLine e Message Asnl return finally Step 3 try if outs catch outs Close Exception e Util WriteStackTrace e null O O Console Error Close the output stream if opened If you compare this example with the BER encoding example in Figure 1 you will see the encoding procedure is almost identical This makes it very easy to switch encoding methods should the need arise All you need to do is change Asn1BerEncodeBuffer to Asn BerOutputStream and remove the explicit code that writes the messages into the stream Also closing of the stream should be added 67 Chapter 6 Generated BER DER CER Decode Methods For each ASN 1 production defined in the ASN 1 source file a C decode method may be generated This method will decode an ASN 1 message into public member variables within the C object As was the case for encode methods a decode method is only generated if it is required to alter the default method in the base class The C model is built on inheritance from a set of common run time base classes These run time classes contain default implementations of encode decode methods that handle the encoding decoding of the basic types These default implementations include support for handling the universal tags associated with the types as defined in the X 680 standard
63. as a file network or memory stream The ASNIC compiler has the stream option to generate encode functions of this type For each ASN 1 production defined in the ASN 1 source file a C encode method may be generated This function will convert a populated variable of the given type into an encoded ASN 1 message The basic principles of the generation of the encode methods are the same as for the memory buffer based BER DER encode methods described in the preceding section Stream oriented BER encoding starts from the beginning 65 Generated BER DER CER Encode Methods of the message until the message is complete This is sometimes referred to as forward encoding This differs from memorybuffer based BER where encoding that is done from back to front Indefinite lengths are used for all constructed elements in the message Also there is no permanent buffer for stream oriented encoding all octets are written directly to the output stream Generated C Method Format and Calling Parameters The signature for a C BER stream oriented encode method is as follows public override void Encode AsnlBerOutputStream outs bool explicitTagging The outs argument is a reference of an Asn BerOutputStream object that describes the output stream into which a message is being encoded This must be created and initialized before calling any encode method See the description of this class in the C Run Time Classes section for details on ho
64. ation of an encode method is not necessary For example the following production will not result in the generation of an encode method X INTEGER In this case the generated C class extends the AsnJ Integer base class and the default encode method within this class is sufficient to encode a value of the generated type 80 Generated XML Methods A custom encode method is only generated if 1 The ASN 1 type is constructed SEQUENCE SET SEQUENCE OF SET OF or CHOICE 2 The ASN 1 type contains a testable constraint for example INTEGER 1 100 3 The ASN 1 type is enumerated This includes an INTEGER type with named numbers a BIT STRING with named bit constants or the ENUMERATED built in type Note Two variations are discussed here XER and XML The XML variant applies to EXTENDED XER See the Overview section above for more information Generated C Method Format and Calling Parameters The signature for a C XER encode method is as follows public override void Encode AsnlXerEncoder buffer string elemName The signature for a C XML encode method is similar public override void Encode AsnlXmlEncoder buffer string elemName The buffer argument is a reference to an AsnlXerEncoder or Asn XmlEncoder derived object that describes the buffer or output stream into which a message is to be encoded Asn XerEncoder is a base interface for the AsnlXerEncodeBuffer and Asn1XerOutputStream
65. b ed EEE EENE E E EEES E o STE 41 ALOS D EE E E EEE E E Seve ot 42 OBJECT IDENTIFIER cit E e eld cdots a a enon 42 RELATIVE OID 2d 43 READ lt A A AAA EEE il 43 AN 28 nds toes is acess ess eaaeo REEE REEE EEE sous EEEIEE ESSER EARO eden veh sucmh ed poeneendssercengsaeoea ashe 43 SEQUENCE iii is a 44 Creation of Temporary Types ainia aer crap e paves ea Raga se PONE TRE 45 OPTIONAL Keyword oesie eoten Bast o a sd Mined A IA SEAS 46 DEFAULT Keyword A ssesgsens EEEE TEPAS cand ods sasedecesaagyseovssadardeassads seswabvessdanssatesd 46 EXTENSION Elements A noes E Sees 47 XSD lt xsd all gt Type Mapping oct ito Sates sa rio teta ewes tanieweetss 47 SED EE Sai Seed ee ein es abe Hee AE Sis be esd we Seay 47 SEQUENCE OB 32 ctacedee totes g foe stae dees acs ese ade teach ag Secs See dogs ropa T 48 Generation of Temporary Types for SEQUENCE OF Elements o oo 48 SEQUENCE OF Type Elements in Other Constructed Types 11 cseccsecceecc ence eeceeeeeeseeeseaeeanes 49 SET OP ar Ei tU 50 CHOICE comes eri ones rodea wobec due lirica 50 Creation of Temporary Types ooooonccnoccnnccnncnnnconononncnnnrnnnnnnnnnnronnrnnnrnn cono EE RE in s oee 51 Populating Generated Choice Structures for Encoding oooonnnnccnnccnnccnnconncononnnacnnacnnnnnnnnnnrnnnrnnn 51 Accessing the Choice Element Value after Decoding oooonncnncinnccnnccnncnnnconacnnacnnarnnncnnncnaranacnnos 52 XSD lt xsd union gt Type Mapping sscnissovcsesss voces ss einioes i ai ori
66. bersome for setting values in deeply nested constructed types A default constructor is then generated followed by overloaded constructors for setting the element values The first form is simply a direct mapping of each of the element types to a constructor argument The second form only contains arguments for the required types in the SEQUENCE i e OPTIONAL and DEFAULT elements are omitted The third form uses the base type of each of the elements as the type for each argument This makes it possible to construct a SEQUENCE or SET using literal variables instead of always having to create an object Finally another variant of this constructor with primitive types is generated for required elements only It is possible that you will not see all of these variations in a given generated class It depends on a whether or not the SEQUENCE or SET contains optional items and b whether or not it contains primitive data items For example the following shows how a variable of a generated class containing two IA5String elements could be constructed vl new HelloWorld hello world Without this second form of constructor the following would need to be done vl new HelloWorld new AsnlIA5String hello new AsnilIA5String world Also note that since all member variables are public it is not necessary to use any of the argument based constructors at all A variable can be created using the default constructor and each of
67. can look at the following definition from the UDP MIB udpInDatagrams OBJECT TYPE SYNTAX Counter32 MAX ACCESS read only STATUS current DESCRIPTION The total number of UDP datagrams delivered to UDP users udp 1 In this case a type definition is generated for the SYNTAX element and an Object Identifier value is generated for the entire item The name used for the type definition is lt name gt _SYNTAX where lt name gt would be replaced with the OBJECT TYPE name i e udpInDatagrams The name used for the Object Identifier value constant is the OBJECTTYPE name So for the above definitions the following two C items would be generated 1 A udpInDatagrams_SYNTAX cs file This would contain the udpInDatagrams_SYNTAX class definition and 2 AudpInDatagrams value definition in the UDP_MIB Values class 121
68. cneencceececeeeeseceeaeeeeeaeeceeaeeesaneeesaseeeeeeeesaneeesenes 101 Additional Code Generated for the tables Option oooconnconcconccnnccnnnnnnnnnnnnnnrnnarnnncnnccnnccnnocnno 101 Populating OpenType Variables for Encoding occcoccnnccnoconcconoconoconocnncnnnrnnncnnconnccnnccnnconnconnconncnnnos 103 Decoding Types with Table Constraints is soson sooie nes irop iror ER EE ARS pE eens pE EEE EEP SSN 105 13 Generated Print Methods ens nse nd id EE ate hing EON 106 Generated C Method Format and Calling Parameters oooccoccnnccnnccnnccnnccnnconnconoconncnnncnnncnnccnnroninnnos 106 14 Generated Makefile ii A ai oases 108 153 Event Handler Interface conidios at flia gre ARE EEEN ASER 109 HOW At Works sui iS is He Russ teksts te ot io 109 Howto Use O 110 Example 1 A Formatted Print Handler ccc cece cece cece nec cece cece ee ance nooo naco nncnnnrnnncnnncnnss 110 Ex mple 2 An XML Converter Class eor eeann yo e ee E Ripa cra tne TEE EIEE N bread 112 16 IMPORT EXPORT of Ty pes ics oa tei seg is vce Sale on E PR aah eee aaa Ri ae 116 17 Compact Cod Generations senin ean sates iii des era 117 RS A A E EA ES 118 ROSE OPERATION and ERROR oc eserecusess roots se teaguens Sees liebe delicias 118 SNMP OBJECT TYPE v e n e ii 121 Chapter 1 Overview of ASN1C for C The ASNIC code generation tool translates an Abstract Syntax Notation 1 ASN 1 or XML Schema Definitions XSD source file into computer language s
69. coded This is similar to the context variable in the C version of the product The explicitTagging and implicitLength arguments should be of no concern to the average user The explicitTagging argument should be set to t rue and the implicitLength argument set to zero These arguments are only used in internal calls generated by the compiler when implicit tagging is used In this case the decoder will at times only be concerned with decoding the contents of a field and not the tag information At the outer levels it will always be necessary to decode a tag and length The C decode method reports errors by throwing exceptions This is a change from the C C version that returned a status value The Asn Exception class is the base class for all exceptions defined for ASNIC A complete list of these exceptions can be found in the ASN1C Exceptions section For PER the signature is similar public override void Decode AsnlPerDecodeBuffer buffer In this case the explicitTagging and implicitLength arguments are not required since PER has no tagging The only required argument is a reference to a decode buffer object For XER two overloaded decode methods are generated public override void Decode System Object reader string xmlURI public override void Decode System Object reader Stream byteStream These take as arguments an XML reader object reference and a reference to an input source object The XML reader object is
70. connconnccnnccnncnnncnnncos 71 Procedure for Calling C PER Encode Methods ooooccnoconoconcconccnnonnncnnnconoronocnnconnconnccnnccnnccnnconncnnncos 72 Reuse of C Encoding Objects elsa ri ar aia ewes dade elm eee 73 S Generated PER Decode Methods nisser ceneno p n vadeeopauwaesspeseadiens vuadsephwedgvstheunessneseesneb wens 75 Generated C Method Format and Calling Parameters coooconocnnccnnccnncnnncnnocnnccnn cono connconnconnconnconncnnncos 75 Procedure for Calling C PER Decode Methods oocoooccnnconcoconcconcconocnncnnncnnnronccnnccnnccnnccnnccnnconncnnncnnnes 75 Reuse of C Decoding Ob ects tit A EERS E ESN ET 76 9 Generated XML Method os sss ceu circa ton E E soastes ptueeesy eed edapanwedss pees NE RS EENE NEE 78 OVNEN a A oor Mia cu debian E A ii 78 Differences between OSys XER and XER BASIC XER ocoocooccnccoconcnoconcnoconcnoroncnoroncnaroncnaronos 78 EXTENDED XER e r EAE Ea ocn 79 Generated Encode Methods srs e E E E N E EE SE tess ds 80 Generated C Method Format and Calling Parameters coooccnccnnccnncnnnconocnnccnnconnccnnccnnconaconicinoss 81 Procedure for Calling C XER Encode Methods ocoooccccccccnnccnnconnconncnnnccnnconncnnncnnncnnncnaronacnnos 81 Generated Decode Methods tia A AA i 85 10 Generated MDER Encode Methods sesir onts a a e ERE E E N E EEE 88 Generated Method Format and Calling Parameters sseesseeessuerrssreereresrrrersrerrsrrerrrrrerrreerrereerreees 88 Populating Generated Var
71. d For decoding the logic is reversed The normal decode logic is performed first to populate the standard and open type fields in the generated structure After that the CheckTC method is invoked to perform the following table constraint checks Relative Table Constraint 1 The table constraint key is searched in the object set array to find the class object for the data in the populated type variable to be encoded 102 Table Constraint Processing 2 If the key element value is NOT found and the table constraint object set is extensible the CheckTC method will do no further processing i e a value field match will not be performed and the variable type fields will be stored as open types i e as instances of C Asn OpenType classes The user will be responsible for further decoding of the open type value 3 If the key element value is found the CheckTC method will verify all fixed type values match what is defined in the key row of the object set and will fully decode all type fields according to the key row type and store the resulting decoded type in the ASN Type fields 4 If the key element value is NOT found in the table or object set and the object set is NOT extensible then a table constraint violation exception will be thrown Simple Table Constraint 1 This function will verify all the fixed type values match what is defined in the table constraint object set If an element value does not exist in the table
72. default value in the ASN 1 CLASS s ValueField and Type is the type in the ASN 1 CLASS s ValueField This value is used as a defined value in the information object definition for an absent value of the field This new value assignment is used for compiler internal code generation purpose It is not designed for use by the end user ABSTRACT SYNTAX class The ASN 1 ABSTRACT SYNTAX class is a useful class definition used to declare the top level protocol data units PDU s defined within a specification The class is described using the following ASN 1 definition ABSTRACT SYNTAX CLASS amp id OBJECT IDENTIFIER UNIQUE amp Type property BIT STRING handles invalid encoding 0 DEFAULT WITH SYNTAX amp Type IDENTIFIED BY amp id HAS PROPERTY amp property 96 Table Constraint Processing ASNIC is used to create a meta definition for this structure The definition will be generated in the file AsnlAbstractSyntax cs or Asn XerAbstractSyntax cs for XER if needed by compiling ASN 1 definitions An object created from the resulting C class is populated just like any other compiler generated structure for working with ASN 1 data TYPE IDENTIFIER class The ASN 1 TYPE IDENTIFIER class is a useful class definition for uniquely identifying typed data at runtime The class is described using the following ASN 1 definition TYPE IDENTIFIER CLASS amp id OBJECT IDENTIFIE
73. e 1 Add events to your asnlc command line This is necessary for element name tracking to work 2 Obtain an Asn1Context object from your encode decode buffer using Asn1MessageBuffer Context 3 Enable element name tracking before encoding decoding by invoking Asn1Context EnableElementTracking 4 Get the name of the problem element by invoking Asn1Context GetCurrentElement inside your exception handling code Element name tracking is demonstrated in the sample Writer in sample_ber EventHandler 36 Chapter 4 ASN 1 Type to C Class Mappings The following sections discuss the specific mappings of ASN 1 and XSD types to C classes BOOLEAN The ASN 1 BOOLEAN type is converted to a CF class that inherits the Asn Boolean run time class This base class encapsulates the following public member variable public bool mValue This is where the Boolean value to be encoded is stored It also contains the result of a decode operation Since it is public it can be accessed directly to get or set the value The generated constructors can also be used to set the value The following shows the basic mapping from ASN 1 type to C class definition ASN 1 Production lt name gt BOOLEAN XSD Type lt xsd boolean gt Generated C class public class lt name gt AsnlBoolean public lt name gt base public lt name gt bool value_ base value_ This definition assumes a simpl
74. e assignment of the form lt name gt BOOLEAN i e no tagging or subtypes have been added to the BOOLEAN declaration In this case no specific encode or decode methods are generated calls to these methods pass through to the generic calls defined in the base class This is true of all other primitive type declarations as well unless otherwise noted INTEGER The ASN 1 INTEGER type is converted to a C class that inherits the AsnJInteger run time class This base class encapsulates the following public member variable public long mValue This is where the integer value to be encoded is stored It also contains the result of a decode operation Since it is public it can be accessed directly to get or set the value The generated constructors can also be used to set the value The following shows the basic mapping from ASN 1 type to C class definition ASN 1 Production lt name gt INTEGER XSD Types lt xsd integer gt lt xsd byte gt lt xsd short gt lt xsd int gt lt xsd long gt lt xsd unsignedByte gt lt xsd unsignedShort gt lt xsd unsignediInt gt lt xsd unsignedLong gt lt xsd positi1 lt xsd nonPositivelnt gt lt xsd negativelInt gt lt xsd nonNegativelnt gt 37 ASN 1 Type to C Class Mappings This shows the class generated for a simple INTEGER assignment If a tagged or constrained type is specified specific encode and decode
75. e data members Example As an example consider the following ASN 1 class definition ATTRIBUTE CLASS amp Type amp id OBJECT IDENTIFIER UNIQUE WITH SYNTAX WITH SYNTAX Type ID amp id A file named ATTRIBUTE cs is generated with following definition public class ATTRIBUTE public AsnlType Type public AsnlObjectIdentifier id public ATTRIBUTE Type null id null public ATTRIBUTE AsnlType Type_ AsnlObjectIdentifier id_ Type Type_ id id_ NOTE If the ASN 1 type name is same as the ASN 1 class name ignoring case in a single module definition then the ASN 1 class name will be changed to the following lt ClassName gt _CLASS In this definition lt ClassName gt would be replaced with the name of the ASN 1 CLASS and the literal token _CLASS would be appended For example Test DEFINITION BEGIN 95 Table Constraint Processing Attribute INTEGER ATTRIBUTE ABSTRACT SYNTAX END ASNIC will change the ATTRIBUTE class name to ATTRIBUTE_CLASS to avoid conflicts with the Attribute type This automated feature will help users to successfully compile the generated code without having to manually change the name via a configuration file setting Additional C classes are generated to create types for fields within the class definitions as follows 1 New type assignments are created for TypeField ty
76. e is converted to a Java class that extends the Asn Real 0 run time class A base 10 real is specified in ASN 1 using a WITH COMPONENTS clause such as the following REAL WITH COMPONENTS base 10 It is also used for XSD decimal type specifications In this case the real number is stored as a C character string in the character string base class public String mValue ASN 1 Production lt name gt REAL WITH COMPONENTS basg 10 43 ASN 1 Type to C Class Mappings XSD Types lt xsd decimal gt Generated C class public class lt name gt AsnlReal10 public lt name gt base public lt name gt String value_ base value_ SEQUENCE The ASN 1 SEQUENCE type is converted to a CF class that inherits the Asn Type run time base class Public member variables are generated for each of the elements defined in the SEQUENCE Each of these member variables represents an object reference since all of the ASN 1 types are mapped to C objects ASN 1 Production lt name gt SEQUENCE lt elementl name gt lt elementl type gt lt element2 name gt lt element2 type gt XSD Types lt xsd sequence gt lt xsd all gt Generated C class public class lt name gt AsnlType public lt typel gt lt el mentl name gt public lt type2 gt lt el ment2 name gt public lt name gt
77. e runtimes is used so that you know which cases apply to you When it comes to decoding there is no difference the generated decoders use SAX Simple API for XML for parsing Note that you may use the xsd switch when generating XML encoders and decoders The XML schema produced from the ASN 1 specification using the xsd switch can be used to validate the XML messages generated using the XML encode functions Similarly an XML instance can be validated using the generated XML schema prior to decoding Compiler Invocation What is Generated xer flag is used to compile ASN 1 without XER encoding Generated code supports BASIC XER and canonical XER instructions xsd produces schema that validates BASIC XER encodings xer or xml flag is used to comple ASN 1 with supported Generated code supports EXTENDED XER only XER encoding instructions Gf any instructions are not supported all instructions are ignored and the above entry XSd produces schema that validates EXTENDED XER in this table applies encodings As of this writing this is not fully supported xml used to compile ASN 1 Generated code suppports OSys XER encodings xsd produces schema that validates OSys XER encodings xml used to compile XSD Generated code supports EXTENDED XER only Differences between OSys XER and XER BASIC XER OSys XER differs from BASIC XER in the following ways e Lists of numbers enumerated tokens and named bits are exp
78. e that you have chosen the folder c mydocs temp as the location Next a small window appears that simply tells you that the wizard will now invoke the ASN1C GUI 17 Using the Compiler This wizard will now invoke the ASN1C GUI Use the GUI to choose your ASN1C options and then click the Compile button on the last screen When you click OK in this window the ASN1C GUI launches 18 Using the Compiler a ASI NI ASN1C1 acpro ASN1C Project Wizard E New Project 5 Open Project When the ASN1C GUI is invoked from the Visual Studio wizard the available options are more limited because the wizard instructs the GUI only to enable options that are relevant to the project In this window for example the options to create a new project or open an existing project are disabled When you click Next you are presented with the window that allows you to select the specification files that will be part of the code generation 19 Using the Compiler C mydocs temp ASN1C1 ASN1C1 Notice here that the option to specify an output directory is disabled this value is pre established by the Visual Studio wizard For purposes of this example let s assume that you specify employee asn as the file from which to generate code 20 Using the Compiler ASNIC ASNICL acpro Select Files and Directories ASN 1 XSD Files C mydocs temp employee asn When you click Next you
79. eclare that it throws an Asn Exception leaving it to be dealt with at a higher level Finally encode buffer methods can be called to access the encoded message component The C API provides an object called a ByteArrayInputStream that provides a way to look at the encoded component as a stream The encode buffer object provides a method called GetInputStream that returns a byte array input stream representing the message component This is the preferred way to access the encoded component In addition to GetInputStream there is a MsgCopy property that will retrieve a copy of the generated message into a byte array object This is somewhat slower because a copy needs to be done Another option that is only available when doing PER encoding is the Buffer property This returns a reference to the actual message buffer into which the message was encoded Since a PER message is encoded front to back unlike the back to front used in BER DER encoding the buffer reference returned will point to the start of the encoded message The MsgByteCnt property can then be used to get the message length in bytes or the MsgBitCnt property can be called to get the length in bits The encode buffer class also contains other methods for operating directly on the encoded component for example the write method can be used to write it to a file or other medium And of course one could derive their own special encode buffer class from this class to add more functionality
80. ecode message buffer is created using an input stream object that contains a series of messages for example a file containing multiple records or a 69 Generated BER DER CER Decode Methods communications device all that needs to be done is the continuous invocation of the BER decode method for the given message type Nothing special needs to be done to reuse the generated type object for decoding The decoder will automatically all the internal Jnit method before decoding to make sure all items are reset to their starting state In the example above all that would need to be done to decode a series of personnel records is the inclusion of a loop after the PersonnelRecord object was created in step 2 for 75 personnelRecord Decode decodeBuffer if trace System Console Out WriteLine Decode was successful personnelRecord Print personnelRecord 70 Chapter 7 Generated PER Encode Methods The generation of methods to encode data in accordance with the Packed Encoding Rules PER is similar to how methods were generated in the BER DER case discussed previously For each ASN 1 production defined in the ASN 1 source file a C encode method may be generated This function will convert a populated variable of the given type into an encoded ASN 1 message An encode method is only generated if it is required to alter the encoding of the base class method The C model is built on inheritance from a s
81. ecord object was previously populated with data AsnlXerOutputSteram outs null try Step 1 Create an output stream object This object uses standard XER non canonical and the default internal buffer s size outs new AsnlXerOutputStream new System 1I0 FileStream filename System IO FileMode Create Step 2 Invoke th ncode methods These include encodeStartDocument to encode the XML document header the generated C encode method to encode the document body and the encodeEndDocument method to complete the messag Note that these methods must be invoked from within a try catch block E outs EncodeStartDocument personnelRecord Encode outs null outs EncodeEndDocument if trace System Console Out WriteLine Encoding was successful encodeBuffer Write System Console OpenStandardOutput catch Exception e System Console Out WriteLine e Message AsnlUtil WriteStackTrace e Console Error return finally Step 3 Close the stream try if outs null outs Close 84 Generated XML Methods catch Exception e If you compare these examples with the other encoding examples you will see the procedures are similar This makes it very easy to switch encoding methods should the need arise In the case of XML encode the procedure is very similar The only dif
82. ed XSD 12 Using the Compiler XSD Generation Options E Generate Application Information Annotations Specify the Target XML Namespace 4 Reference Types in the asn1 xsd schema These options are described in Running ASNIC from the command line C Code Generation Options For information about code generation options for languages other than C please refer to the appropriate language manual or the online documentation The following window contains the C specific code generation options 13 Using the Compiler C Code Generation Options Code Organization Output code to directories based on module names dirs Code generation option File name Specify namespace namespace Specify namespace prefix nspfx Build Options Generate a list of cs files in lt modulename gt mk Generate a makefile genmake The options in this window allow users to change the way the generated code is organized and what files are generated to assist compiling the generated code Changing the code organization can be particularly helpful for using generated code with IDEs like Netbeans or Eclipse IDEs typically impose a directory structure for projects so ASNIC can try to organize code to conform to such a hierarchy A makefile may also be generated for use with nmake Separate files may also be created that contain a list of generated sources These options are detailed further
83. ed a variable called personnelRecord to hold a PersonnelRecord object the varName object would be set to personnelRecord The level argument is used to specify the indentation level for printing nested types The user would always want to set this to zero at the outer level The second signature exists in the Asn Type base class This provides a simplified interface for printing to standard output In this case the outs and level arguments are omitted public override void Print string varName The varName argument is same as in the first case above For example the call to print the personnelRecord from the previous examples would be as follows personnelRecord Print personnelRecord The output would be formatted as follows personnelRecord name givenName John initial P familyName Smith number 51 title Director dateOfHire 19710917 nameOfSpouse givenName Mary initial T familyName Smith 106 Generated Print Methods children 0 name givenName Ralph initial T familyName Smith dateOfBirth 19571111 children 1 name givenName Susan initial B familyName Jones dateOfBirth 19590717 107 Chapter 14 Generated Makefile The genmake option causes a makefile to be generated The makefile can be used to compile the generated source files to create the asnlapi dll library User can use the nma
84. edure for Calling Memory Buffer Based BER Encode Methods Once an object s member variables have been populated the object s encode method can be invoked to encode the value The general procedure to do this involves the following three steps 1 Create an encode message buffer object into which the value will be encoded 62 Generated BER DER CER Encode Methods 2 Invoke the encode method 3 Invoke encode message buffer methods to access the encoded message component The first step is the creation of an encode message buffer object Unlike the C C version of the product there is no choice to be made between a static or dynamic encode buffer In C everything is dynamic There are two forms of the constructor a default constructor and one that allows specification of a message buffer size increment The size increment will determine how often the buffer will need to be resized to hold large messages If you know that you will be encoding large messages then this object should be constructed with a large value for the increment If you know that you will be encoding small messages in a constrained environment then this value can be set very low The default constructor sets the value to a reasonable mid range value see SIZE_INCREMENT in Asn EncodeBuffer cs as of this writing the value was set to 1024 The second step is the invocation of the encode method The calling arguments were described earlier As per the C standard
85. efinition in a separate C source file containing a C class corresponding to the ASN 1 CLASS definition The name of the source file and class is of the following format lt ClassName gt cs In this definition lt ClassName gt would be replaced with the name of the ASN 1 CLASS for which this file is generated Data Member Generation For each of the following ASN 1 CLASS fields a corresponding member variable is generated in the C class definition For a value field public lt TypeName gt lt FieldName gt For a type field public AsniType lt FieldName gt For an information object field public lt ClassName gt lt FieldName gt For an information object set field public lt ClassName gt lt FieldName gt where 94 Table Constraint Processing lt FieldName gt is replaced with the name of the field lt TypeName gt is replaced with the generated runtime C classname for the ASN 1 Type lt ClassName gt is replaced with the name of the information object class For a type field definition an element with type Asn1 Type is generated which is the base class for all types in the C runtime namespace A type field can hold a value of any type Method and Constructor Generation Each generated C class will have two constructors The first constructor will be the default constructor This will initialize each member variable value to null The second constructor will accept values for all th
86. elD property can therefore be used to determine what type of choice element was received in a decode operation The ElemName property is generated by the compiler and returns the name of the selected element A series of Set_ lt element gt methods are generated for setting the element value In these declarations lt element gt would be replaced with the actual element names This is the only way an element value can be set for encoding these methods ensure a consistent setting of both the element identifier and object reference values To access the value of a generated CHOICE object the ChoicelD property and GetElement methods within the base class are used This is generally done with an if or switch statement as follows Asn1BMPString element if aliasAddress ChoiceID AliasAddress _H323_ID element Asn1BMPString aliasAddress GetElement In this case ChoiceID is invoked and the result tested to see if the expected value was received If it was the element is assigned using GetElement with a cast operation Creation of Temporary Types The rules for the generation of CHOICE temporary type variables are the same as they were for SEQUENCE and SET variables Complex nested types are pulled out of the definitions and used to create additional types to reduce the nesting levels An example of this is as follows TestChoice CHOICE a INTEGER b BOOLEAN c SEQUENCE aa IA5String bb NULL
87. en type holders to the generated structures These open type holders consist of a byte array for storing information on an encoded message fragment for processing at the next level The ASN1C compiler is capable of generating code in one of two forms for information in an object specification 1 Simple form in this form references to variable type fields within standard types are simply treated as open types and an open type placeholder is inserted 2 Table form in this form all of the classes objects and object sets within a specification result in the generation of code for parsing and formatting the information field references within standard type structures The second form is selected by specifying the tables command line option To better understand the support in this area the individual components of Information Object specifications are examined We begin with the CLASS specification that provides a schema for Information Object definitions A sample class specification is as follows OPERATION CLASS amp 0perationCode CHOICE local INTEGER global OBJECT IDENTIFIER sArgumentType amp ResultType amp Errors ERROR OPTIONAL Users familiar with ASN 1 will recognize this as a simplified definition of the ROSE OPERATION MACRO using the Information Object format When a class specification such as this is parsed information on its fields is maintained in memory for later refe
88. encoding and decoding functions are generated by the compiler If the target application does not require encoding or decoding capabilities for example if it is only intended to read messages and does not need to write them unchecking the corresponding checkbox will reduce the amount of code generated Check Stream to modify generated encode and decode functions to use streams instead of memory buffers This allows encoding and decoding to a source or sink such as a file or socket Stream based encoding and decoding cannot be combined with buffer based As an aid to debugging Print functions may also be generated Three different different types exist print to stdout print to string and print to stream These allow the contents of generated types to be printed to the standard output a string or a stream such as a file or socket Constraint checking may be relaxed or tightened depending on selected options Constraints may be ignored completely by checking Do not generate constraint checks To tighten constraints check Enable strict constraint checks ASN1C supports decoding and encoding values described by table constraints checking Generate code to handle table constraints will enable this behavior This option is a legacy option for C and C code generation generating table constraints in unions is the preferred method see the following section To reduce the code footprint several other options may be selected Generate compact code
89. er size generally provides better performance at the expense of increased memory consumption The first constructor sets the value to a reasonable mid range value The second step is the invocation of the Encode method The calling arguments were described earlier As per the CA standard this method must be invoked from within a try catch block to catch the possible Asn Exception and System Exception which may be thrown Alternatively the method from which the encode method is called can declare that it throws Asn1 Exception and System Exception leaving it to be dealt with at a higher level Finally close the output stream A complete example showing how to invoke a stream based encode method is as follows Note personnelRecord object was previously populated with data AsnlBerOutputStream outs null 66 Generated BER DER CER Encode Methods ey Step 1 Create an ou tput stream object default size increment for buffer expansion This object uses the outs new AsnlBerOutputStream new System 10 FileStream filename System 1I0 FileMode Create Step 2 Invoke th ncode method Note that it must be done from within a try catch block personnelRecord Encode outs true if trace System Console Out WriteLine Encoding was successful System Console Out WriteLine Hex dump of encoded record ncodeBuffer HexDump System Console Out WriteLine Bin
90. es 3 Indent System Console Out WriteLine lt name gt public void Characters string svalue short typeCode Indent string typeName new string AsnlType getTypeName typeCode typeName Replace _ System Console Out Write lt typeName gt System Console Out Write svalue System Console Out WriteLine lt typeName gt public void Finished System Console Out WriteLine lt mVarName gt private void Indent for int i 0 i lt mIndentSpaces i System Console Out Write This is very similar to the PrintHandler class defined earlier The StartElement method simply opens an XML element block public void StartElement string name int index Indent System Console Out WriteLine lt name gt mIndentSpaces 3 113 Event Handler Interface The EndElement method closes it public void EndElement string name int index mindentSpaces 3 Indent System Console Out WriteLine lt name gt The Characters method outputs the data with a type wrapper public void Characters string svalue short typeCode Indent string typeName new string AsnlType getTypeName typeCode typeName Replace _ System Console Out Write lt typeName gt System Console Out Write svalue System Console Out WriteLine lt
91. essage directly from a binary file Create an input file stream object System IO FileStream ins new System IO FileStreanm filename System IO FileMode Open System IO FileAccess Read Create a decode buffer object AsnlPerDecodeBuffer decodeBuffer new AsnlPerDecodeBuffer ins Step 2 create an object of the generated type and invoke the decode method PersonnelRecord personnelRecord new PersonnelRecord personnelRecord Decode decodeBuffer Step 3 process the data if trace System Console Out WriteLine Decode was successful personnelRecord Print personnelRecord catch Exception e System Console Out WriteLine e Message AsnlUtil WriteStackTrace e Console Error return Reuse of C Decoding Objects C objects can be reused for decoding PER messages in the same way they were for BER messages The decode buffer and message type objects are created outside of the main decoding loop Then in the main loop these objects are 76 Generated PER Decode Methods reused to process each input message Data must be saved from the message type object after each iteration because the contents of the object will be overwritten on each consecutive loop iteration Nothing special needs to be done at the bottom of the loop to ready the decoder for the next message All necessary initialization will be handled internally
92. et of common run time base classes These run time classes contain default implementations of encode decode methods that handle the encoding decoding of the basic types For simple assignments the generation of an encode method is not necessary For example the following production will not result in the generation of an encode method X INTEGER In this case the generated C class inherits the Asn Integer base class and the default encode method within this class is sufficient to encode a value of the generated type In the case of BER DER a custom encode method is generated if a the type is tagged or b it contains a testable constraint In the case of PER only the latter condition will cause a custom method to be generated The reason is because PER basically ignores the tags on tagged types and they therefore have no effect on the final encoded message component For example the following declaration will cause a custom encode method to be generated because the value range constraint is a PER visible constraint that will alter the encoding X INTEGER 1 255 In this case special logic is necessary to apply the value range constraint Some types will always cause encode methods to be generated At the primitive level this is true for the ENUMERATED type This type will always contain a custom set of enumerated values All constructed types SEQUENCE SET SEQUENCE SET OF and CHOICE will cause encode
93. ete X 208 standard with ROSE or SNMP macros XML Schema XSD E Lax Syntax Check Additional Translations Generate equivalent XML schema XSD file E Generate HTML files for input ASN 1 C Generate ASN 1 file based on X 694 XSD input only Application Language Type c C Java C None syntax check only Encoding Rules WM BER joer cer F PeR F xer xm Joer 5 mDER select aligned or unaligned PER at run time Code Options E Generate code for all dependent imported type definitions E Generate code compatible with compiler version Let s assume that you make no other selections and click Next until you come to the Compile screen If you look as you re clicking you ll see that the option to generate a Visual Studio project file is checked and can t be unchecked and the version of Visual Studio is 2008 which is the version you re using 23 Using the Compiler _ASNIC ASNICLacproj Compile Compilation Options Generate listing ist Show compilation warnings warnings Compilation command C lasnic_douglasn 1c dev bin asn ic C mydocsltemplemployee asn O C mydocs temp ASN1C 1 ASN1C 1 ber c vcproj 2008 At this point you would click the Compile button to do the code generation Once the generation is done you would click the Finish button Visual Studio then resumes control Since in this case the generated project is not part of a solutio
94. ference is that it is not necessary to call the EncodeStartDocument and EncodeEndDocument methods The are built into the generated encode method for PDU data types The resulting XML document from running the program above is as follows lt xml version 1 0 encoding UTF 8 gt lt PersonnelRecord gt lt name gt lt givenName gt John lt givenName gt lt initial gt P lt initial gt lt familyName gt Smith lt familyName gt lt name gt lt number gt 51 lt number gt lt title gt Director lt title gt lt dateOfHire gt 19710917 lt dateOfHire gt lt nameOfSpouse gt lt givenName gt Mary lt givenName gt lt initial gt T lt initial gt lt familyName gt Smith lt familyName gt lt nameOfSpouse gt lt children gt lt ChildInformation gt lt name gt lt givenName gt Ralph lt givenName gt lt initial gt T lt initial gt lt familyName gt Smith lt familyName gt lt name gt lt dateOfBirth gt 19571111 lt dateOfBirth gt lt ChildInformation gt lt ChildInformation gt lt name gt lt givenName gt Susan lt givenName gt lt initial gt B lt initial gt lt familyName gt Jones lt familyName gt lt name gt lt dateOfBirth gt 19590717 lt dateOfBirth gt lt ChildInformation gt lt children gt lt PersonnelRecord gt Generated Decode Methods The code generated to decode XML messages is different than that of the other encoding rules This is because off theshelf XML parser software i
95. file format Projects made with previous versions may be loaded with version 6 3 but new projects are incompatible with previous versions Additional metadata are stored in the project file to help with version tracking Files may be added to a project in the following window Using the Compiler Select Files and Directories ASN 1 XSD Files C acv630 cpp sample_ber employee employee asn Include Import Directories Configuration File s Browse Output Directory C acv630 cpp sample_ber employee Browse co In this window the ASN 1 file or files to be compiled are selected This is done by clicking the Add button on the right hand side of the top windows pane A file selection box will appear allowing you to select the ASN 1 or XSD files to be compiled Files can be removed from the pane by highlighting the entry and clicking the Remove button ASN 1 specifications and XML Schema Documents must not be compiled in the same project Once an asn file has been added no xsd files may be added Include directories are selected in a similar manner in the middle pane These are directories the compiler will search for import files By default the compiler looks for files in the current working directory with the name of the module being imported and extension asn or xsd Additional directories can be searched for these files by adding them here User defined configuration files are specified in the third
96. for any IO errors This method attempts to read data from an input stream using the methods in the System IO Stream Procedure for Calling C BER Decode Methods The general procedure to decode an ASN 1 BER message involves the following three steps 1 Create a decode message buffer object to describe the message to be decoded 2 Invoke the decode method 3 Process the decoded data values The first step is the creation of a decode message buffer object The Asn BerDecodeBuffer object contains constructors that can either accept a message as a byte array or as an I O input stream The input stream option makes it possible to decode messages directly from other mediums other than a memory buffer for example a message can be decoded directly from a file 68 Generated BER DER CER Decode Methods The Asn BerDecodeBuffer object contains a method called PeekTag that can be used to determine the outer level tag on a message This can be used to determine the type of message received in applications that must deal with multiple message types The final step is to process the data All data is contained within public member variables so access is quite easy And of course C has the distinct advantage of not requiring any clean up once you are done with the data The garbage collector will collect the unused memory when it is no longer referenced A complete example showing how to invoke a decode method is as follows ELY
97. for details on how this class is used The decode method returns no result Unlike the C C version a negative status value is not returned to indicate a failure That is handled by the exception mechanism All ASN1C C exceptions are derived from the Asn1 Exception base class See the section on exceptions for a complete list and description of the various ASN 1 exceptions that can be thrown The System Exception that can be thrown is in the read method within the decode buffer base class This method attempts to read data from an input stream using the methods in the System IO Stream class Procedure for Calling C PER Decode Methods The general procedure to decode an ASN 1 PER message involves the following three steps 1 Create a decode message buffer object to describe the message to be decoded 2 Invoke the decode method 3 Process the decoded data values The first step is the creation of a decode message buffer object The Asn PerDecodeBuffer object contains constructors that can either accept a message as a byte array or as an I O input stream The input stream option makes it possible to decode messages directly from other mediums other than a memory buffer for example a message can be decoded directly from a file or a socket Unlike BER or DER no mechanism exists in PER to peek at an outer level tag or identifier to identify the message type This type must be known beforehand Most protocols that employ PER have a specific oute
98. for inclusion in the final encoded message This element will be of type ASN OpenExt and have the name extElem1 This field will contain the complete encoding of any extension elements that may have been present in a message when it is decoded On subsequent encode of the type the extension fields will be copied into the new message If the SEQUENCE type contains an extension marker and extension elements then the open extension type field will not be added Instead the actual extension elements will be present These elements will be treated as optional elements whether they were declared that way or not The reason is because a version message could be received that does not contain the elements XSD lt xsd all gt Type Mapping As per the X 694 standard the XSD all type is mapped to an ASN 1 SEQUENCE type with a special element add named order This is added as a special element to the generated C class with the name _order This contains an index entry for each element that identifies the order elements are to be serilaized in when encoded in XML By default the array is initialized to encode the elements in the same order as specified in the type When an XML document of this type is decoded the order in which the elements are received in recorded in this array If the data is serialized out in binary form BER or PER the array is included in the encoding If is only transparent in XML encode decode operations to mimic the behavior of its
99. generate a common name for the new temporary type that can be used for other similar references The form of this common name is as follows _SeqOf lt elementProdName gt So instead of this SomePDU addresses SEQUENCE OF AliasAddress The following equivalent type would be generated _SeqOfAliasAddress SEQUENCE OF AliasAddress 49 ASN 1 Type to C Class Mappings The advantage is that the new type can now be easily reused if SEQUENCE OF AliasAddress is used in any other element declarations Note the illegal use of an underscore in the first position This is to ensure that no name collisions occur with other ASN 1 productions defined within the specification An example of the savings of this optimization can be found in H 225 The above element reference is repeated 25 different times in different places The result is the generation of one new temporary type that is referenced in 25 different places Without this optimization 25 unique types with the same definition would have been generated SET OF The ASN 1 SET OF type is converted into a C class that is identical to that for SEQUENCE OF as described in the previous section CHOICE The ASN 1 CHOICE type is converted to a CF class that inherits the Asn Choice run time base class This base class contains protected member variables to hold the choice element object and a selector value to specify which item in the CHOICE was chose
100. handling in XSD An example of how this is used might be a gateway application that read XML data and then translated to binary form for transmission over a low bandwidth network When received on the other end the receiving application would transcode back from binary to XML Suppose the item being transmitted was described using an xsd all type that had three elements a b and c When the original XML document was received by the sending application suppose the elements were received in the order c b a The order array would record this fact and it would be included in the binary serialization When the receiver decoded the message on the other end the order information would be available along with the element data The receiver could then reconstruct the XML document with the items in the same order as received SET The ASN 1 SET type is converted into a C class that is identical to that for SEQUENCE as described in the previous section The only difference between SEQUENCE and SET is that elements may be transmitted in any order in a SET whereas they must be in the defined order in a SEQUENCE The only impact this has on ASNIC is in the generated decoder for a SET type The decoder must take into account the possibility of out of order elements This is handled by using a loop to parse each element in the message Each time an item is parsed an internal mask bit within the decoder is set to indicate the element was received The complete
101. he GUI the project file will be created for you The wizard then loads the project file into your Visual Studio workspace To use the wizard follow these steps 15 Using the Compiler Edit the file ASNICWizard vsz in the vswizard folder of your ASNIC distribution with a text editor Make the customizations to the file that are noted in the comments at the top Take special note of the instruction to remove the comment lines as the wizard mechanism will not function if those lines remain in the file Copy the ASN1CWizard vsz file the ASN1CWizard vsdir file and the ASN1CWizard ico file to the VC CSharpProjects folder of your Visual Studio installation e g C Program Files x86 Microsoft Visual Studio 8 VC CSharpProjects The wizard can then be invoked by clicking Visual C from the Visual Studio New Project dialog and then choosing ASNIC as the project template For example let s assume you want to use the Visual Studio Wizard to work with code generated from the employee asn file which is included in numerous samples provided with ASNIC The first step is to edit the ASN1CWizard vsz file Below is a typical ASN1CWizard vsz file as furnished with an ASNIC kit version 6 5 0 in this example T hese comment typ T lines must be removed in order for this O The OSROOT installation variable then as long as that defini of OSROOTDIR in this file can be removed this file and as a Windows envi
102. his point that we got a login invoke request 119 ASN1C90 2 Based on the information from step 1 the ROSE layer would know that the Open Type field contains a pointer and length to an encoded Login ARGUMENT component It would then route this information to the appropriate processor within the Application Layer for handling this type of message 3 The Application Layer would call the specific decoder associated with the Login ARGUMENT It would then have available to it the username password the user is logging in with It could then do whatever application specific processing is required with this information database lookup etc 4 Finally the Application Layer would begin the encoding process again in order to send back a Result or Error message to the Login Request A picture showing this is as follows Application Layer Call specific function to decode Login ARGUMENT and process data A Encoded message pointer and length Decode ROSE header message structure Invoke Open type structure contains message pointer and length of encoded Login_ARGUMENT A Encoded ROSE message The login OPERATION also contains references to ERROR definitions These are defined using a separate MACRO that is built into the compiler The definition of this MACRO is as follows ROSE Layer ERROR MACRO BEGIN TYPE NOTATION Parameter VALUE NOTATION value VALUE INTEGER Parameter
103. hods are added to an inner SAX handler class generated for each ASN 1 production The procedure to invoke the generated decode method is as follows 1 Instantiate an Xm SaxParser object 2 Instantiate a generated C lt ProdName gt object to hold the decoded message data 86 Generated XML Methods 3 Invoke the lt ProdName gt object decode method passing the reader created in step 1 and the URI of the XML document to be parsed This method initiates and invokes the XML parser s parse method to parse the document This in turn invokes the generated SAX handler methods 4 Methods within the lt ProdName gt object can now be used to access the decoded data The member variables that were declared to be public can be accessed directly 5 Error handling is accomplished using a try catch block to catch SAX exceptions A program fragment that could be used to decode an employee record is as follows public class Reader public static void main string args string filename employee xml try Create an XML reader object XmlSaxParser reader XmlSaxParser NewInstance Read and decode the messag PersonnelRecord personnelRecord new PersonnelRecord personnelRecord Decode reader filename if trace System Console Out WriteLine Decode was successful personnelRecord Print personnelRecord catch Exception e System Console Out WriteLine e Mes
104. iables for Encoding oooccoooccnnoccnonccnnnnccnnncnnnnconnnncnonccnnnnccnnnrnnnnccnnnnccnnicnns 88 Procedure for Calling MDER Encode Methods ooccoccocccnccnnccnnccnnconnccnnccnnconnconnconncnnnrnnncnnrcnnrcnncnnns 89 Reuse of Encoding Objects errea e e E SNE cep E E E EREE 90 11 Generated MDER Decode Methods inrsin a di i n 92 iv ASNIC Generated Method Format and Calling Parameters 2 0 0 0 ccc cece ceee cece cece cece ee ee een ceneeeeeeeeeeeeeeaeseaees 92 Procedure for Calling MDER Decode Methods oooocccccccccccccnocnnccnnccnnconnccnnconnconnconnnnnncnnncnnncnaronirnnos 92 Reusecof Decoding Objects merienn e aa E a a A a e eE a Ea aE 93 12 Table Constraint Processing iii a si id di E E ES 94 CLASS Specification ae n ea n a a E a E e A a EEA E EE Eaa 94 Data Member Gener dt A E vote id io 94 Method and Constructor Generation oocooccocnncnoconcnonononanononnrononnnononnrononnrononnrononnroncnnronennronos 95 ABSTRACT SYNTAX CIGSS ed 96 TYPEIDENTIFIER clas plas ieee 97 Information Object i loa ds kos ee Jap as eg nea E id 97 Information Object Setren aena Sacithe ses gevete a thee shee een ydeedba cade ae a E A E E edo gaueddesarvedaneed 98 Generated Information Object Table Structure 20 0 0 cece cece cece ence ence eeceeeseeeeaeeea esau seen sean eeue esas 99 Simple Form Code Generation ooo e seseiesevseovy seins ocasione reee bp Seba pu wed refe ETSE eet 100 Table Form Code Generation ccccccccceecnecne
105. ic Name toBeSigned public AsnlObjectIdentifier algorithmOID public Params paramS public Asn1BitString signature When processing parameterized type definitions ASNIC will first look to see if the parameters are actually used in the final generated code If not they will simply be discarded and the parameterized type converted to a normal type reference For example when used with information objects parameterized types are frequently used to pass information object set definitions to impose table constraints on the final type Since table constraints do not affect the code that is generated by the compiler the parameterized type definition is reduced to a normal type definition and references to it are handled in the same way as defined type references This can lead to a significant reduction in generated code in cases where a parameterized type is referenced over and over again For example consider the following often repeated pattern from the UMTS 3GPP specs ProtocolIE Field RANAP PROTOCOL IES IEsSetParam SEQUENCE id RANAP PROTOCOL TIES id IEsSetParam criticality RANAP PROTOCOL IES criticality IEsSetParam id value RANAP PROTOCOL IES amp Value IEsSetParam id In this case JEsSetParam refers to an information object set specification that constrains the values that are passed for any given instance of a type referencing a ProtocollE Field The compiler does not
106. imal String Value Specification This value specification causes a C constant to be generated containing a byte array of the hexadecimal byte values ASN 1 production lt name gt OCTET STRING hhhhhh H Generated C constants public static readonly byte lt name gt Oxhh Oxhh In the ASN 1 production definition the lowercase h s above represent hexadecimal digits 0 9 a f or A F The generated constant specifies the binary data using hexadecimal byte values Character String Value Specification A character string declaration causes a C String constant to be generated ASN 1 production lt name gt lt StringType gt ccccccc Generated C constants public static readonly string lt name gt ccccccc 57 ASN 1 Type to C Class Mappings In the ASN 1 production definition lt StringType gt would be replaced with one of the ASN 1 character string types for example A5String The lowercase c s represent string characters The generated constant is simply the string in C form Object Identifier Value Specification An object identifier value specification causes a C integer array to be generated containing the subidentifier values ASN 1 production lt name gt OBJECT IDENTIFIER lt oidvalue gt Generated C constants public static readonly int lt name gt idl id2 idn For example consider the following declaration
107. in the Running ASNIC from the Command Line section 14 Using the Compiler Compilation When all options have been specified the final screen may be used to execute the compilation command Compile Compilation Options Y Generate listing ist 2 Show compilation warnings warnings Compilation command C acv630 pin asn 1c C acv630 cpp sample_ber employee employee asn O C facv630 cpp sample_ber employee useAsn 1Xsd ber per xml xsd cpp depends ist warnings E Save Project T compile cnet Included in the window are the compiler command an option to save the project and the output from compilation Selected options are reflected in the command line It is also possible to generate a printed listing of the input specifications Warnings encountered during compilation will also be printed if the appropriate check box is marked Click Finish to terminate the program The wizard will ask whether or not to save any changes made whether a new project has been created or not Using the Visual Studio Wizard to Generate ASN1C Projects On Windows systems ASNIC includes a Visual Studio wizard to help you with creating projects that use ASNIC in Visual Studio 2005 or later The wizard simply invokes the ASN1C GUI program You use the GUI to define whatever options you want to have set for generating your code and your project file Then when you click on the Compile button on the last screen of t
108. in the World Wide Consortium W3C Related XML Schema can be produced by using the xsd command line option Using the GUI Wizard to Run ASN1C ASNIC includes a graphical user interface GUI wizard that can be used as an alternative to the command line version It is a cross platform GUI and has been ported to Windows and several UNIXes The GUI makes it possible to specify ASN 1 files and configuration files via file navigation windows to set command line options by checking boxes and to get online help on specific options Using the Compiler The Windows installation program should have installed an ASN1C Compiler option on your computer desktop and an ASNIC option on the start menu The wizard can be launched using either of these items The UNIX version should be installed in ASN1C_INSTALL_DIR bin no desktop shortcuts are created so it will be necessary to create one or to run the wizard from the command line The C GUI differs little from the C C GUI screenshots may include references to C or C directories but the common code options are identical Using Projects The wizard is navigated by means of Next and Back buttons Following is the initial window ASN1C Project Wizard a New Project ASNIC 6 3 0 Evaluation License License expire date is Thu Apr 15 11 08 09 2010 Open Project The status window will display the version of the software you have installed as well as report any e
109. information object set The argument element is an open type but its type must match that specified at the location in the SupportedAttributes information object set indexed by opcode In this example opcode can have only two possible values 0 1 1 or 0 1 2 If the opcode value is 0 1 1 then argument must be a value of type VisibleString If the opcode value is 0 1 2 then argument will have an INTEGER value Any other value of the opcode element will be a violation of the table constraint If the SupportedAttributes object set is extensible in this example it is not then the argument element can be a value of any type In this case if the user is using an index element value outside the object set then the user will have to encode the argument element as an Asn OpenType The following sample code populates the open type value Step 1 populate the Invoke type with data Invoke pdu new Invoke pdu opcode new AsnlObjectIdentifier new int 0 1 1 pdu argument new AsnlVisibleString objsys note opcode value is 0 1 1 so argument must be AsnlVisibleString type note the rest of the encode method will be same as general PER DER BER encoding rules Step 2 Create a message buffer object AsnlPerEncodeBuffer encodeBuffer new AsnlPerEncodeBuffer Step 3 Invoke th ncode method Note that it must be done from
110. ing generated variables for encoding can be done in most cases either through the object constructors or directly by assigning an object reference to a public member variable Constructors are provided for most generated types to allow direct population of the encapsulated member variable s on initialization The exception is the classes generated for SEQUENCE OF or SET OF These only allow the size of an array to be specified population of the array elements must be done manually All of the base run time classes except Asn Null contain public member variables In practically all cases there is a single variable called mValue that is of the base type that needs to be populated For example the AsnJ Integer base class contains the following item public long mValue Therefore population of any class variable derived from INTEGER can be done by adding mValue to the end of the lefthand side of the assignment and an integer value on the right So for the following assignment X INTEGER A variable of the type can either be populated using the constructor with the following statement X x new X 25 or via direct access of the member variable as follows X xX new X x mValue 25 The only primitive type that does not have a single member called mValue to represent its value is BIT STRING In this case the Asn BitString class contains a second variable called numbits to specify the number of bits in the string Proc
111. ions tend to change frequently An external configuration file can be reused with a new version of an ASN 1 module but internal directives would have to be reapplied to the new version of the ASN 1 code At the outer level of the markup is the lt asnlconfig gt lt asn1config gt tag pair Within this tag pair the specification of global items and modules can be made Global items are applied to all items in all modules An example would be the lt storage gt qualifier A storage class such as dynamic can be specified and applied to all productions in all modules This will cause dynamic storage pointers to be used to any embedded structures within all of the generated code to reduce memory consumption demands The specification of a module is done using the lt module gt lt module gt tag pair This tag pair can only be nested within the top level lt asnlconfig gt section The module is identified by using the required lt name gt lt name gt tag pair or by specifying the name as an attribute for example lt module name MyModule gt Other attributes specified within the lt module gt section apply only to that module and not to other modules specified within the specification A complete list of all module attributes is provided in the table at the end of this section The specification of an individual production is done using the lt production gt lt production gt tag pair This tag pair can only be nested within a lt modu
112. ke command in Visual Studio NET command prompt to use this makefile When a makefile is generated it is assumed that the ASNIC project exists within the ASNIC installation directory tree The generation logic tries to determine the root directory of the installation by traversing upward from the project directory in an attempt to locate the csharp subdirectory which is assumed to be the installation root directory If the project is located outside of the ASNIC hierarchy the user can set the OSROOTDIR environment variable to point at the root directory If the root directory is located successfully the generated build script will use that directory however if the compiler fails to find the installation root directory it will use ROOT_DIR instead and print an error message Users will have to manually replace ROOT_DIR with the actual compiler installation root directory If the compiler fails to find the asnIrt dll runtime library it will use EASNIRT_DIRE instead and print an error message User will have to manually replace ASNIRT_DIR with the actual C runtime library directory 108 Chapter 15 Event Handler Interface The events command line switch causes hooks for user defined event handlers to be inserted into the generated C decode methods What these event handlers do is up to the user They fire when key message processing events occur during the course of parsing an ASN 1 message They are similar in functionality to
113. king down a syntax error The most common types of syntax errors are as follows e Invalid case on identifiers module name must begin with an uppercase letter productions types must begin with an uppercase letter and element names within constructors SEQUENCE SET CHOICE must begin with lowercase letters e Elements within constructors not properly delimited with commas either a comma is omitted at the end of an element declaration or an extra comma is added at the end of an element declaration before the closing brace e Invalid special characters only letters numbers and the hyphen character are allowed Programmers tend to like to use the underscore character _ in identifiers This is not allowed in ASN 1 Conversely C or C does not allow hyphens in identifiers To get around this problem ASNIC converts all hyphens in an ASN 1 specification to underscore characters in the generated code Semantics errors occur on the compiler back end as the code is being generated In this case parsing was successful but the compiler does not know how to generate the code These errors are flagged by embedding error messages directly in the generated code The error messages always begin with an identifier with the prefix ASN A search can be done for this string in order to find the locations of the errors A single error message is output to stderr after compilation on the unit is complete to indicate error conditions exist
114. l SaxHandler lt code gt public void StartElement string namespaceURI string localName string qName Attributes atts lt code gt public void Characters char ch int start int length lt code gt 35 Generated C Source Code Overview public void EndElement string namespaceURI string localName string qName lt code gt This is an implementation of a standard SAX content handler class As the XML parser software parses messages the methods within this class are invoked with the parsed content The StartElement method is invoked after a start element tag lt tag gt is parsed The Characters method is invoked one or more times to pass the content between tags into the application The EndElement method is invoked when an end element tag lt tag gt is encountered The ASNIC compiler generates custom code for each ASN 1 type within a given specification to parse the XML contents and fill in the generated C objects Error Handling As noted elsewhere in this manual the asnlc runtime and generated code will throw exceptions that are or derive from Asn1Exception The exception tells you what was wrong and provides a stack trace If you need additional information you may try the following e Identify the byte location in the input data using Asn1DecodeBuffer ByteCount e Identify the problem element using element name tracking The procedure to do this is simpl
115. lRecord Print personnelRecord catch Exception e System Console Out WriteLine e Message AsnlUtil WriteStackTrace e Console Error return Reuse of Decoding Objects The sample above showed the MDER decoding of a single message In a typical application a loop would be involved to decode a series of messages A single decode buffer can be used to process a stream of messages If the decode buffer is created using an input stream that contains a series of messages for example a file containing multiple records or a communications device you can repeatedly invoke the MDER decode method on the given message type Note that you can also use the same instance of your message type for repeated decoding rather than creating a new object and leaving the old one to be garbage collected Nothing special needs to be done to do this The generated decode method will automatically call the internal Jnit method before decoding to make sure all items are reset to their starting state In the example above all that would need to be done to decode a series of personnel records is the inclusion of a loop after the PersonnelRecord object was created in step 2 for 77 personnelRecord Decode decodeBuffer if trace System Console Out WriteLine Decode was successful personnelRecord Print personnelRecord 93 Chapter 12 Table Constraint Processing The ASNIC C code generati
116. lds 5 Encode the Invoke type to produce the final message In this case the amount of code generated to support the information object references is minimal The amount of coding required by a user to encode or decode the variable type field elements however can be rather large This 100 Table Constraint Processing is a trade off that exists between using the compiler generated table constraints solution as we will see below and using the simple form Table Form Code Generation If we now add table constraints to our original type definition it might look as follows Invoke SEQUENCE invokeID INTEGER opcode OPERATION amp 0perationCode My ops argument OPERATION amp ArgumentType My ops opcode The My ops constraint on the opcode element specifies an information object set not shown that constrains the element value to one of the values in the object set The My ops opcode constraint on the argument element goes a step further it ties the type of the field to the type specified in the row that matches the given opcode value ASNIC generates an in memory table for each of the items in the information object sets defined in a specification In the example above a table would be generated for the My ops information object set The code generated for the type would then use this table to verify that the given items in a structure that reference this table match the const
117. le gt section The production is identified by using the required lt name gt lt name gt tag pair or by specifying the name as an attribute for example lt production name MyProd gt Other attributes within the production section apply only to the referenced production and nothing else A complete list of attributes that can be applied to individual productions is provided in the table at the end of this section When an attribute is specified in more than one section the most specific application is always used For example assume a lt typePrefix gt qualifier is used within a module specification to specify a prefix for all generated types in the module and another one is used to specify a prefix for a single production The production with the type prefix will be generated with the type prefix assigned to it and all other generated types will contain the type prefix assigned at the module level Values in the different sections can be specified in one of the following ways 1 Using the lt name gt value lt name gt form This assigns the given value to the given name For example the following would be used to specify the name of the H323 MESSAGES module in a module section lt name gt H323 MESSAGES lt name gt 2 Flag variables that turn some attribute on or off would be specified using a single lt name gt entry For example to specify a given production is a PDU the following would be specified in a produc
118. ll have different logic for relative and simple table constraints The logic to invoke this method is as follows On the encode side Relative Table Constraint 1 The table constraint key is searched in the object set array to find the class object for the data in the populated type variable to be encoded 2 If the key element value is NOT found and the table constraint object set is extensible the CheckTC method will do no further processing i e a value field match will not be performed The user will have had to populate the type field using an Asn OpenType object in order for it to be encoded because the generated table contains no information on how to encode the value 3 If the key element value is found the method will verify all fixed type values match what is defined in the key row of the object set and will also verify that the type of any variable type fields matches the expected type 4 If the key element value is not found in the table or object set and the object set is NOT extensible then a table constraint violation exception will be thrown Simple Table Constraint 1 The CheckTC method will verify that all of the fixed type values match what is defined in the table constraint object set If the element value does not exist in the table or object set and the object set is NOT extensible then a table constraint violation exception will be thrown After the CheckTC method call the normal encode logic is performe
119. methods to be added to the generated classes Generated C Method Format and Calling Parameters The signature for a C PER encode method is as follows public override void Encode AsnlPerEncodeBuffer buffer The buffer argument is a reference of an Asn PerEncodeBuffer object that describes the buffer into which a message is to be encoded This must be created and initialized before calling any encode method See the description of this class in the C Run Time Classes section for details on how this class is used The PER encode methods do not return a value This is different than the C C version that returns a negative status value to indicate an encoding failure For C errors are reported via the exception mechanism All ASNIC CH exceptions are derived from the Asn Exception base class See the section on exceptions for a complete list and description of the various exceptions that can be thrown 71 Generated PER Encode Methods Procedure for Calling C PER Encode Methods The C class variables corresponding to each of the ASN 1 types and method of population are the same as they were in the BER encoding case See the section on BER encoding for instructions on how to populate the variables prior to encoding Once an object s member variables have been populated the object s encode method can be invoked to encode the value The general procedure to do this involves the following three steps 1 Create an enc
120. methods will be generated as well Large Integer Support The maximum size for a C long integer type is 64 bits ASN 1 has no such limitation on integer sizes and some applications security key values for example demand larger sizes In order to accommodate these types of applications the ASN1C compiler allows an integer to be declared a big integer via a configuration file variable the lt isBigInteger gt setting is used to do this see the section describing the configuration file for full details When the compiler detects this setting it will declare the integer class to be derived from the Asn 1 BigInteger class instead of the Asn Integer class The Asn1 BigInteger class encapsulates an object of the C BigInteger class This provides full support for working with integers of arbitrary lengths For example the following INTEGER type might be declared in the ASN 1 source file SecurityKeyType APPLICATION 2 INTEGER Then in a configuration file used with the ASN 1 definition above the following declaration can be made lt production gt lt name gt SecurityKeyType lt name gt lt isBigInteger gt lt production gt This will cause the compiler to generate the following class header class SecurityKeyType AsnlBigInteger The value field is populated by creating a C BigInteger object and either passing it in through the constructor or using it to directly populate the public member variable named m
121. n Methods are generated to get and set the base class members The following shows the basic mapping from ASN 1 type to C class definition ASN 1 Production lt name gt CHOICE lt elementl name gt lt elementl type gt lt element2 name gt lt element2 type gt XSD Types lt xsd choice gt lt xsd union gt Generated C class public class lt name gt AsnlChoice public const byte _ lt ELEMENT1 NAME gt 1 public const byte _ lt ELEMENT2 NAME gt 2 public lt name gt base public override string ElemName public void Set_ lt elementl name gt public void Set_ lt element2 name gt public override void Decode public override int Encode public override void Print Notes 1 The notation used in the ASN 1 definition above does not represent the ASN 1 extensibility notation It is used to show a continuation of the sequence elements 2 The public and private methods that are generated are shown without arguments or function bodies for brevity The compiler generates sequential identification constants for each of the defined elements in the CHOICE construct The format used is the element names converted to all uppercase characters and preceded by an underscore The 50 ASN 1 Type to C Class Mappings constants represent the values returned by the base class Choic
122. n it asks you if you want to create a new sln file The suggested folder for the new sln file in this case is the same folder where the new vcproj file was created 24 Using the Compiler GA Save File As X JQ de mydocs temp gt ASNICL ASNICL y Search ASNICI pl Ej Recent Places Name Date modified Dropbox No items match your search Libraries ES Documents a Music Pictures EE Videos Computer El Windows 7 C Ga Extra Space E For this example we ll assume you choose to save the sln file in the suggested location You now have a solution with one project and the project contains the source code generated from the employee asn file 25 Using the Compiler A Solution ASNICI 1 project i ka References Using the Compiler Compiler Configuration File In addition to command line options a configuration file can be used to specify compiler options These options can be applied not only globally but also to specific modules and productions A simple form of the Extended Markup Language XML is used to format items in the file This language was chosen because it is fairly well known and provides a natural interface for representing hierarchical data such as the structure of ASN 1 modules and productions The use of an external configuration file was chosen over embedding directives within the ASN 1 source itself due to the fact that ASN 1 source vers
123. n an ASN 1 encoded message It was introduced in 1994 to replace EXTERNAL by removing unneeded fields and adding a few new ones to hold information that was missing This type is described using the following ASN 1 SEQUENCE EmbeddedPDV UNIVERSAL 11 IMPLICIT SEQUENCE identification CHOICE syntaxes SEQUENCE abstract OBJECT IDENTIFIER transfer OBJECT IDENTIFIER syntax OBJECT IDENTIFIER lt presentation context context negotiation SE presentation context id INTEGER transfer syntax OBJECT IDENTIFIER transfer syntax OBJECT IDENTIFIER fixed NULL Key data value OCTET STRING WITH COMPONENTS F data value descriptor ABSENT The ASN 1 compiler is used to create a meta definition for this structure The definition will be generated in the file AsnlEmbeddedPDV cs or AsnlXerEmbeddedPDV cs for XER if needed by compiling ASN 1 files An object created from the resulting C class is populated just like any other compiler generated structure for working with ASN 1 data Parameterized Types The ASN1C compiler can parse parameterized type definitions and references as specified in the X 683 standard These types allow dummy parameters to be declared that will be replaced with actual parameters when the type is referenced This is similar to templates in C A simple and common example of the use of pa
124. n object of the Asn1XerEncodeBuffer class The following constructors are available for creating an XER encode buffer object public AsnlXerEncodeBuffer public AsnlXerEncodeBuffer bool canonical int sizeIncrement The default constructor sets all internal buffer control variables to default values Canonical XER is set to false and size increment is set to 1024 The other forms of the constructor allow these variables to be changed Canonical XER specifies that the canonical form of XER encoding CXER as specified in X 693 should be used Size increment specifies the amount by which the dynamic encode buffer should be expanded when it fills up This should be set lower for small memory constrained environments and higher if large messages are being encoded If the output stream method is used then the first step is the creation of an output stream For XER encoding this is an object of the Asn XerOutputStream class The following constructors are available for creating an XER encode buffer object public AsnlXerOutputStream OutputStream os public AsnlXerOutputStream OutputStream os bool canonical int bufSize The first constructor creates a buffered XER output stream with default size of an internal buffer Canonical XER is set to false The other form of the constructor allows these variables to be changed Canonical XER specifies that the canonical form of XER encoding CXER as specified in X 693 should be used The buffer
125. ned The following sections provide details on the C constants generated for the various types of ASN 1 value specifications INTEGER Value Specification An INTEGER value specification causes a C integer constant to be generated stant to be generated ASN 1 production lt name gt INTEGER lt value gt Generated C constant public static readonly int lt name gt lt value gt 56 ASN 1 Type to C Class Mappings BOOLEAN Value Specification A BOOLEAN value specification causes a C boolean constant to be generated ASN 1 production lt name gt BOOLEAN lt value gt Generated C constant public static readonly bool lt name gt lt value gt Binary String Value Specification This value specification causes two C constants to be generated a numbits constant specifying the number of bits in the string and a data constant that hold the actual bit values ASN 1 production lt name gt BIT STRING bbbbbbb B Generated C constants public static readonly int lt name gt _numbits lt numbits gt public static readonly byte lt name gt _data Oxhh Oxhh In the ASN 1 production definition the lowercase b s above represent binary digits 1 s or 0 s The generated code contains a numbits constant set to the number of bits binary digits in the string The data constant specifies the binary data using hexadecimal byte values Hexadec
126. nent In addition to GetInputStream there is a MsgCopy property that will retrieve a copy of the generated message into a byte array object This is somewhat slower because a copy needs to be done Another option that is available when doing XER encoding is the Buffer property This returns a reference to the actual message buffer into which the message was encoded Since an XER message is encoded front to back unlike the back to front used in BER DER encoding the buffer reference returned will point to the start of the encoded message The MsgLength property can then be used to get the message length in bytes Note that the byte count may not correspond to the actual character count as UTF 8 encoding is used and some characters may be multiple bytes in length If an output stream is used the stream should be closed when encoding is complete to ensure all buffered data is flushed to the output device The Asn1XerEncodeBuffer encode buffer class also contains other methods for operating directly on the encoded component for example the write method can be used to write it to a file or other medium A user could also derive their own special encode buffer class from this class to add more functionality See the description of the Asn1XerEncodeBuffer class in the run time section for a full description of the available methods A complete example showing how to invoke an XER encode method is as follows Note personnelRecord object was previ
127. nerated C class would contain public member variables for each of the string objects public AsnlIA5String givenName public AsnlIA5String initial public AsnlIA5String familyName 64 Generated BER DER CER Encode Methods The most efficient way to repopulate these variables within a loop would be simply to assign each of the new strings to be encoded directly to the public mValue member variables contained within the Asn A5String objects i e the Name or Asn1IAS5String objects should not be reconstructed each time A code snippet showing how this could be done is as follows Step 1 Create Name and AsnlBerEncodeBuffer objects for use in the loop Name name new Name W W W creates empty string objects AsnlBerEncodeBuffer encodeBuffer new AsnlBerEncodeBuffer for logic here to read name components from a DB or other medium populate string variables assume stringl 2 and 3 are string variables read from DB above name givenName mValue stringl name initial mValue string2 name familyName mValue string3 encode try len name Encod encodeBuffer true do something with th ncoded message component reset encode buffer for next pass ncodeBuffer Reset catch AsnlException e handle error Stream Oriented Indefinite Length Encode Methods BER messages can be encoded directly to an output stream such
128. nt string name int index mindentSpaces 3 Indent System Console Out WriteLine public void Characters string svalue short typeCode Indent System Console Out WriteLine svalue private void Indent for int i 0 i lt mIndentSpaces i System Console Out Write In this definition we chose to add the mVarName and mIndentSpaces member variables to keep track of these items The user is free to add any type of member variables he or she wants The only firm requirement in defining this class is the implementation of the methods defined in the interface We implement these methods as follows In StartElement we print the name equal sign and opening brace public void StartElement string name int index Indent System Console Out Write name if index gt 0 System Console Out Write index System Console Out WriteLine mIndentSpaces 3 In this simplified implementation we simply indent this is another private method within the class and print out the name equal sign and opening brace We then increment the indent level Logic is also present to check the index value to see if it is zero or greater If it is an array subscript is added to the element name In EndElement we simply terminate our brace block as follows 111 Event Handler Interface public void EndElement string name int index mindentSpaces 3 Indent
129. nt levels global module and individual production Global Level There are no attributes that are specific to C that can be specified at the global level Module Level These attributes can be applied at the module level by including them within a lt module gt section Name Values Description lt name gt lt name gt lt include module name This attribute identifies the module to which this section applies It is required This item allows a list of ASN 1 values names gt types names ASN 1 type or values names are specified as an attribute list types and or values to be included in the generated code By default the compiler generates code for all types and values within a specification This allows the user to reduce the size of the generated code base by selecting only a subset of the types values in a specification for compilation Note that if a type or value is included that has dependent types or values for example the element types in a SEQUENCE SET or CHOICE all of the dependent types will be automatically included as well lt include importsFrom name gt ASN 1 module name s specified as an attribute list This form of the include directive tells the compiler to only include types and or values in the generated code that are imported by the given module s lt exclude values names gt types names ASN 1 type or value
130. nvolves the following three steps 1 Create a decode buffer on the message to be decoded 2 Invoke the decode method 3 Process the decoded data values The first step is the creation of a decode buffer Asn MderDecodeBuffer has a constructor that accepts messages stored in a byte array It also has a constructor that accepts a System IO Stream so that messages may be streamed from various sources such as from a file The second step is to invoke the generated decode method The calling arguments were described earlier The final step is to apply your application specific processing to the data All data is contained within public member variables so access is quite easy A complete example showing how to invoke a decode method is as follows ery A Step 1 create a decode buffer for the message to be decoded This example will use a file input stream to decode a messag in a binary file 92 Generated MDER Decode Methods Create an input file stream object Stream ins File OpenRead filename Create a decode buffer object AsniMderDecodeBuffer decodeBuffer new AsnlMderDecodeBuffer ins Step 2 create an object of the generated type and invoke the decode method PersonnelRecord personnelRecord new PersonnelRecord personnelRecord Decode decodeBuffer Step 3 process the data if trace System Console Out WriteLine Decode was successful personne
131. o the following 1 At the application layer the Login ARGUMENT structure would be populated with the username and password to be encoded 2 The encode function for Login ARGUMENT would be called and the resulting message pointer and length would be passed down to the next layer the ROSE layer 3 At the ROSE layer the Invoke structure would be populated with the OPERATION value invoke identifier and other header parameters The open type object used to hold the encoded parameter value from step 2 is populated by creating an Asn1 OpenType object using the length of the encoded component 4 The encode function for Invoke would be called resulting in a fully encoded ROSE Invoke message ready for transfer across the communications link The following is a picture showing this Application Layer Populate specific message structure Login ARGUMENT and encode y Encoded message pointer and length ROSE Laver Populate ROSE header message structure Invoke and encode 7 Open type structure contains message pointer and length from previous step y Final encoded message process On the decode side the process would be reversed with the message flowing up the stack 1 At the ROSE layer the header would be decoded producing information on the OPERATION type based on the MACRO definition and message type Invoke Result etc The invoke identifier would also be available for use in session management In our example we would know at t
132. objective SYSTEMS INC ASNIC ASN 1 Compiler Version 6 5 C Users Guide Reference Manual Objective Systems Inc version 6 5 May 2014 The software described in this document is furnished under a license agreement and may be used only in accordance with the terms of this agreement Copyright Notice Copyright 1997 2012 Objective Systems Inc All rights reserved This document may be distributed in any form electronic or otherwise provided that it is distributed in its entirety and that the copyright and this notice are included Author s Contact Information Comments suggestions and inquiries regarding ASN1C may be submitted via electronic mail to info obj sys com Table of Contents Le Overview of ASNIC for CH sta ssa notan E a a sa pide rita atinente 1 2 Using the Compiler iii AG oe ads Se ok weed gs TE Sete es cok ehe Ain 2 ASNIC C Command Line Options sas siseccc es seccsvgsveissedssvececisaeeee sep seca gibebsassasesvacssbedsavdsesomeagssetess 2 Using the GUI Wizard to Run ASNIC 000 cece cece nce e cen eccnneeeeeeeeeeeeeeeeaeeeaeeeaeeea sean sean een eegs 6 Using Projects 25 ss ac09s sos ii napa repita E E patie sea bees 7 Common Code Generation Options cee ceee cece ee ceeeceeeceeecaeecaeeaeecae eeu eeneeeeeeeeseeseaeseaeeeaes 9 TS 12 C Code Generation Options aee ienei EE EE EEEE E E ESEE 13 Compilation stas ei E E T E E E E a SE 15 Using the Visual Studio Wizard
133. od See the description of this class in the C Run Time Classes section for details on how this class is used The useCachedLength argument indicates whether the encode method can rely on cached length information In some cases MDER requires pre calculation of the length of nested structures and this piece of information is needed twice during encoding once when encoding the containing structure and once when encoding the nested structure The generated types cache this information during encoding User code should normally pass false for this argument The generated encoding methods will pass t rue to other encoding methods when appropriate As you can see the encode methods return void an exception is thrown if an error occurs All ASNIC exceptions are derived from Asn1 Exception See the section on exceptions for a complete list and description of the various exceptions that can be thrown Populating Generated Variables for Encoding Populating generated types for encoding can be done in most cases either through the constructors or by assigning object references to public member variables Constructors are provided for most generated types to allow direct population of the encapsulated member variable s on initialization The exception to this is for classes generated for SEQUENCE OF types In that case the constructors only allow the size of an array to be specified population of the array elements must be done manually All of the
134. ode buffer class from this class to add more functionality See the description of the Asn BerEncodeBuffer class in the run time section for a full description of the available methods A complete example showing how to invoke an encode method is as follows Note personnelRecord object was previously populated with data Step 1 Create a message buffer object This object uses the default size increment for buffer expansion AsnlBerEncodeBuffer encodeBuffer new AsnlBerEncodeBuffer Step 2 Invoke th ncode method Note that it must be done from within a try catch block Ery 4 personnelRecord Encode encodeBuffer true if trace System Console Out WriteLine Encoding was successful System Console Out WriteLine Hex dump of encoded record ncodeBuffer HexDump System Console Out WriteLine Binary dump encodeBuffer BinDump 63 Generated BER DER CER Encode Methods Step 3 Access th ncoded message component In this case we use methods in the class to write the component to a file and output a formatted dump to the message dmp 7 tive Write th ncoded record to a file encodeBuffer Write new System 10 FileStream filename System IO FileMode Create Generate a dump file for comparisons System 10 StreamWriter messagedmp new System 10 StreamWriter new System 10 FileStream message dmp
135. ode message buffer object into which the value will be encoded 2 Invoke the encode method 3 Invoke encode message buffer methods to access the encoded message component The first step is the creation of an encode message buffer object For PER encoding this is an object of the AsnlPerEncodeBuffer class The following constructors are available for creating a PER encode buffer object public AsnlPerEncodeBuffer bool aligned public AsnlPerEncodeBuffer bool aligned int sizeIncrement The first argument indicates whether PER aligned or unaligned encoding should be done The second form of the constructor contains a size increment argument This argument will determine how often the buffer will need to be resized to hold large messages If you know that you will be encoding large messages then this object should be constructed with a large value for the increment If you know that you will be encoding small messages in a constrained environment then this value can be set very low The default constructor sets the value to a reasonable mid range value see SIZE_INCREMENT in Asn EncodeBuffer cs as of this writing the value was set to 1024 The second step is the invocation of the encode method The calling arguments were described earlier As per the C standard this method must be invoked from within a try catch block to catch the possible exceptions that may be thrown Alternatively the method from which the encode method is called can d
136. oding rules Production Level These attributes can be applied at the production level by including them within a lt production gt section Name Values Description lt name gt lt name gt module name This attribute identifies the module to which this section applies It is required lt isBigInteger gt n a This is a flag variable an empty element in XML terminology that specifies that this production will be used to store an integer larger than the C long type 64 bits A C BigInteger class will be used to hold the value This qualifier can be applied to either an integer or constructed type If constructed all integer elements 29 Using the Compiler Name Values Description within the constructed type are flagged as big integers Compiler Error Reporting Errors that can occur when generating source code from an ASN 1 source specification take two forms syntax errors and semantics errors Syntax errors are errors in the ASN 1 source specification itself These occur when the rules specified in the ASN 1 grammar are not followed ASNIC will flag these types of errors with the error message Syntax Error and abort compilation on the source file The offending line number will be provided The user can re run the compilation with the I flag specified to see the lines listed as they are parsed This can be quite helpful in trac
137. oductions depend on from IMPORT files der None This option instructs the compiler to generate functions that implement the Distinguished Encoding Rules DER as specified in the ASN 1 standards dirs None This is a C option that causes a subdirectory to be created to hold each of the generated C source files for each module in an ASN 1 source file events None Generate extra code to invoke user defined event and error handler callback methods see the Event Handlers section Using the Compiler Option Argument Description genmake None lt directory gt This option is used to generate a makefile for compiling generated classes using nmake command from within a Visual Studio NET command prompt window This option is used to specify a directory that the compiler will search for ASN 1 source files for IMPORT items Multiple I qualifiers can be used to specify multiple directories to search lax None This option instructs the compiler to not generate code to check constraints When used in conjunction with the compact option described next it produces the smallest code base for a given ASN 1 specification list None Generate listing This will dump the source code to the standard output device as it is parsed This can be useful for finding parse errors namespace noencode lt namespaceName gt None This
138. ommand line options not available in GUI The Sample Program Generation frame allows you to generate boilerplate reader and writer applications as well as randomized test data for populating a sample encoded message The items in the Protocol Data Units frame may be used in conjunction to select the appropriate PDU data type to be used in the sample programs The Debugging and Event Handlers frame contains options that generate code for adding trace diagnostics and event handling hooks into generated code It is possible to generate a type parser by generating only an event handler and no data types for the decoded messages This grants a great deal of flexibility in handling input data at the expense of generating pre defined functions for most common encoding and decoding tasks Users of embedded systems may find this useful as it will shrink the output considerably while allowing them fine control over decoding procedures The Other Options frame contains miscellaneous modifications to code output including type name resolution avoiding duplicate names date stamp removal useful when generated code will be stored in source control and a line item for including any new command line features not yet represented in the GUI XSD Options If the Generate equivalent XML schema XSD file option was checked in the Common Code Generation Options screen the following window will be presented for modifying the contents of the generat
139. on capability can generate code to process ASN 1 table constraints as specified in the X 681 and X 682 ASN 1 standards This code is generated through the use of the tables option This instructs the compiler to generate additional methods and tables to allow multi level message types specified using table constraints to be encoded or decoded with a single method call Special code is generated for the CLASS Information Object and Information Object Set items to create the table necessary to for table constraint processing Then additional encode and decode methods are generated that use these tables to branch to the multiple message levels CLASS Specification NOTE Class code generation is done only when tables is specified This additional code is generated to support the processing required to verify table constraints which is intended for use only in compiler generated code Therefore it is not necessary for the average user to understand the mappings in order to use the product The information presented here is informative only to provide a better understanding of how the compiler handles table constraints The C class generated to model an ASN 1 class contains member variables for each of the fields within the class To create an instance of this class an information object is required to populate these variables with the values defined in the ASN 1 information object specification C code will be generated for each ASN 1 CLASS d
140. or all constructed elements in a message Using the Compiler Option Argument Description tables None This option is used to generate additional code for the handling of table constraints as defined in the X 682 standard uniquenames None This option instructs the compiler to automatically generate unique names to resolve name collisions in the generated code Name collisions can occur for example if two modules are being compiled that contain a production with the same name A un ique name is generated by prepending the module name to one of the productions to form a name of the form lt module gt _ lt name gt Note that name collisions can also be manually resolved by using the typePrefix enumPrefix and valuePrefix configuration items see the Compiler Configuration File section for more details vcproj lt version gt This option instructs the compiler to generate a Visual Studio C project file lt version gt is the version of Visual Studio 2010 2008 default 2005 warnings None Output information on compiler generated warnings xer None This option instructs the compiler to generate functions that implement the XML Encoding Rules XER as specified in the ASN 1 standards Related XML Schema can be produced by using the xsd command line option xml None This option instructs the compiler to generate functions that implement the XML Encoding Rules XML as specified
141. ource files that allow typed data to be encoded decoded This release of ASNIC includes options to generate code in the following languages C C C or Java This manual discusses the C code generation capabilities The following other manuals discuss the other language code generation capabilities e ASNIC C C Compiler User s Manual C C code generation e ASNIC Java Compiler User s Manual Java code generation Each module or namespace that is encountered in an ASN 1 or XSD source file results in the generation of a series of C source files A separate C file is generated for each production type or global element in the source file Additional files are generated for compiler generated productions and to hold value specification constants There is also a set of classes that form the run time component of the C package These classes provide the primitive component building blocks that are assembled by the compiler to encode decode complex structures They also provide support for managing message buffers that hold the encoded message components ASNIC works with the version of ASN 1 specified in ITU T international standards X 680 through X 683 It generates code for encoding decoding data in accordance with the following encoding rules e Basic Encoding Rules BER Distinguished Encoding Rules DER and Canonical Encoding Rules CER as published in the ITU T X 690 standard e Packed Encoding Rules PER as published in the ITU
142. ously populated with data Step 1 Create a message buffer object This object uses standard XER non canonical and the default size increment for buffer expansion AsnlXerEncodeBuffer encodeBuffer new AsnlXerEncodeBuffer Step 2 Invoke th ncode methods These include encodeStartDocument to encode the XML document header the generated C encode method to encode the document body and the encodeEndDocument method to complete the messag Note that these methods must be invoked from within a try catch block t cd Op personnelRecord Encode encodeBuffer null encodeBuffer EncodeEndDocument if trace System Console Out WriteLine Encoding was successful encodeBuffer Write System Console OpenStandardOutput Step 3 Access th ncoded message component In this case we use methods in the class to write the encoded XML document to a file encodeBuffer Write new System 10 FileStream filename System IO FileMode Create 83 Generated XML Methods We can also directly access the buffer as follows byte buffer encodeBuffer Buffer int msglen encodeBuffer MsgByteCnt catch Exception e System Console Out WriteLine e Message AsnlUtil WriteStackTrace e Console Error return An example showing stream based encoding is as follows Note personnelR
143. ows void Characters string svalue short typeCode The svalue argument contains the stringified value The format of this value is ASN 1 value notation for the value as defined in the X 680 standard The typeCode argument contains an identifier that specifies the ASN 1 type of the value The identifier corresponds to the universal identifier values the ID number in the universal tags for each of the primitive data types The only exception to this rule is that the identifier 99 was added to represent an Open Type construct Constants for all of the identifier values are provided in the Asn Type class See the C documentation for this class for a list of the constants How to Use lt To define event handlers two things must be done 1 One or more new classes must implement the Asn NamedEventHandler interface 2 Objects of these classes must be created and registered prior to calling the generated decode method for a particular type The best way to illustrate this procedure is through examples We will first show a simple event handler application to provide a customized formatted printout of the fields in a BER message Then we will show a simple XML converter class that will convert the data in a BER message to XML Example 1 A Formatted Print Handler The ASNIC evaluation and distribution kits include a sample program for doing a formatted print of parsed data This code can be found in the csharp sample_ber EventHandler directory
144. p System lush true StreamWriter new System IO FileStream TIO FileMode Create ncodeBuffer HexDump messagedmp We can also directly access the buffer as follows byte buffer ncodeBuffer Buffer int msglen encodeBuffer MsgByteCnt catch Exception e System Console O AsnlUtil WriteSt return ut WriteLin ackTrace e e Message Console Error If you compare this example with the BER encoding example in Figure 1 you will see the encoding procedure is almost identical This makes it very easy to switch encoding methods should the need arise All you need to do is change AsnlBerEncodeBuffer to Asn PerEncodeBuffer and remove the explicit argument from the encode method call Reuse of C Encoding Objects The concept of reusing C objects for PER encoding is the same as was described previously for BER encoding Basically all that needs to be done is the creation of a single PER encode buffer object and an object corresponding 73 Generated PER Encode Methods to the ASN 1 data type to be encoded outside of the processing loop These objects can then be reused to encode each instance of the messages to be sent After each message is encoded the PER buffer must be reset for the next message by using the Reset method See the section on reuse of objects in the BER encoding section for a more thorough discussion and sample code on using this capability 74
145. pane These allow further control of the compilation process They are optional and are only needed if the default compilation process is to be altered for example if a type prefix is to be added to a generated type name See the Compiler Configuration File section for details on defining these files Common Code Generation Options Code generation options common to all language types are specified in the following tabbed window Using the Compiler Common Code Generation Options Language Options Function Options _ Utility Options Input File Type 9 Modern ASN 1 1997 based on X 680 standard Legacy ASN 1 based on obsolete X 208 standard with ROSE or SNMP macros Schema XSD E Lax Syntax Check Additional Translations Y Generate equivalent XML schema XSD file Generate ASN 1 file based on X 694 XSL None syntax check only BER DER CER XER T XML select aligned or unaligned PER at run time Code Options V Generate code for all dependent imported type definitions Generate code compatible with compiler version 6 2 Language options pictured above encompass not only the output language choice but also input specification type encoding rules and code compatibility options Certain options will be inactive greyed out depending on the file type selected For example if an XSD file is selected the option Generate ASN 1 file based on X 694 will be active and
146. pe definitions as follows _ lt ClassName gt _ lt FieldName gt lt Type gt Here ClassName is replaced with name of the Class Assignment and FieldName is replaced with name of the field Type is the type definition in the ASN 1 CLASS s TypeField This type is used as a defined type in the information object definition for absent values of the TypeField It is also useful for the user to generate a value for a related OpenType definition in a table constraint 2 New type assignments are created for ValueField or ValueSetField type definitions if the type is with a constraint definition and or the type is Sequence Set Choice Sequenceof SetOf definition _ lt ClassName gt _ lt FieldName gt lt Type gt Here ClassName is replaced with name of the Class Assignment and FieldName is replaced with name of the ValueField or ValueSetField Type is the type definition in The ASN 1 CLASS s ValueField or ValueSetField This type will appear as a defined type in the ASN 1 CLASS s ValueField or ValueSetField This new type assignment is used for compiler internal code generation purpose It is not designed for use by the end user 3 New value assignments are created for ValueField default value definitions as follows _ lt ClassName gt _ lt FieldName gt _default lt Type gt lt Value gt Here ClassName is replaced with name of the Class Assignment and FieldName is replaced with name of the ValueField Value is the
147. pes Two constructors are generated a default constructor and a constructor that takes a number of elements argument The default constructor will set the elements variable to null The second constructor will allocate space for the given number of elements The recommended way to populate a variable of this type for encoding is to use the second form of the constructor to allocate the required number of elements and then directly set the element object values For example to populate the following construct IntSeq SEQUENCE OF INTEGER with 3 integers the following code could be used IntSeq intSeq new IntSeq 3 intSeq elements 0 new AsnlInteger 1 intSeq elements 1 new AsnlInteger 2 intSeq elements 2 new AsnlInteger 3 Note that each of the integer element values is wrapped in an Asn1 Integer wrapper class Generation of Temporary Types for SEQUENCE OF Elements As with other constructed types the lt type gt variable can reference any ASN 1 type including other ASN 1 constructed types Therefore it is possible to have a SEQUENCE OF SEQUENCE SEQUENCE OF CHOICE etc 48 ASN 1 Type to C Class Mappings When a constructed type is referenced a temporary type is generated for use in the final production The format of this temporary type name is as follows lt prodName gt _element In this definition lt prodName gt refers to the name of the production containing the SEQUENC
148. r does with this definition is uses it to parse types and values out of OPERATION definitions An example of an OPERATION definition is as follows login OPERATION ARGUMENT SEQUENCE username IA5String password IA5String 118 ASN1C90 yu ESULT SEQUENCE ticket OCTET STRING welcomeMessage IA5String ERRORS authenticationFailure insufficientResources 1 In this case there are two embedded types an ARGUMENT type and a RESULT type and an integer value 1 that identifies the OPERATION There are also error definitions The ASN1C90 compiler generates two types of items for the OPERATION 1 It extracts the type definitions from within the OPERATION definitions and generates equivalent C classes and encoders decoders and 2 It generates value constants for the value associated with the OPERATION e the value to the right of the in the definition The compiler does not generate any structures or code related to the OPERATION itself for example code to encode the body and header in a single step The reason is because of the multi layered nature of the protocol It is assumed that the user of such a protocol would be most interested in doing the processing in multiple stages hence no single function or structure is generated Therefore to encode the login example the user would do the following Therefore to encode the login example the user would d
149. r level type know 75 Generated PER Decode Methods as a Protocol Data Unit PDU that encompasses all of the different message types that might be received This is typically a CHOICE construct with each option representing a different type of message The generated decode method for the PDU is invoked to decode the message The calling arguments were described earlier As per the C standard this method must be invoked from within a try catch block to catch the possible exceptions that may be thrown Alternatively the method from which the decode method is called can declare that it throws the exceptions leaving them to be dealt with at a higher level The final step is to process the data All data is contained within public member variables so access is quite easy All of the primitive data type classes contain a public member variable called mValue that contains decoded data This can be accessed in nested structures by prefixing mValue with each of the element names from the top down For example the givenName element in the Name type shown earlier would be accessed as follows name givenName mValue this assumes an instance of the Name class was created using the variable name name A complete example showing how to invoke a decode method is as follows try 4 Step 1 create a decode message buffer object to describe the message to be decoded This example will use a file input stream to decode a m
150. raints The C type generated for the SEQUENCE above when tables is specified would be as follows public class Invoke AsnlType public AsnlInteger invokelD public OPERATION_operationCode opcode public AsniType argument This is almost identical to the type generated in the simple case The difference is that ASN Type is used instead for the argument element instead of ASN OpenType This type is defined as the base class for all the generated ASN 1 types It holds the value to be encoded or decoded The way a user Would use this to encode a value of this type is as follows 1 Populate a variable of the type to be used as the argument to the invoke type 2 Assign it to the argument member variable in the structure above 3 Populate the remaining Invoke type fields 4 Encode the Invoke type to produce the final message Note that in this case the intermediate type does not need to be manually encoded by the user The generated encoder has logic built in to encode the complete message using the information in the generated tables Additional Code Generated for the tables Option The following additional code is generated for type definitions when the the tables command line option is used The code generated to support table constraints is intended for use only in compiler generated code Therefore it is not necessary for the average user to understand the mappings in order to use the product The information presented here
151. rameterized types is for the declaration of an upper bound on a sized type as follows SizedOctetString INTEGER ub OCTET STRING SIZE 1 ub In this definition ub would be replaced with an actual value when the type is referenced For example a sized octet string with an upper bound of 32 would be declared as follows OctetString32 SizedOctetString 32 The compiler would handle this in the same way as if the original type was declared to be an octet string of size 1 to 32 In the case of C this would result in size constraint checks being added to the generated encode and decode methods for the type 54 ASN 1 Type to C Class Mappings Another common example of parameterization is the substitution of a given type inside a common container type For example security specifications frequently contain a signed parameterized type that allows a digital signature to be applied to other types An example of this would be as follows SIGNED ToBeSigned SEQUENCE toBeSigned ToBeSigned algorithmOID OBJECT IDENTIFIER params Params signature BIT STRING An example of a reference to this definition would be as follows SignedName SIGNED Name where Name would be another type defined elsewhere within the module ASNIC performs the substitution to create the proper C class definition for SignedName public class SignedName AsnlType publ
152. rence In the simple form of code generation the class definition itself does not result in the generation of any corresponding C code It is only an abstract template that will be used to define new items later 99 Table Constraint Processing on in the specification In the table form a C container class is generated to hold the Information Object instances of the ASN 1 CLASS Fields from within the class can be referenced in standard ASN 1 types It is these types of references that the compiler is mainly concerned with These are typically header types that are used to add a common header to a variety of other message body types An example would be the following ASN 1 type definition for a ROSE invoke message header Invoke SEQUENCE invokeID INTEGER opcode OPERATION amp operationCode argumentOPERATION amp ArgumentType This is a very simple case that purposely omits a lot of additional information such as Information Object Set constraints that are typically part of definitions such as this The reason this information is not present is because we are just interested in showing the items that the compiler is concerned with We will use this type to demonstrate the simple form of code generation We will then add table constraints and discuss what changes when the tables command line options is used The opcode field within this definition is an example of a fixed type field reference
153. ressed in space separated list form instead of as individually wrapped elements or value lists 78 Generated XML Methods For example the ASN 1 specification A SEQUENCE OF INTEGER with value 1 2 3 would produce the following encoding in XER lt A gt lt INTEGER gt 1 lt INTEGER gt lt INTEGER gt 2 lt INTEGER gt lt INTEGER gt 3 lt INTEGER gt lt A gt in XML it would be the following lt A gt l 2 3 lt A gt e The values of the BOOLEAN data type are expressed as the lower case words true or false with no delimiters In XER the values are lt true gt and lt false gt e Enumerated token values are expressed as the identifiers themselves instead of as empty XML elements i e elements wrapped in lt gt For example a value of the ASN 1 type Colors ENUMERATED red blue green equal to red would simply be lt color gt red lt color gt instead of lt color gt lt red gt lt color gt e The special REAL values lt NOT A NUMBER gt lt PLUS INFINITY gt and lt MINUS INFINITY gt are represented as NaN INF and INF respectively GeneralizedTime and UTCTime values are transformed into the XSD representation for dateTime YYYY MMDDTHH MM SS SSSS Zl I HH MM when encoded to XML When an XML document is decoded the time format is transformed into the ASN 1 format EXTENDED XER EXTENDED XER specified in X 693 allows you to vary the XML
154. ronment file will take precedence Since this Visual Studio folder hierarchy see R vsz file to work he ABSOLUTE_PATH parameter below must be set to the full path specification f the vswizard folder within your ASN1C installation DIR parameter below can be set to the root of the ASNIC If OSROOTDIR is already defined as a Windows environment tion is what s desired the definition If OSROOTDIR is defined both in variable then the definition in this file needs to be copied into the EADME txt this feature can be useful if multiple ASN1C and Visual S Studio is being used VSWIZARD 7 0 Wizard VsWizard VsWizardEngine 8 0 tudio versions are installed and a different version of ASN1C is to be used depending on what version of Visual Param WIZARD_NAME ASN1CWizard Param ABSOLUTE_PATH C acv650 vswizard Param OSROOTDIR C acv650 Param FALLBACK_LCID 1033 Param WIZARD_UI FALSE Param SOURCE_FILTER txt For this example let s assume that ASNIC 6 5 0 was installed into E acv650 instead of C acv650 Let s also assume that you want to retain the OSROOTDIR setting in this file You would need to modify this file so it looks like this Param WIZAR Param ABSOLUT Param OSROOTD Param FALLBAC Param WIZARD_ Param SOURCE_FILT D_NAME F IR UL E_PAT K_LCI Eal ASN1CWizard E acv650 vswizard acv650 1033 ALS yom a
155. rrors upon startup that occur such as a missing license file The Project Wizard will allow you to save your compilation options and file settings into a project file and retrieve them later If you wish to make a new project click the icon next to Create a New Project Using the Compiler amp Get Project File Name GO ES cpp gt sample_ber employee v Organize v New folder HE Desktop a Name Date modified Type 8 EME _ employee acp 3 16 2010 11 19 AM ACP File El Recent Places Libraries Documents d Music mes Pictures E Videos Computer fly COMPAQ C a FACTORY_IMAGI 4 Filename EME Save as type acproj acp Hide Folders Previously saved projects may be recalled by clicking the icon next to Open an Existing Project m 3 Load ASNIC Project gO Le cpp gt sample_ber employee v s Organize v New folder fF Favorites Name Date modified Type EE Desktop employee acp 3 16 2010 11 19AM ACP File de Downloads E Recent Places A Libraries E Documents ad Music ime Pictures amp Videos Mi Computer fly COMPAQ C a FACTORY_IMAGI Ed m l Filename employee acp v S acproj Zacp y The project format has changed in ASNIC 6 3 to help accommodate the transition to Qt 4 5 Changes to the interface necessitated changes to the underlying project
156. s and this must be used whenever an open type is required for XER The reason for creating a special derived class is because of dependencies on XML parser classes defined within this class If these were added directly to the Asn OpenType class a user would need to always have XML parser files included in their classpath even if working with BER DER or PER only If the tables command line option is selected and the ASN 1 type definition references a table constraint the code generated is different In this case Asn OpenType above is replaced with Asn1Type This the base class for all ASN 1 types This allows a value of any ASN 1 type to be specified On the encoding side a user can assign an object of any ASN 1 type to this variable and the encoding routine will call the appropriate encoder according to the table index value If the variable type is not present in the table and the Object Set is extensible than it can be encoded as an open type Otherwise an exception will be thrown On the decoding side the appropriate variable type is populated from the table based on the decoded index parameters The user can determine the variable type from the table index value If the variable type is not present in table then it will be decoded as an open type if the Object Set is extensible otherwise and exception will be thrown lt xsd any gt Handling The XSD any wildcard item is similar to an ASN 1 open type in semantics in that it allows
157. s names are specified as an attribute list This item allows a list of ASN 1 types and or values to be excluded in 28 Using the Compiler Name Values Description the generated code By default the compiler generates code for all types and values within a specification This is generally not as useful as in include directive because most types in a specification are referenced by other types If an attempt is made to exclude a type or value referenced by another item the directive will be ignored lt sourceFile gt lt sourceFile gt source file name Indicates the given module is contained within the given ASN 1 source file This is used on IMPORTs to instruct the compiler where to look for imported definitions This replaces the module txt file used in previous versions of the compiler to accomplish this function lt pkgName gt C namespace name Name of the C namespace associated with this module This will cause a C using statement to be generated for the module if this name is not the same as that of the namespace being compiled lt namespace gt lt namespace gt namespace name This is used to specify the namespace name for the given module By default Asnlc compiler will use the http www obj sys com as the module namespace This option should be used with XML encoding rule XML only Asnic compiler will ignore this option usage with other enc
158. s used to parse the XML documents to be decoded This software contains a common interface known as the Simple API for XML or SAX that is a de facto standard that is supported by most parsers 85 Generated XML Methods ASNIC generates an implementation of the content handler interface defined by this standard This implementation receives the parsed XML data and uses it to populate the structures generated by the compiler The default XML parser used for C is the MSXML parser that is part of the Microsoft NET framework As mentioned since SAX is a de facto standard it should be a relatively straightforward process to use the generated handlers with any other parser A diagram showing the components used in the XML decode process is as follows Java file class MySeq AsnlInteger a ASN 1 Specification AsnlBoolean b AsnlUTF String Cc SEQUENCE a INTEGER b BOOLEAN c UTF8String class SaxHandler startElement characters pe endElement lt MySeq gt lt a gt 22 lt a gt lt b gt lt true gt lt b gt lt c gt Hello lt c gt 22 true Hello lt MySeq gt ASN1C generated SAX handlers ASNIC generates code to implement the following methods defined in the SAX content handler interface StartElement Characters EndElement The interface defines other methods that can be implemented as well but these are sufficient to decode XER encoded data These met
159. sa ESETI paT RSS EESE TAPASTE Es SS eeeoads 52 iii ASNIC NN 52 NSA ANY gt Handling AS ad Cabs A id 53 Bxtertial Py A NTE 53 EmbeddedPDV DA o1 e E A A ana eed 54 Parameterized TY Pes rynna cocacola te de eos pa os 54 Value Specifications Guti li iS A Gade dade Aad A de dela 56 INTEGER Value SpecifiCan AA O NS 56 BOOLEAN Value Specification ass A E E E T E E A EE E E E a EEA EN 37 Binary String Value Specification cccccece ence ence E eE E AE EEAS sean NEEE EEEE EE 37 Hexadecimal String Value Specification oooooncnnccnnccnnconnconncnnncnnncnnncnnnnnnnrnnnnnnrnnnrnnccnnccnnccnnis 57 Character String Value Specification m renien eeo a Ea E A a Eo R ERE REEKS 57 Object Identifier Value Specification ccc cece cece ence ence eee n eee ece eee eeeeeeceeesaeesaeseaeeea seas eeaeegs 58 ENUMERATED Value Specification eyen asse eean e eean e E EEEE 58 REAL Value Specific ahi On rs neer na e EE a E Ad A AA 58 SEQUENCE Value Specification svansen oE ERE E E AE eka E Derrida 58 SEL Value Specific E E as ee e AI IDAS TO 59 SEQUENCE OF Vale Specification os sco ous ios non abs sev ean ashes tsp en dss pase NEE pugs see yeee pees eee NEESS 59 SET OF Value Specificato a orie o cSt SASSER o Ga UDA ANG OAD BOE UE pe 60 CHOICE Value Specification senian e dawn Sas ee wages heh Rea ion boy uA Ro EAS ne LiaA E HOSS 60 5 Generated BER DER CER Encode Methods 1 000 000 ceee cece cnee ce eeca cece cece eens eens ceneee
160. sage AsnlUtil WriteStackTrace e Console Error return 87 Chapter 10 Generated MDER Encode Methods Unlike what is done for other encoding rules for MDER we provide stream based encoding only In order to encode to a memory buffer you simply use a System IO MemoryStream For each ASN 1 production defined in an ASN 1 source file an encode method may be generated This function will convert a populated variable of the given type into an encoded ASN 1 message An encode method is only generated if it is required to alter the behavior of the base class The C model is built on inheritance from a set of common run time base classes MDER supports only a few primitive types and most of these are subsets of ASN 1 built in types Therefore in most cases there is not an applicable MDER encode method in the common run time base class and so an encode method will be generated The generated classes for all constructed types SEQUENCE SEQUENCE OF and CHOICE will include generated encode methods Generated Method Format and Calling Parameters The signature for the MDER encode method comes in two forms shown below public virtual void Encode AsnilMderOutputStream buffer bool useCachedLength public virtual void Encode AsniMderOutputStream buffer The buffer argument is an Asn MderOutputStream object which receives the encoded message This must be created and initialized before calling any encode meth
161. set All character string types are derived from the Asn1CharsString base class except the UniversalString This class contains the following public member variable that holds the character string contents public string mValue Each of the specific ASN 1 character string types except UniversalString has an associated C class that is derived from the Asn CharString base class The general form of the C class name for each of the ASN 1 string types is AsnI followed by the ASN 1 string type name For example JA5String is represented by the AsnJ A5String class NumericString by the Asn NumericString etc The UniversalString associated C class is derived from Asn1Type and it contains the following public member that holds the character string contents public int mValue The following shows the basic mapping from ASN 1 type to C class definition ASN 1 Production lt name gt lt CharStrType gt XSD Types lt xsd string gt and all related types including date time types and duration Generated C class public class lt name gt AsnlOctetString public lt name gt base public lt name gt byte data base data public lt name gt byte data value_ Generated C class public class lt name gt Asnl lt CharStrType gt 40 ASN 1 Type to C Class Mappings public lt name gt base public lt name gt string value_ base value_
162. set of received elements is then checked after the loop is completed to verify all required elements were received 47 ASN 1 Type to C Class Mappings SEQUENCE OF The ASN 1 SEQUENCE OF type is converted to a C class that inherits the Asn Type run time base class An array public member variable named elements is generated to hold the elements of the defined type The following shows the basic mapping from ASN 1 type to C class definition ASN 1 Production lt name gt SEQUENCE OF lt type gt XSD Types Eleements or content group definitions containing the minOccurs and or maxOccurs facets Also lt xsd list gt types use this model Generated C class public class lt name gt AsnlType public lt type gt elements public lt type gt elements null public lt type gt int numRecords lements new lt type gt numRecords public override void Decode public override int Encode public override void Print The compiler first generates a public member variable to hold the SEQUENCE OF elements The decision was made to make the variable public to make it easier to populate for encoding The alternative was to use protected or private variables with get set methods for setting or examining the values It was felt that this approach would be too cumbersome for setting values in deeply nested constructed ty
163. size argument specifies the size of the internal buffer of the stream Larger buffer sizes typically provide better performance at the expense of increased memory consumption Similar classes exist for XML encode buffer and streams int sizeIncrement OutputStream os OutputStream os int bufSize public AsnlXmlEncodeBuffer public AsnlXmlEncodeBuffer public Asn1Xml10utputStream public Asn1Xml10utputStream aa The main difference is the XML classes to not have a canonical XML option therefore there is not exer or canonical boolean argument The second step is the invocation of the encode methods The calling arguments were described earlier As per the CA standard this method must be invoked from within a try catch block to catch the possible Asn Exception or System Exception that may be thrown Alternatively the method from which the encode method is called can declare that it throws Asn1 Exception and System Exception leaving it to be dealt with at a higher level Finally if a message buffer is used encode buffer methods can be called to access the encoded message component The C API provides an object called a ByteArrayInputStream that provides a way to look at the encoded component 82 Generated XML Methods as a stream The encode buffer object provides a method called GetInputStream that returns a byte array input stream representing the message component This is the preferred way to access the encoded compo
164. sure values of the correct types are specified for these elements These checks are discussed in the sections on the specific constructed types Constructors Constructors are generated to allow an object to be initialized in a number of different ways All productions have a default constructor with no parameters This creates an empty object that can be filled in at a later time Constructors are also created that take a parameter of the base type value to allow direct population upon creation of an object In our example code two constructors were generated public EmployeeNumber base public EmployeeNumber int value_ base value_ 33 Generated C Source Code Overview More complex constructed ASN 1 types such as a SEQUENCE would have a constructor that would have an argument for each defined element A CHOICE on the other hand would have a unique constructor for each of the possible choice items See the sections on specific ASN 1 types to find out exactly what constructors are generated for a given type Decode Method The generated decode method for BER DER has the following general form public override void Decode AsnlBerDecodeBuffer buffer bool explicitTagging int implicitLength Users of the C and C version of the product might recognize this form It is very similar to the C function prototype A reference to an Asn BerDecodeBuffer object is passed that specifies the message being de
165. t than the C C version that returns a negative status value to indicate an encoding failure For C errors are reported via the exception mechanism All ASNIC CA exceptions are derived from the Asn Exception base class See the section on exceptions for a complete list and description of the various exceptions that can be thrown If I O error occurs then the System Exception is thrown Procedure for Calling C XER Encode Methods The C class variables corresponding to each of the ASN 1 types and method of population are the same as they were in the BER encoding case See the section Populating Generated Variables for Encoding for instructions on how to populate the variables prior to encoding 81 Generated XML Methods Once an object s member variables have been populated the object s encode method can be invoked to encode the value The general procedure to do this involves the following three steps 1 Create an encode message buffer or output stream object into which the value will be encoded 2 Invoke encode methods These include the EncodeStartDocument and EncodeEndDocument methods from the AsnlXerEncodeBuffer class and the encode method from the ASNIC generated class 3 If the encode message buffer is used invoke encode message buffer methods to access the encoded message component If the output stream is used close the stream The first step is the creation of an encode message buffer object For XER encoding this is a
166. ted ASN 1 production lt name gt lt ChoiceType gt elemname lt elemvalue gt Generated C constants public static readonly lt ChoiceType gt lt name gt new lt ChoiceType gt lt ElemCode gt new lt ElemType gt lt elemvalue gt For example consider the following declaration ChoiceType CHOICE oid OBJECT IDENTIFIER id INTEGER value ChoiceType id 1 This would result in the following C constant being generated public static readonly ChoiceType value new ChoiceType ChoiceType _ID new AsnlInteger 1 60 Chapter 5 Generated BER DER CER Encode Methods Two different types of BER Basic Encoding Rules encode methods may be generated using the ASN1C compiler e Memory buffer based definite length backward encoders e Stream based indefinite length forward encoders For DER Distinguished Encoding Rules only the first option is available because a requirement of DER is that all lengths must be in definite form For CER Canonical Encoding Rules only the second option is available because all constructed element lengths must be in indefinite length form Each of these methods are described in the following sections Memory buffer Based Definite Length Encoders For each ASN 1 production defined in the ASN 1 source file a C memory buffer based encode method may be generated These are the default type of encode methods that are generated
167. the Simple API for XML SAX that was described earlier for parsing XML messages How It Works Users of XML parsers are probably already quite familiar with the concepts of SAX Significant events are defined that occur during the parsing of a message As a parser works through a message these events are fired as they occur by invoking user defined callback functions These callback functions are also known as event handler functions A diagram illustrating this parsing process is as follows Parser ASN 1 decode function The events are significant actions that occur during the parsing process The following events are defined that will be passed to the user when an ASN 1 message is parsed 1 StartElement This event occurs when the parser moves into a new element For example if we have a SEQUENCE a b c construct type names omitted this event will fire when we begin parsing a b and c The name of the element is passed to the event handling callback function 2 EndElement This event occurs when the parser leaves a given element space Using the example above these would occur after the parsing of a b and c are complete The name of the element is once again passed to the event handling callback function 3 Characters method This method is defined to pass all of the different types of primitive values that are encountered when parsing a message The primitive values are passed out in a stringified form
168. the encode method The calling arguments were described earlier Finally close the output stream A complete example showing how to invoke an encode method is as follows Note personnelRecord object was previously populated with data AsniMderOutputStream encodeStream null try Step 1 Create an encode output stream ncodeStream new AsniMderOutputStream File OpenWrite filename Step 2 Invoke th ncode method personnelRecord Encod encodeStream useCachedLength false if trace System Console Out WriteLine Encoding was successful catch Exception e 89 Generated MDER Encode Methods System Console Out WriteLine e Message AsnlUtil WriteStackTrace e Console Error return finally try if encodeStream null encodeStream Close catch Exception e Reuse of Encoding Objects The simple example above showed the procedure to encode a single record But what if you had to encode a series of the same type of record over and over again In such cases you can avoid some object creation and garbage collection by reusing objects you have already created The generated classes and the ASNIC runtime classes can often be viewed as reusable containers into which you can simply assign new data To show an example of object reuse suppose we were going to encode a series of octet strings The ASN 1 type for our dat
169. this value would have to have been first encoded and then placed in an Asn OpenType container object Decoding Types with Table Constraints The general procedure to decode an ASN 1 message with table constraint is the same as without table constraints The only difference is that after decoding variable type fields will be replaced with instanced of the actual types they are specified to contain in the associated object set instead of with generic Asn OpenType fields 105 Chapter 13 Generated Print Methods The print option causes print methods to be generated These functions can be used to print the contents of variables of generated types A print method is generated in each of the generated C source files Generated C Method Format and Calling Parameters There are two signatures for generated print methods which are as follows The first signature generated allows printing to any output stream public override void Print System IO StreamWriter outs string varName int level The outs argument specifies a System IO StreamWriter object to which the output will be written The C class System IO Stream may be populated with System Console Out to write directly to standard output The varName argument is used to specify the top level variable name of the item being printed Normally this would be set to the same name as the variable declared in your program that holds the object being printed For example if you declar
170. tion hence there is no need for a return value The general form of an XER encode method is as follows public override void Encode AsnlXerEncodeBuffer buffer string elemName In this case the buffer reference is to an XER encode buffer and an element name argument is added The element name is the name of the element that is to bracket the XML encoded value i e lt elemName gt value lt elemName gt The return type is also void as in the PER case because errors are reported through the exception mechanism Other Methods Other generated methods include the following A private Init method This is generated in constructed types to set all element object references to null prior to decoding A public Print method This is only generated if the print option is specified This provides a formatted printout of the contents of the object The output can be directed to a StreamWriter object A public ElemName property CHOICE only This property retrieves the name of an element within a CHOICE construct give its assigned identifier value The public Set_ lt element gt methods CHOICE only These are generated for each element in a CHOICE construct to allow the CHOICE value to be set Inner Classes The generation of code for XER causes the following inner class definition to be generated public class SaxHandler AsnlXerSaxHandler AsnlXerSaxHandler mElemSaxHandler StringBuffer mCurrElemValue interna
171. tion Object constant calls the Class constructor with the field value specified in the ASN 1 information object definition If the ASN 1 CLASS field is optional and the field value is absent in the Information Object definition then its corresponding member variable will be initialized to null If the ASN 1 CLASS field has a default value and its field value is absent in the Information Object then the generated code for the Information Object will set the Class field s value to the default value ASN 1 definition lt name gt lt ClassName gt lt Info0bject gt Generated C constants 97 Table Constraint Processing public static readonly lt ClassName gt lt name gt new lt ClassName gt lt InfoObject values gt gt For example consider the following Information Object declaration for the above ATTRIBUTE class name ATTRIBUTE WITH SYNTAX VisibleString ID 011 This would result in the following C constant being generated public static readonly ATTRIBUTE name new ATTRIBUTE new AsniVisibleString new AsnlObjectIdentifier new int 0 1 1 NOTE The following new Type Assignment is created for each TypeField s type definition if the type is one of the following ASN 1 built in types Sequence Set SequenceOf SetOf Choice Constrained Type Enumerated Type NamedInteger Type NamedBitList Type ParameterizedType _ lt ObjectName gt _ lt FieldName gt
172. tion section lt isPDU gt 3 An attribute list can be associated with some items This is normally used as a shorthand form for specifying lists of names For example to specify a list of type names to be included in the generated code for a particular module the following would be used lt include types TypeNamel TypeName2 TypeName3 gt The following are some examples of configuration specifications lt asnlconfig gt lt storage gt dynamic lt storage gt lt asnlconfig gt 27 Using the Compiler This specification indicates dynamic storage should be used in all places where its use would result in significant memory usage savings within all modules in the specified source file lt asnlconfig gt lt module gt lt name gt H323 MESSAGES lt name gt lt sourceFile gt h225 asn lt sourceFile gt lt typePrefix gt H225 lt typePrefix gt lt module gt lt asnlconfig gt This specification applies to module H323 MESSAGES in the source file being processed For IMPORT statements involving this module it indicates that the source file h225 asn should be searched for specifications It also indicates that when C or C types are generated they should be prefixed with the H225 This can help prevent name clashes if one or more modules are involved and they contain productions with common names The following tables specify the list of attributes that can be applied at all of the differe
173. to Generate ASNIC Projects coooccccccnccnnccnoconccnnconnconnccnnccnnconnconicnnnos 15 Compiler Configuration Pile comicas coordinar iris serios odie opp earlier sai dias pia 27 Compiler Error Reporting issis Eer S e EEE eo des ade 30 3 Generated C Source Code Overview cipe sn esenee notes a a E a E E E E E R E ES 31 Namespace Specification 2235 0 cs5 gies ieys aie na r E E S E N EEEE EE ESES 32 Class Declaration sois illinois as eee arresi p coves Spe eP fear AEETI EE Era SEa sededes yon 32 Tag Constant is is 33 Public Member Variables seniiti ea e a a aten E a a E A a AT Sa 33 COMSILUCLOIS rot EEEE Lone ces LEE a tects SEA a E es tee ee ove reek Wea 33 Decode Method isidro 34 Encode Method iii eere EEE P Malic cosas teenies bik das weet sah estos ya pists eed sar SES 34 Other A ra parched eeneg sss E E E EE ban E E ses bata aaNeate ies E A E ETES 35 Inner Classes eesi roa rE N EE EE EEE EE E E ees cs a Saat 35 Error Handling sss ssc0sssscsossc3ssecnauaes reep teenaa apo EE ETES OSEP E Eo PESEE EEIEIE tens OGOS a dees 36 4 ASN 1 Type to C Class Mappings vin toc eriten e EEE E EE EEEE EEEE EE EE EEE 37 BOOLEAN corte a yes E a dle pt E AE 37 INTEGER ook re Ghee A ee eds EE ees A ERE en eA 37 BIF STRING ea saek pape Eero liar SEEE ES N AE EEE E SENEE EErEE OTISO ETTAN 38 OCTET SIRING vr peste tote n e A E E E E E E Des e 39 Character String Types eingi E E E EE E a E E a EE E O A TES 40 ENUMERATED eraros riea korre EEA e EEE E Ge
174. tring The string form expects the string to be passed in the ASN 1 value notation format for either a binary string i e xxxx B or a hexadecimal string i e xxxx H Named Bits In the ASN 1 standard it is possible to define an enumerated bit string that specifies named constants for different bit positions ASNIC provides support for this type of construct by generating symbolic constants that can be used to set clear or test these named bits These symbolic constants are simply the bit names and values in the following general form public readonly static int lt name gt lt value gt The base class contains the following methods for using these generated constants Set This method can be used to set a bit in the bit string to be set There is also an overloaded version that takes a boolean value argument that can be used to set the bit to the given boolean value Clear This method can be used to clear the named bit in the bit string Get This method can be used to test if the named bit is set or clear See the Asn BitString class description in the run time section for more details on these methods OCTET STRING The ASN 1 OCTET STRING type is converted to a C class that inherits the Asn OctetString run time class This base class encapsulates the following public member variable public byte mValue The number of octets to be encoded or that were decoded is specified in the built in length component of the
175. tring object to represent Y The logic to process the application tags and the size constraint on the octet string will be generated inline in the encode and decode methods in Z Due to the way some ASN 1 specifications are written this can have a significant effect in reducing the amount of generated code For example in the TAP3 sample program the total number of generated classes was reduced from 20 to 3 117 Chapter 18 ASN1C90 As of ASNIC version 5 7 ASN1C90 is now an option built in to the standard ASNIC executable program This option is 1990 Therefore specifying asnlc lt file gt 1990 on the command line is equivalent to using the old asn1c90 executable program The remaining text in this section refers to using ASNIC with the 1990 option ASNIC when used with the 1990 option contains extensions to handle the older 1990 version of ASN 1 Although this version is no longer supported by the ITU T it is still in use today This version of the compiler also contains logic to parse some common MACRO definitions that are still in widespread use despite the fact that MACRO syntax was retired with this version of the standard The types of MACRO definitions that are supported are ROSE OPERATION and ERROR and SNMP OBJECT TYPE ROSE OPERATION and ERROR ROSE stands for Remote Operations Service Element and defines a request response transaction protocol in which requests to a conforming entity must be answered
176. typeName gt This illustrates the use of the typeCode argument for obtaining information on the ASN 1 type of the data Note that this is a simplified version of an XER formatting method A true implementation would need to do some massaging of the stringified data to fit the XER rules which in general do not follow the ASN 1 value formatting rules The implementation would also need some logic to check if the type wrapper should be output or not it is not always done in certain cases Finally note the constructor and finished method The constructor prints out the outer level wrapper tag Since C does not have destructors a finished method is defined to terminate this tag This method must be called manually from within the application program after the C decode method See the Reader cs program to see how this is done Object registration is done as before in the PrintHandler example The only difference is that an object of the XMLHandler class is created instead of the PrintHandler class When compiled and executed the output from the Reader program looks like this lt PersonnelRecord gt lt name gt lt givenName gt lt IA5String gt John lt IA5String gt lt givenName gt lt initial gt lt IA5String gt P lt IA5String gt lt initial gt lt familyName gt lt IA5String gt Smith lt IA5String gt lt familyName gt lt name gt lt number gt lt INTEGER gt 51 lt INTEGER gt lt number gt
177. ules CER as specified in the ASN 1 standards Using the Compiler Option Argument Description compact compat None lt versionNumber gt This option instructs the compiler to generate more compact code at the expense of some constraint and error checking This is an optimization option that should be used after an application is thoroughly tested Generate code compatible with an older version of the compiler The compiler will attempt to generate code more closely aligned with the given previous release of the compiler lt versionNumber gt is specified as x x for example compat 5 2 config lt filename gt This option is used to specify the name of a file containing configuration information for the source file being parsed A full discussion of the contents of a configuration file is provided in the Compiler Configuration File section csfile cs or a specific cs file name If valued with cs indicates that ASNIC is to generate one cs file for each ASN 1 module processed If valued with a specific cs file name indicates that ASNIC is to generate one cs file to hold all code Do not specify any folder information in the csfile value use the o qualifier instead depends None This option instructs the compiler to generate a full set of C source files that contain only the productions in the main file being compiled and items those pr
178. w this class is used The explicitTagging argument specifies whether or not an explicit tag should be applied to the encoded contents The average user will almost always want to set this argument to true The only time it would not be set to true is if a user wanted to just encode a contents field with no tag This argument is used primarily by the compiler when generating internal calls to properly handle implicit and explicit tagging Unlike the C C version a negative value is never returned form encode methods to indicate an encoding failure That is handled by the exception mechanism All ASNIC C exceptions are derived from the Asn Exception base class See the section on exceptions for a complete list and description of the various exceptions that can be thrown If an I O error occurs then the System Exception is thrown Procedure for Calling C BER Stream Oriented Encode Methods Once an object s member variables have been populated the object s encode method can be invoked to encode the value The general procedure to do this involves the following three steps 1 Create an output stream object into which the value will be encoded 2 Invoke the encode method 3 Close the output stream The first step is the creation of an output stream object There are two forms of the constructor a constructor with one parameter System IO Stream reference and one that allows specification of an internal buffer size A larger internal buff
179. when the ber command line option is selected To generate stream based forward encoders the stream option must be specified as well An encode method is only generated if it is required to alter the encoding of the base class method The C model is built on inheritance from a set of common run time base classes These run time classes contain default implementations of encode decode methods that handle the encoding decoding of the basic types These default implementations include support for adding the universal tags associated with the types as defined in the X 680 standard So for simple assignments the generation of an encode method is not necessary For example the following production will not result in the generation of an encode method X INTEGER In this case the generated C class inherits the Asn 1 Integer base class and the default encode method within this class is sufficient to encode a value of the generated type However if the type is altered to contain a tag or constraint then a custom encode method would be generated X APPLICATION 1 INTEGER In this case special logic is necessary to apply the tag value Some types will always cause encode methods to be generated At the primitive level this is true for the ENUMERATED type This type will always contain a custom set of enumerated values All constructed types SEQUENCE SET SEQUENCE SET OF and CHOICE will cause encode methods to be added
180. with the result or errors defined in operation definitions Variations of this are used in a number of protocols in use today including CSTA and TCAP The definition of the ROSE OPERATION MACRO that is built into the ASN1C90 version of the compiler is as follows OPERATION MACRO e BEGIN TYPE NOTATION Parameter Result Errors LinkedOperations VALUE NOTATION value VALUE INTEGER Parameter ArgKeyword NamedType empty ArgKeyword ARGUMENT PARAMETER Result RESULT ResultType empty Errors ERRORS ErrorNames empty LinkedOperations LINKED LinkedOperationNames empty ResultType NamedType empty ErrorNames ErrorList empty ErrorList Error Errorlist Error Error value ERROR shall reference an error value type shall reference an error type if no error value is specified LinkedOperationNames OperationList empty OperationList Operation OperationList Operation Operation value OPERATION shall reference an operation value type shall reference an operation type if no operation value is specified NamedType identifier type type END This MACRO does not need to be defined in the ASN 1 specification to be parsed In fact any attempt to redefine this MACRO will be ignored Its definition is hard coded into the compiler What the compile
181. within a try catch block try pdu Encod encodeBuffer if trace System Console Out WriteLine Encoding was successful System Console Out WriteLine Hex dump of encoded record ncodeBuffer HexDump System Console Out WriteLine Binary dump encodeBuffer BinDump Invoke Step 3 Access th ncoded message component In this case we use methods in the class to write the component to a file and output a formatted dump to the message dmp file Write th ncoded record to a file encodeBuffer Write new System 10 FileStream filename System IO FileMode Create Generate a dump file for comparisons System 10 StreamWriter messagedmp new System IO message d messagedmp Autor ncodeBuffer Hex mp lu r sh true Dump messagedmp StreamWriter new System 1I0 FileStream System IO FileMode Create We can also directly access the buffer as follows 104 Table Constraint Processing byte buffer encodeBuffer Buffer int msglen encodeBuffer MsgByteCnt catch Exception e System Console Out WriteLine e Message AsnlUtil WriteStackTrace e Console Error return The important thing to note is that not much changes from the normal procedure The only significant difference is that now the argument field can be directly populated with an instance of its target type Without table constraint checking logic
Download Pdf Manuals
Related Search
Related Contents
ENTRETIENS PROFESSIONNELS MODE D`EMPLOI 1/ Quelques 入札説明書 METRAHIT 27M, 27I et H+E CAR Milliohmmètre et multimètre BENADO EFFECTS user manual Samsung ED65C 用戶手冊 WD 1 (M) / WD 1000 Betriebsanleitung Supra eKEY® for BlackBerry® Products User Manual RUL形キャピネツト ` 取扱説明書 ASSACRIL LATEX Method and apparatus for providing a more powerful user Copyright © All rights reserved.
Failed to retrieve file