NG-RAN E1AP C# Sample Code Using OSS ASN.1 Tools


This sample is provided as part of the OSS ASN.1 Tools trial and commercial shipments. The source code and related files are listed below for reference.

The sample demonstrates how to use the OSS ASN.1 Tools to process messages for the NG-RAN E1AP standard (TS 37.483 version 19.0.0).

It runs on Windows as an example and illustrates how to decode, inspect, and create PER-encoded E1AP messages using the OSS ASN.1 Tools API.

The sample reads E1AP messages from .per files, decodes and prints them, and creates and encodes a response message.

A Windows batch script (run.bat) is included for running the test program using the OSS ASN.1/C# runtime.

To explore more samples (LTE RRC, 5G RRC, S1AP, X2AP), visit the main Sample Code page.

Overview

This sample shows how to:

  • Initialize the OSS ASN.1/C# runtime for the E1AP schema.
  • Read .per files that contain valid PER-encoded E1AP messages.
  • Decode and print E1AP messages.
  • Create and encode a response message.
  • Run the sample test program using the provided run.bat script.

Files in This Sample

The files listed below are included in the OSS ASN.1 Tools trial and commercial shipments and are used by this sample program:

File Description
README.TXT Instructions and sample overview.
*.asn ASN.1 source files that describe the 3GPP NG-RAN E1AP protocol (TS 37.483) used with this program example.
E1AP-PDU_Reset.per Valid PER-encoded E1AP message. It should pass testing.
app.cs Simple C# program that shows how to work with NG-RAN E1AP protocol data. It reads input messages from files, decodes and prints them, and creates and encodes a response message.
run.bat Windows batch script that runs the sample test.
gui/ ASN.1 Studio project for viewing/compiling schema and generating sample data.

Build and Run Instructions

(Installation instructions for the OSS ASN.1 Tools are included in all trial and commercial shipments.)

To build and run this sample, install a trial or licensed version of the OSS ASN.1 Tools for C#.

1. Verify environment variables (if not using the OSS command prompt)

If you use the OSS command prompt window, you do not need to set environment variables to run this sample. Otherwise, ensure the following are defined:

  • OSS_CSHARP_HOME
  • PATH (must include the OSS bin directory)

If using Visual Studio, run the Microsoft vsvars32.bat script to set up the .NET command-line environment. If Visual Studio is not installed, ensure your PATH includes the required .NET directories. For details, see ossvars.bat installed with the product.

2. Run the sample
run
3. Clean up generated files
run clean
4. Other Platforms

Note: The C# source code in this sample is platform-independent. Windows commands are shown as an example, but equivalent samples and run instructions may be available for other platforms. For help with platform-specific instructions, please contact OSS Support.

Code Listing: app.cs

The following listing shows the main C# source file for this sample test program, app.cs. It demonstrates how to read PER-encoded E1AP messages from files, decode and print them, and create and encode a response message using the OSS ASN.1 Tools API.

Show app.cs source code
///////////////////////////////////////////////////////////////////////////////
// Copyright (C) ###RELEASE_YEAR### OSS Nokalva, Inc. All rights reserved.                 //
//                                                                           //
// THIS FILE IS PROPRIETARY MATERIAL OF OSS NOKALVA, INC.                    //
// AND MAY BE USED ONLY BY DIRECT LICENSEES OF OSS NOKALVA, INC.             //
// THIS FILE MAY NOT BE DISTRIBUTED.                                         //
// THIS COPYRIGHT STATEMENT MAY NOT BE REMOVED.                              //
///////////////////////////////////////////////////////////////////////////////
// THIS SAMPLE PROGRAM IS PROVIDED AS IS. THE SAMPLE PROGRAM AND ANY RESULTS //
// OBTAINED FROM IT ARE PROVIDED WITHOUT ANY WARRANTIES OR REPRESENTATIONS,  //
// EXPRESS, IMPLIED OR STATUTORY.                                            //
///////////////////////////////////////////////////////////////////////////////

