Source code for the AS2 Server VB .NET example posted at EDIINT AS2.  A detailed explanation of the algorithm can be read at "An AS2 Server example".

Public Class As2Server

    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not IsPostBack Then

            'Get Http header so that it can be included in the oMailDoc object during LoadContent
            Dim sHttpHeader As String = ""

            'Put user code to initialize the page here
            'Get Http header so that it can be included in the oMailDoc object during LoadContent
            sHttpHeader = Request.ServerVariables("ALL_RAW")

            'saves AS2 message into a file without http headers.
            Dim uploadFileName As String = SaveAS2ToFile(Request, sHttpHeader)

            'processes the uploaded AS2 message, and then replies back an MDN syncronously or asyncronously
            Dim MDNResult As String = ProcMDN(uploadFileName, sHttpHeader)

        End If

    End Sub

    Private Function SaveAS2ToFile(ByRef Request As HttpRequest, sHttpHeader As String) As String


        If Not IsPostBack Then

            Try
                Const bufferSize As Integer = 512
                Dim fsAs2 As FileStream = Nothing
                Dim writerAs2 As BinaryWriter = Nothing
                Dim reader As BinaryReader = Nothing

                'path of file that is being received
                Dim uploadFileName As String = ConfigurationManager.AppSettings("uploadDirectory") + "\\" + Session.SessionID.Trim() + ".bin"

                'write stream of uploaded file to a file
                fsAs2 = New FileStream(uploadFileName, FileMode.Create, FileAccess.Write)
                writerAs2 = New BinaryWriter(fsAs2)

                reader = New BinaryReader(Request.InputStream)

                If Request.ContentLength > 0 Then

                    While reader.PeekChar >= 0
                        writerAs2.Write(reader.ReadBytes(bufferSize))
                    End While

                End If
                writerAs2.Close()
                reader.Close()
                fsAs2.Close()
                writerAs2.Dispose()
                reader.Dispose()
                fsAs2.Dispose()

                'saves header (not necessary, but useful for troubleshooting)
                If sHttpHeader <> "" Then
                    Dim uploadFileNameHeader As String = ConfigurationManager.AppSettings("uploadDirectory") + "\\" + Session.SessionID.Trim() + ".hdr.txt"
                    Dim oWriter As StreamWriter

                    oWriter = New StreamWriter(uploadFileNameHeader)
                    oWriter.Write(sHttpHeader)
                    oWriter.Close()
                    oWriter.Dispose()
                End If

                Return uploadFileName
            Finally

            End Try
        Else
            Return ""
        End If

    End Function

    Private Function ProcMDN(ByVal AS2FileName As String, sHttpHeader As String) As String

        If Not IsPostBack Then

            Dim oEdiDoc As ediDocument
            Dim oSchemas As ediSchemas
            Dim i As Integer

            Dim sPath As String = AppDomain.CurrentDomain.BaseDirectory
           
            Dim sSaveFilePath As String = ConfigurationManager.AppSettings("processDirectory") + "\\" + Session.SessionID.Trim()

            oEdiDoc = New ediDocument()

            oEdiDoc.Property(DocumentPropertyIDConstants.Property_Execution_Log) = sSaveFilePath & "_log.txt"

            'Use certificates in Local Machine
            oEdiDoc.Option(DocumentOptionIDConstants.OptDocument_MachineKeySet) = 1

            'set cursor type to forward only
            oEdiDoc.CursorType = DocumentCursorTypeConstants.Cursor_ForwardOnly

            'security settings
            Dim oSecurities As ediSecurities
            oSecurities = oEdiDoc.GetSecurities()
            oSecurities.DefaultProviderName = "Microsoft Strong Cryptographic Provider"
            oSecurities.DefaultCertSystemStoreLocation = "LocalMachine"
            oSecurities.DefaultCertSystemStoreName = "My"
            oSecurities.DefaultKeyContainer = "EDIDEV_SRV_DEMO_COMPANY_Keys"    'Test

            'Disable internal standard reference library
            ediSchemas.Set(oSchemas, oEdiDoc.GetSchemas)
            oSchemas.EnableStandardReference = False

            ' Load into RAM only the SEF file that is being used
            oSchemas.Option(SchemasOptionIDConstants.OptSchemas_SetOnDemand) = 1

            Dim oMailDoc As mailDocument
            oMailDoc = oEdiDoc.GetMailDocument()

            ' RFC4130. The address in the "Disposition-Notification-To" is not used to identify where to 
            '   return the MDN.  Receiving applications MUST ignore the value and MUST not complain about 
            '   RFC 2822 address syntax violations.  For AS2, this field is redefined as generic text so that
            '   any string is accepted.
            oMailDoc.AddDefinedHeader("Disposition-Notification-To", MailMessageHeaderTypeConstants.HeaderType_FieldText, RequirementTypeConstants.Requirement_Optional)
            'oMailDoc.AddDefinedHeader("Receipt-delivery-option", MailMessageHeaderTypeConstants.HeaderType_FieldText, RequirementTypeConstants.Requirement_Optional)
            oMailDoc.AddDefinedHeader("Message-ID", MailMessageHeaderTypeConstants.HeaderType_FieldText, RequirementTypeConstants.Requirement_Mandatory)
            oMailDoc.AddDefinedHeader("Original-Message-ID", MailMessageHeaderTypeConstants.HeaderType_FieldText, RequirementTypeConstants.Requirement_Mandatory)
            'oMailDoc.AddDefinedHeader("Cookie", MailMessageHeaderTypeConstants.HeaderType_FieldText, RequirementTypeConstants.Requirement_Optional)

            'change default properties of boundaries
            oMailDoc.Property(MailDocPropertyIDConstants.MailDocProp_Boundary) = "CompanyX.Electronic.Document.Boundary"
            oMailDoc.Property(MailDocPropertyIDConstants.MailDocProp_BoundaryMdn) = "CompanyX.Electronic.Document.Boundary.mdn"
            oMailDoc.Property(MailDocPropertyIDConstants.MailDocProp_BoundarySign) = "CompanyX.Electronic.Document.Boundary.sign"

            Dim oMDN As mailMessage
            oMDN = oMailDoc.GetMDN()

            ' you can add your own MDN headers at this time
            ' oMDN.set_HeaderFieldValue("Received-Content-MIC", " ");
            ' oMDN.set_HeaderFieldValue("Final-Receipient", "1234");

            Dim oMdnSecurity As ediSecurity
            oMdnSecurity = oMDN.GetSecurity()
            oMdnSecurity.CertificateSignerName = "EDIDEV SRV DEMO COMPANY"     'Test

            ' Prevent any processing at this point.  Just load the raw document.
            oMailDoc.Option(MailDocOptionIDConstants.MailDocOpt_Auto) = 0

            ' This option means not to process the EDI file in the content when the process method is called. We only want to process
            ' the mail document upto a point where we can determine the content type.
            oMailDoc.Option(MailDocOptionIDConstants.MailDocOpt_EnableEdi) = 0

            ' Use certificates in the cretificate store only. (Not in files.) Must enable this to verify signed messages.
            oMailDoc.Option(MailDocOptionIDConstants.MailDocOpt_UseCertStoreOnly) = 1

            ' Load the mail file that was just received from the client.  If the client had requested that an MDN be generated then 
            ' the MDN is also generated internally at this point.
            ' Load the http headers with the As2 file
            If oMailDoc.LoadContent(AS2FileName, sHttpHeader) <> 1 Then
                ' "Failed to load AS2"
            Else
                ' Saving the mail document at this point is not necessary, but is saved for troubleshooting if need be.
                oMailDoc.Save(sSaveFilePath + "_MailDoc.bin")
                
                Dim oMessage As mailMessage
                oMessage = oMailDoc.GetMessageContent()

                ' Check to see if there is a value in the header 'Receipt-Delivery-Option' and
                '   if there is then this is an asynchronous session.
                Dim sReceiptDeliveryOption As String = oMessage.HeaderFieldValue("Receipt-delivery-option")

                Dim oReceiptURI As mailInternetURI
                oReceiptURI = oMessage.GetHeaderTypeURI("Receipt-delivery-option")

                ' The component automatically detects what algorithm was used to encrypt the message and uses the same algorithm to decrypt the it.
                ' If you wish to know what algorithm was used to encrypt the message, then call the DecryptAlgorithm method.
                'Dim oMsgSecurity As ediSecurity = oMessage.GetSecurity()
                'Dim oSecurityEncryptionCfg As ediSecurityEncryptionCfg = oMsgSecurity.GetEncryptionConfig()
                'Dim sCfgDecryptAlgorithm As String = oSecurityEncryptionCfg.DecryptAlgorithm
                'Dim sDecryptAlgorithm As String = oMsgSecurity.DecryptAlgorithm
                'Dim sSignDigest As String = oMsgSecurity.GetSignDigest(EncodingMechanismTypeConstants.EncodeType_Base64)

                ' It's not necessary to process in steps, but good for troubleshooting.  To process in steps, use the ProcessStep method.
                Dim sContentTransferEncoding As String = oMessage.HeaderFieldValue("Content-Transfer-Encoding").ToLower()
                ' If the file was encoded in base64, this step will decode it only.
                If sContentTransferEncoding = "base64" Then
                    oMessage.ProcessStep()
                    oMessage.Save(sSaveFilePath + "_MessageAfterBase64Process.bin")
                End If

                sContentTransferEncoding = oMessage.HeaderFieldValue("Content-Transfer-Encoding").ToLower()
                ' If the file was encrypted, this step will decrypt it only.
                If sContentTransferEncoding = "base64" Then
                    oMessage.ProcessStep()
                    oMessage.Save(sSaveFilePath + "_MessageAfterBinaryProcessProcess.bin")
                End If

                ' Do all other processes to get to the Content Type of the file.
                oMailDoc.Process()
                oMailDoc.Save(sSaveFilePath + "_ContentType.bin")

                'Get EDI from message so that it will be saved to a file
                Dim oMailBody As mailBody
                oMailBody = oMessage.GetBody()

                'Get the content type of the EDI message so that it can be processed appropriately
                Dim sTypeMessage As String = oMessage.HeaderFieldValue("Content-Type")

                If LCase(sTypeMessage) = "application/edi-x12" Then 'EDI is X12
                    'Export the EDI part of the message into a file
                    oMailBody.Export(sSaveFilePath + ".X12")

                    'Load all pertaining X12 SEF files here. This is not necessary if you do 
                    'not wish to include the validation results in the MDN

                    oEdiDoc.LoadSchema(sPath + "SEF/sample_850_X12-4010.SEF", SchemaTypeIDConstants.Schema_Standard_Exchange_Format)
                    oEdiDoc.LoadSchema(sPath + "SEF/sample_837_X098.SEF", SchemaTypeIDConstants.Schema_Standard_Exchange_Format)

                ElseIf LCase(sTypeMessage) = "application/edifact" Then 'EDI is EDIFACT

                    'Export the EDI part of the message into a file
                    oMailBody.Export(sSaveFilePath + ".edi")

                    'UNA segment allowed
                    oEdiDoc.Option(DocumentOptionIDConstants.OptDocument_ServiceSegment) = 1

                    'Load all pertaining EDIFACT SEF files here. 
                    oEdiDoc.LoadSchema(sPath + "SEF/sample_ORDERS_S93A.SEF", SchemaTypeIDConstants.Schema_Standard_Exchange_Format)

                ElseIf LCase(sTypeMessage) = "application/xml" Then   'XML

                    'Export the EDI part of the message into a file
                    oMailBody.Export(sSaveFilePath + ".xml.txt")

                Else    'unknown

                    'Export the body part of the message into a file
                    oMailBody.Export(sSaveFilePath + ".stream.bin")

                End If

                If Not sReceiptDeliveryOption.Equals("") Then 'Asynchronous requested. 

                    'Disconnect the client connection because it is not needed in an asyncronous MDN request
                    'while server continues to process the received AS2 message, and then send back an MDN
                    'with a new connection.

                    Response.Flush()
                    Response.Close()

                    ' Enable the EDI process and everything else (auto) in the next Process method.
                    ' These options are not necessary if you don't want to include the EDI validation results
                    ' in the MDN
                    oMailDoc.Option(MailDocOptionIDConstants.MailDocOpt_EnableEdi) = 1
                    oMailDoc.Option(MailDocOptionIDConstants.MailDocOpt_Auto) = 1

                    If oMailDoc.Process() <> 1 Then

                        ' failed to process
                    Else

                        
                        Dim oSmtpCfg As ediSmtpCfg

                        Dim sMdnTempFile As String
                        Dim sHttpResponse As String

                        Dim oTransport As ediTransport
                        Dim oTransports As ediTransports
                        oTransports = oMailDoc.GetMdnTransports()
                        oTransport = oTransports.CreateTransport()

                        'Get a unique temp file
                        Dim oFileSystem As ediFileSystem
                        oFileSystem = oEdiDoc.GetFileSystem()
                        sMdnTempFile = oFileSystem.CreateTempFile("")

                        'Because the cursor type was set to forward only, we have to iterate thru each segment of
                        'the EDI file so that they can be validated.  This is not necessary if you do 
                        'not wish to include the validation results in the MDN
                        Dim oSegment As ediDataSegment
                        oSegment = oEdiDoc.FirstDataSegment()
                        Do While Not oSegment Is Nothing
                            ediDataSegment.Set(oSegment, oEdiDoc.NextDataSegment)
                        Loop

                        If oMailDoc.RefreshMDN() <> 1 Then
                            ' "MDN failed to refresh"
                        Else

                            'Save MDN to file. This is not necessary because the transport object
                            'sends the mdn from the content of the object (and not from the file)
                            If oMDN.Save(sSaveFilePath + ".mdn1.async.bin") <> 1 Then 'sMdnTempFile
                                'failed to save MDN file
                            Else
                            End If

                            Dim sTimeStamp As String = Format(Now(), "yyMMddhhmm")
                            Dim sAsyncSchema As String = Trim(UCase(oReceiptURI.SchemeName))
                            Dim sAsyncHost As String = oReceiptURI.HostName
                            Dim sAsyncUserInfo As String = oReceiptURI.UserInfo
                            Dim sAsyncUrlPath As String = oReceiptURI.UrlPath
                            Dim sAsyncPort As String = oReceiptURI.Port
                            Dim sAsyncValue As String = oReceiptURI.Value   'oMessage.HeaderFieldValue("Receipt-Delivery-Option")

                            'Send the MDN back to the sender using the scheme and address
                            'specified in the header 'Receipt-Delivery-Option'

                            If sAsyncSchema = "HTTP" Then
                                oTransport.SetHTTP()
                                oTransport.InternetUrl = Trim(sAsyncValue) + "/"
                                Dim oHttpCfg As ediHttpCfg = oTransport.GetHttpCfg
                                oHttpCfg.SendVerb = "POST"
                                oHttpCfg.EnableProcessResponse = False
                                Try
                                    oTransport.SendFile(sSaveFilePath + ".mdn1.async.bin")
                                    sHttpResponse = oTransport.LastResponseInfo
                                    'If oTransport.Send(sTimeStamp & ".mdn1.async.bin") <> 1 Then
                                    'Else
                                    'End If
                                Finally
                                End Try
                                oHttpCfg.Dispose()

                            ElseIf sAsyncSchema = "HTTPS" Then
                                oTransport.SetHTTPS()
                                oTransport.InternetUrl = Trim(sAsyncValue) + "/"
                                Dim oHttpCfg As ediHttpCfg = oTransport.GetHttpCfg
                                oHttpCfg.SendVerb = "POST"
                                oHttpCfg.EnableProcessResponse = False
                                Try
                                    oTransport.SendFile(sSaveFilePath + ".mdn1.async.bin")
                                    sHttpResponse = oTransport.LastResponseInfo
                                    'If oTransport.Send(sTimeStamp & ".mdn1.async.bin") <> 1 Then
                                    'Else
                                    'End If
                                Finally
                                End Try
                                oHttpCfg.Dispose()

                            ElseIf sAsyncSchema = "FTP" Then
                                oTransport.SetFTP()
                                oTransport.Address = sAsyncHost
                                oTransport.TargetPath = sAsyncUrlPath
                                oTransport.ServerPort = sAsyncPort
                                If oTransport.Send(sTimeStamp & ".mdn1.async.bin") <> 1 Then
                                Else
                                End If

                            ElseIf sAsyncSchema = "MAILTO" Then
                                oTransport.SetSMTP()
                                ediSmtpCfg.Set(oSmtpCfg, oTransport.GetSmtpCfg)
                                oSmtpCfg.ServerName = "smtp.comp.domain.com"
                                oSmtpCfg.User = "userid"
                                oSmtpCfg.Password = "password"
                                oSmtpCfg.AddTo(sAsyncUserInfo)
                                oSmtpCfg.From = "support@domain.com"
                                oSmtpCfg.FromDisplay = "FrameworkEDI Interoperability test"
                                oSmtpCfg.Subject = "Interoperability Test Document"
                                oSmtpCfg.MessageText = "Please find attached text document"

                                If oTransport.Send(sTimeStamp & ".mdn1.async.bin") <> 1 Then
                                Else
                                End If

                            End If 'sAsyncSchema

                        End If

                        oFileSystem.Dispose()
                        oTransport.Dispose()
                        oTransports.Dispose()

                    End If 'If oMailDoc.Process
                    
                Else 'send MDN synchronously

                    ' Enable the EDI process and everything else (auto) in the next Process method.
                    ' These options are not necessary if you don't want to include the EDI validation results
                    ' in the MDN
                    oMailDoc.Option(MailDocOptionIDConstants.MailDocOpt_EnableEdi) = 1
                    oMailDoc.Option(MailDocOptionIDConstants.MailDocOpt_Auto) = 1

                    If oMailDoc.Process() <> 1 Then
                        'Failed to process
                    Else
                        ' Save MDN to file. This is not necessary because the transport object sends the mdn from the content of 
                        ' the object (and not from the file)
                        oMDN.Save(sSaveFilePath + ".mdn1.bin")

                        'Because the cursor type was set to forward only, we have to iterate thru each segment of
                        'the EDI file so that they can be validated.  This is not necessary if you do 
                        'not wish to include the validation results in the MDN
                        Dim oSegment As ediDataSegment
                        oSegment = oEdiDoc.FirstDataSegment()
                        Do While Not oSegment Is Nothing
                            oSegment = oEdiDoc.NextDataSegment()
                        Loop

                        If oMailDoc.RefreshMDN() <> 1 Then
                            ' "MDN failed to refresh"
                        Else

                            oMDN.Save(sSaveFilePath + ".mdn2.bin")

                            'You can still add and edit the header of an MDN at this point, but not the message.
                            'oMDN.HeaderFieldValue("AS2-Version") = "1.0"
                            'oMDN.HeaderFieldValue("Message-ID") = "12345demo@companyX.com"

                            Dim oHeaders As mailHeaders = oMDN.GetHeaders()
                            Dim oHeader As mailHeader = Nothing
                            'add the headers of the MDN file into the http headers
                            For i = 1 To oHeaders.Count
                                mailHeader.Set(oHeader, oHeaders.GetHeaderByIndex(i))
                                Response.AddHeader(oHeader.Name, oHeader.Value)
                            Next

                            'send the MDN body witout the headers since they will be included into the http headers
                            'so we get the messages only
                            Dim oMdnMsgs As mailMessages = oMDN.GetMessages

                            'save the message to a file so that we can read it back as binary
                            oMdnMsgs.Export(sSaveFilePath + ".msgs.mdn")

                            Dim oMdnReader As BinaryReader = Nothing
                            Dim oMdnFs As FileStream
                            Dim oMdnBytes() As Byte = Nothing

                            oMdnFs = New FileStream(sSaveFilePath + ".msgs.mdn", FileMode.Open)
                            oMdnReader = New BinaryReader(oMdnFs)

                            'read the generated .msgs.mdn file and write it back to the response stream
                            Dim bufferSize As Integer = 512
                            Dim done As Boolean = False
                            Dim bits(bufferSize) As Byte
                            While Not done
                                bits = oMdnReader.ReadBytes(bufferSize)
                                If bits.Length = 0 Then
                                    done = True
                                Else
                                    Response.BinaryWrite(bits)
                                End If
                            End While

                            oMdnReader.Close()
                            oMdnFs.Close()
                            oMdnReader.Dispose()
                            oMdnFs.Dispose()
                            oMdnMsgs.Dispose()
                            oHeaders.Dispose()

                        End If 'oMailDoc.RefreshMDN() <> 1

                    End If 'oMailDoc.Process()

                End If 'url MDN synchronously

                oMailBody.Dispose()
                oReceiptURI.Dispose()
                oMessage.Dispose()

            End If 'oMailDoc.Load(AS2FileName) <> 1

            oMdnSecurity.Dispose()
            oMDN.Dispose()
            oMailDoc.Dispose()
            oSchemas.Dispose()
            oSecurities.Dispose()
            oEdiDoc.Dispose()

        End If 'if IsPostBack

        Return ""

    End Function

End Class

    Click here to download a trial version of the Framework EDI