//
// Demonstrates part of the 5G E1AP protocol.
//


// Classes generated from ASN.1 specification.
using E1ap;
using E1ap.E1APPDUDescriptions;
using E1ap.E1APPDUContents;
using E1ap.E1APContainers;
using E1APConstants = E1ap.E1APConstants.Values;
using E1ap.E1APIEs;

// Classes from the OSS runtime library.
using Oss.Asn1;

// C# system classes.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;


public class Program
{
    public static int Main(string[] args)
    {
        try
        {
            // A folder with encoded messages.
            string dataDir = (args.Length > 0) ? args[0] : "../../";
            Te1ap te1ap = new Te1ap();
            te1ap.Process(dataDir, "E1AP-PDU_Reset.per");
            Console.WriteLine("Message processing has completed successfully.");
            return 0;
        }
        catch (Exception e)
        {
            // Print complete exception information.
            Console.WriteLine("ERROR: Error processing input files.");
            Console.WriteLine(e);
            return 1;
        }
    }
}

/// <summary>
/// Does all the processing of the files with encoded PDUs.
/// </summary>
public class Te1ap
{
    PerAlignedCodec codec = new PerAlignedCodec();
    /// <summary>
    /// Processes a file with encoded E1AP PDU.
    /// </summary>
    public void Process(String dataDir, String fileName)
    {
        try
        {
            String fullPath = Path.Combine(dataDir, fileName);
            E1APPDU req = DecodeRequest(fullPath);
            Console.WriteLine("\nPrinting the PER-Decoded E1APPDU PDU...\n");
            ValueNotationFormatter.Print(req, Console.Out);
            E1APPDU res = CreateResponse(req);
            if (res != null) {
                Console.WriteLine("\nPrinting the created E1APPDU response PDU...\n");
                ValueNotationFormatter.Print(res, Console.Out);
                EncodeAndSend(res);
            }
            Console.WriteLine();
        }
        catch (Exception e)
        {
            throw new Exception("Unable to process file '" + fileName + "'.", e);
        }
    }

    /// <summary>
    /// Creates E1APPDU response PDUs.
    /// </summary>
    E1APPDU CreateResponse(E1APPDU request)
    {
        // Check that the message contains InitiatingMessage.
        if (request.Selected != E1APPDU.Id.InitiatingMessageChosen)
            throw new Exception("ERROR: Wrong message.  Expecting InitiatingMessage.");

        InitiatingMessage msg = request.InitiatingMessage;
        ProcedureCode code = ProcedureCodes.ContainsKey(msg.ProcedureCode) ? ProcedureCodes[msg.ProcedureCode] : ProcedureCode.Unknown;

        switch (code) {
            case ProcedureCode.Reset:
                {
                    Reset req = (Reset)msg.Value.Decoded;
                    AccessResetIEs(req);
                    return CreateResetAcknowledge(req);
                }
            case ProcedureCode.Unknown:
                Console.WriteLine("WARNING: Got unknown ProcedureCode: " + msg.ProcedureCode);
                return null;
            default:
                Console.WriteLine("WARNING: ProcedureCode " + code + " not implemented yet.");
                return null;
        }
    }

    /// <summary>
    /// Creates a ResetAcknowledge PDU.
    /// </summary>
    public E1APPDU CreateResetAcknowledge(Reset req)
    {
        Console.WriteLine("\nCreating a ResetAcknowledge E1APPDU PDU message...");
        Reset.ProtocolIEsType request_IEs = req.ProtocolIEs;

        if (request_IEs == null || request_IEs.Count == 0)
        {
            Console.WriteLine("No IEs in the HandoverRequired message.");
            return null;
        }
        ResetAcknowledge.ProtocolIEsType response_IEs = new ResetAcknowledge.ProtocolIEsType();
        // Add TransactionID to outcome message
        response_IEs.Add(new ResetAcknowledge.ProtocolIEsType.Element()
        {
            Id = E1APConstants.IdTransactionID,
            Criticality = E1ap.E1APCommonDataTypes.Criticality.Reject,
            Value = new OpenType(
                new TransactionID()
                {
                    Value = 7
                })
        });
        ResetAcknowledge resetAcknowledge = new ResetAcknowledge()
        {
            ProtocolIEs = response_IEs
        };
        SuccessfulOutcome successfulOutcome = new SuccessfulOutcome()
        {
            ProcedureCode = E1APConstants.IdReset,
            Criticality = E1ap.E1APCommonDataTypes.Criticality.Reject,
            Value = new OpenType(resetAcknowledge)
        };
        E1APPDU pdu = new E1APPDU()
        {
            SuccessfulOutcome = successfulOutcome
        };
        Console.WriteLine("Created the E1APPDU response PDU successfully.\n");
        return pdu;
    }

    /// <summary>
    /// Decodes an E1APPDU request PDU from a file.
    /// </summary>
    E1APPDU DecodeRequest(String fileName)
    {
        using (Stream stream = File.OpenRead(fileName))
        {
            /// <summary>
            ///  Set the decoder to autodecode open type values.
            /// </summary>
            codec.DecoderOptions.AutoDecode = true;
            Console.WriteLine("\nDecoding the E1APPDU request PDU from the file " + fileName + "...");
            E1APPDU msg = new E1APPDU();
            codec.Decode(stream, msg);
            Console.WriteLine("PDU decoded successfully.");
            return msg;
        }
    }

    /// <summary>
    /// Enumerates possible procedure codes.
    /// </summary>
    public enum ProcedureCode {
        Reset,
        Unknown
    }

    static Dictionary<int, ProcedureCode> ProcedureCodes = new Dictionary<int, ProcedureCode>() {
        {E1APConstants.IdReset, ProcedureCode.Reset}
    };

    /// <summary>
    /// Demonstrates how components of the Reset can
    /// be accessed in the code.
    /// </summary>
    /// <param name="req">A Reset message.</param>
    public void AccessResetIEs(Reset req)
    {
        Console.WriteLine("\nAccessing IEs of the Reset message...\n");
        int ordinal = 0;
        foreach (Reset.ProtocolIEsType.Element ie in req.ProtocolIEs) {
            ++ordinal;
            Console.WriteLine("IE #{0}:\nid {1}\ncriticality {2}", ordinal, ie.Id, ie.Criticality);
            if (ie.Id == E1APConstants.IdTransactionID) {
                TransactionID v = (TransactionID)ie.Value.Decoded;
                Console.WriteLine("value TransactionID: {0}\n", v.Value);
            }
            else if (ie.Id == E1APConstants.IdResetType) {
                ResetType v = (ResetType)ie.Value.Decoded;
                Console.Write("value ResetType: ");
                switch (v.Selected)
                {
                    case ResetType.Id.E1InterfaceChosen:
                        Console.WriteLine("e1-interface: {0}\n", v.E1Interface);
                        break;
                    case ResetType.Id.PartOfE1InterfaceChosen:
                        {
                            Console.WriteLine("partOfE1-Interface: ");
                            var uE_ass_Con = v.PartOfE1Interface;
                            int n = 0;
                            foreach (var entry in uE_ass_Con)
                            {
                                Console.WriteLine("    #{0}:\n    id {1}\n    criticality {2}",
                                    ++n, entry.Id, entry.Criticality);
                                UEAssociatedLogicalE1ConnectionItem item =
                                    (UEAssociatedLogicalE1ConnectionItem)entry.Value.Decoded;
                                Console.WriteLine("    value GNB-CU-CP-UE-E1AP-ID: {0}", item.GNBCUCPUEE1APID);
                                Console.WriteLine("    value GNB-CU-UP-UE-E1AP-ID: {0}\n", item.GNBCUUPUEE1APID);
                            }
                        }
                        break;
                }
            }
            else if (ie.Id == E1APConstants.IdCause)
            {
                Cause v = (Cause)ie.Value.Decoded;
                Console.Write("value Cause: ");
                switch (v.Selected)
                {
                    case Cause.Id.RadioNetworkChosen:
                        Console.WriteLine("radioNetwork: {0}\n", v.RadioNetwork);
                        break;
                    case Cause.Id.TransportChosen:
                        Console.WriteLine("transport: {0}\n", v.Transport);
                        break;
                    case Cause.Id.ProtocolChosen:
                        Console.WriteLine("protocol: {0}\n", v.Protocol);
                        break;
                    case Cause.Id.MiscChosen:
                        Console.WriteLine("misc: {0}\n", v.Misc);
                        break;
                }
            }
            else {
                if (ie.Value.Decoded != null)
                    Console.WriteLine(ie.Value.Decoded);
                else
                    Console.WriteLine("IE left undecoded: {0}\n", BytesToString(ie.Value.Encoded));
            }
        }
    }

    /// <summary>
    /// A utility method to print octets.
    /// </summary>
    /// <param name="bytes">The byte[] value </param>
    /// <returns></returns>
    private string BytesToString(byte[] bytes)
    {
        StringBuilder sb = new StringBuilder(2 * bytes.Length + 3);
        sb.Append("'");
        foreach (byte b in bytes)
            sb.Append(b.ToString("X2"));
        sb.Append("'H");
        return sb.ToString();
    }

    /// <summary>
    /// Dumps binary data to the TextWriter.
    /// </summary>
    /// <param name="data">The binary data</param>
    /// <param name="tty">The TextWriter where the hex dump is written</param>
    private void HexDump(byte[] data, TextWriter tty)
    {
        ValueNotationFormatter.Print(data, data.Length, tty);
    }

    /// <summary>
    /// Encodes and sends a message.
    /// </summary>
    void EncodeAndSend(E1APPDU message)
    {
        // Assert the validity of the response messages
        codec.EncoderOptions.Validate = true;
        try
        {
            using (MemoryStream stream = new MemoryStream()) {
                Console.WriteLine("Encoding the E1APPDU response PDU using memory stream...");
                codec.Encode(message, stream);
                Console.WriteLine("Encoded successfully.\n");
                Console.WriteLine("Printing the E1APPDU response PDU in " + stream.Length + " bytes...");
                HexDump(stream.ToArray(), Console.Out);
            }
            Console.WriteLine("\nEncoding the E1APPDU response PDU again using a class object...");
            byte[] encoded = codec.Encode(message);
            Console.WriteLine("Encoded successfully.\n");
            Console.WriteLine("Printing the E1APPDU response PDU in " + encoded.Length + " bytes...");
            HexDump(encoded, Console.Out);
        }
        catch (Exception e)
        {
            throw new Exception("ERROR: Failed to encode.", e);
        }
    }
}

Expected Output (Excerpt)

This is the expected output when running the sample:

Decoded E1AP message:
  ...
Encoding response message...
Encoding successful.

ASN.1 Schema Excerpt (e1ap.asn)

Show excerpt from e1ap.asn
-- Excerpt from e1ap.asn 3GPP TS 37.483 V19.0.0 (2025-09) 
-- **************************************************************
--
-- Elementary Procedure definitions
--
-- **************************************************************

E1AP-PDU-Descriptions {
itu-t (0) identified-organization (4) etsi (0) mobileDomain (0)
ngran-access (22) modules (3) e1ap (5) version1 (1) e1ap-PDU-Descriptions (0) }

DEFINITIONS AUTOMATIC TAGS ::= 

BEGIN

-- **************************************************************
--
-- IE parameter types from other modules
--
-- **************************************************************

IMPORTS
	Criticality,
	ProcedureCode

FROM E1AP-CommonDataTypes
	Reset,
	ResetAcknowledge,
	ErrorIndication,
	GNB-CU-UP-E1SetupRequest,
	GNB-CU-UP-E1SetupResponse,
	GNB-CU-UP-E1SetupFailure, 
	GNB-CU-CP-E1SetupRequest,
	GNB-CU-CP-E1SetupResponse,
	GNB-CU-CP-E1SetupFailure, 
	GNB-CU-UP-ConfigurationUpdate,
	GNB-CU-UP-ConfigurationUpdateAcknowledge,
	GNB-CU-UP-ConfigurationUpdateFailure,
	GNB-CU-CP-ConfigurationUpdate,
	GNB-CU-CP-ConfigurationUpdateAcknowledge,
	GNB-CU-CP-ConfigurationUpdateFailure,
	BCBearerContextSetupRequest,
	BCBearerContextSetupResponse,
	BCBearerContextSetupFailure,
	BCBearerContextModificationRequest,
	BCBearerContextModificationResponse,
	BCBearerContextModificationFailure,
	BCBearerContextModificationRequired,
	BCBearerContextModificationConfirm,
	BCBearerContextReleaseCommand,
	BCBearerContextReleaseComplete,
	BCBearerContextReleaseRequest,
	BearerContextSetupRequest,
	BearerContextSetupResponse,
	BearerContextSetupFailure,
	BearerContextModificationRequest,
	BearerContextModificationResponse,
	BearerContextModificationFailure,
	BearerContextModificationRequired,
	BearerContextModificationConfirm,
	BearerContextReleaseCommand,
	BearerContextReleaseComplete,
	BearerContextReleaseRequest,
	BearerContextInactivityNotification,
	DLDataNotification,
	ULDataNotification,
	DataUsageReport,
	E1ReleaseRequest,
	E1ReleaseResponse,
	GNB-CU-UP-CounterCheckRequest,
	GNB-CU-UP-StatusIndication,
	MCBearerContextSetupRequest,
	MCBearerContextSetupResponse,
	MCBearerContextSetupFailure,
	MCBearerContextModificationRequest,
	MCBearerContextModificationResponse,
	MCBearerContextModificationFailure,
	MCBearerContextModificationRequired,
	MCBearerContextModificationConfirm,
	MCBearerNotification,
	MCBearerContextReleaseCommand,
	MCBearerContextReleaseComplete,
	MCBearerContextReleaseRequest,
	MRDC-DataUsageReport,
	DeactivateTrace,
	TraceStart,
	PrivateMessage,
	ResourceStatusRequest,
	ResourceStatusResponse,
	ResourceStatusFailure,
	ResourceStatusUpdate,
	IAB-UPTNLAddressUpdate,
	IAB-UPTNLAddressUpdateAcknowledge,
	IAB-UPTNLAddressUpdateFailure,
	CellTrafficTrace,
	EarlyForwardingSNTransfer,
	GNB-CU-CPMeasurementResultsInformation,
	IABPSKNotification,
	DataCollectionRequest,
	DataCollectionResponse,
	DataCollectionFailure,
	DataCollectionUpdate

FROM E1AP-PDU-Contents
	id-reset,
	id-errorIndication,
	id-gNB-CU-UP-E1Setup,
	id-gNB-CU-CP-E1Setup,
	id-gNB-CU-UP-ConfigurationUpdate,
	id-gNB-CU-CP-ConfigurationUpdate,
	id-e1Release,
	id-bearerContextSetup,
	id-bearerContextModification,
	id-bearerContextModificationRequired,
	id-bearerContextRelease,
	id-bearerContextReleaseRequest,
	id-bearerContextInactivityNotification,
	id-dLDataNotification,
	id-uLDataNotification,
	id-dataUsageReport,
	id-gNB-CU-UP-CounterCheck,
	id-gNB-CU-UP-StatusIndication,
	id-mRDC-DataUsageReport,
	id-DeactivateTrace,
	id-TraceStart,
	id-privateMessage,
	id-resourceStatusReportingInitiation,
	id-resourceStatusReporting,
	id-iAB-UPTNLAddressUpdate,
	id-CellTrafficTrace,
	id-earlyForwardingSNTransfer,
	id-gNB-CU-CPMeasurementResultsInformation,
	id-iABPSKNotification,
	id-BCBearerContextSetup,
	id-BCBearerContextModification,
	id-BCBearerContextModificationRequired,
	id-BCBearerContextRelease,
	id-BCBearerContextReleaseRequest,
	id-MCBearerContextSetup,
	id-MCBearerContextModification,
	id-MCBearerContextModificationRequired,
	id-MCBearerNotification,
	id-MCBearerContextRelease,
	id-MCBearerContextReleaseRequest,
	id-dataCollectionReportingInitiation,
	id-dataCollectionReporting

FROM E1AP-Constants;

-- **************************************************************
--
-- Interface Elementary Procedure Class
--
-- **************************************************************

E1AP-ELEMENTARY-PROCEDURE ::= CLASS {
	&InitiatingMessage				,
	&SuccessfulOutcome							OPTIONAL,
	
&UnsuccessfulOutcome						OPTIONAL,
	&procedureCode				ProcedureCode 	UNIQUE,
	&criticality				Criticality 	DEFAULT ignore
}
WITH SYNTAX {
	INITIATING MESSAGE			&InitiatingMessage
	[SUCCESSFUL OUTCOME			&SuccessfulOutcome]
	[UNSUCCESSFUL OUTCOME		&UnsuccessfulOutcome]
	PROCEDURE CODE				&procedureCode
	[CRITICALITY				&criticality]
}

-- **************************************************************
--
-- Interface PDU Definition
--
-- **************************************************************

E1AP-PDU ::= CHOICE {
	initiatingMessage		InitiatingMessage,
	successfulOutcome		SuccessfulOutcome,
	unsuccessfulOutcome		UnsuccessfulOutcome,
	...
}

InitiatingMessage ::= SEQUENCE {
	procedureCode			E1AP-ELEMENTARY-PROCEDURE.&procedureCode		({E1AP-ELEMENTARY-PROCEDURES}),
	criticality				E1AP-ELEMENTARY-PROCEDURE.&criticality			({E1AP-ELEMENTARY-PROCEDURES}{@procedureCode}),
	value					E1AP-ELEMENTARY-PROCEDURE.&InitiatingMessage	({E1AP-ELEMENTARY-PROCEDURES}{@procedureCode})
}

SuccessfulOutcome ::= SEQUENCE {
	procedureCode			E1AP-ELEMENTARY-PROCEDURE.&procedureCode		({E1AP-ELEMENTARY-PROCEDURES}),
	criticality				E1AP-ELEMENTARY-PROCEDURE.&criticality			({E1AP-ELEMENTARY-PROCEDURES}{@procedureCode}),
	value					E1AP-ELEMENTARY-PROCEDURE.&SuccessfulOutcome	({E1AP-ELEMENTARY-PROCEDURES}{@procedureCode})
}

UnsuccessfulOutcome ::= SEQUENCE {
	procedureCode			E1AP-ELEMENTARY-PROCEDURE.&procedureCode		({E1AP-ELEMENTARY-PROCEDURES}),
	criticality				E1AP-ELEMENTARY-PROCEDURE.&criticality			({E1AP-ELEMENTARY-PROCEDURES}{@procedureCode}),
	value					E1AP-ELEMENTARY-PROCEDURE.&UnsuccessfulOutcome	({E1AP-ELEMENTARY-PROCEDURES}{@procedureCode})
}

Using ASN.1 Studio (Optional)

The gui/ subdirectory contains an ASN.1 Studio project for this sample. With ASN.1 Studio you can:

  • Open the E1AP ASN.1 modules.
  • Generate code from the ASN.1 schema.
  • Create and edit sample encoded E1AP messages.
  • Export each project to a Visual Studio project.

Related Samples

Disclaimer

This sample is provided solely for illustration purposes, for example to demonstrate usage of the OSS ASN.1 Tools API with NG-RAN E1AP messages. It does not represent a complete application. To build and run this sample, you must use a trial or licensed version of the appropriate OSS ASN.1 Tools. The copyright and license statements included in each source file remain fully applicable.

Need Help?

If you have questions about using this sample, contact OSS Nokalva Support.

See Also