SMPP connection issue in VB.Net WinForms application

Post Reply
anilsurendar
Posts: 1
Joined: Tue Aug 10, 2021 1:54 pm

SMPP connection issue in VB.Net WinForms application

Post by anilsurendar » Wed Aug 11, 2021 6:16 am

Hello Team,

We are licensed with InetLab.SMPP. Trying to send sms via VB.Net winforms application.

Applying license is working fine. But, couldn't able to establish the connection.

Application is going to non-responsive mode.

Can you please help on this.

Source Code

Code: Select all

[u][b]FormsApplication[/b][/u]
[b]FileName: Form1.vb[/b]

Imports Inetlab.SMPP.Brithol.SMSLibrary

Public Class Form1
    Private bmSmsClient As IBMInetSmsClientManager

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim destinationAddress = ReceiverNumber.Text.Trim

        If String.IsNullOrWhiteSpace(destinationAddress) Then
            MessageBox.Show("Receiver number is missing")
            Return
        End If

        Try
            CheckSms(destinationAddress)
        Catch ex As Exception
            LogManager.Log($"Error occured in Form1: Button1_Click() => {ex.ToString()}", ex)
            MessageBox.Show(ex.ToString())
        End Try

    End Sub

    Private Sub CheckSms(destinationAddress As String)
        Dim setting = SetSmsSetting("{SERVER_ADDRESS}", "{PORT}", "{USER_NAME}", "{PASSWORD}")
        Dim bmMessage = SetBMMessage("{SOURCE}", destinationAddress, "MessageContent-Test message from VBFormsApp.")

        bmSmsClient = New BMInetSmsClientManager(setting)
        bmSmsClient.Send(bmMessage)
    End Sub

    Private Function SetSmsSetting(host As String, port As String, userName As String, password As String) As BMSmsClientSetting
        Return New BMSmsClientSetting With {
            .HostName = host,
            .Port = port,
            .UserName = userName,
            .Password = password
            }
    End Function

    Private Function SetBMMessage(source As String, destination As String, message As String) As BMSmsMessage
        Return New BMSmsMessage With {
           .Source = source,
           .Destination = destination,
           .MessageContent = message
           }
    End Function
End Class

[b]Library project:[/b]

Public Class BMSmsClientSetting
    Public Property HostName As String
    Public Property Port As String
    Public Property UserName As String
    Public Property Password As String
End Class

Public Class BMSmsMessage
    Public Property Source As String
    Public Property Destination As String
    Public Property MessageContent As String
End Class

[b]FileName: IBMInetSmsClientManager.vb[/b]

Public Interface IBMInetSmsClientManager
    Function Send(bmMessage As BMSmsMessage) As Boolean
End Interface

[b]FileName: BMInetSmsClientManager.vb[/b]
Imports Inetlab.SMPP.Common

Public Class BMInetSmsClientManager
    Implements IBMInetSmsClientManager

    Private _client As SmppClient
    Private _bindResponse As PDU.BindResp

    Public Sub New(clientSetting As BMSmsClientSetting)
        If clientSetting Is Nothing Then
            Throw New ArgumentNullException("SMPPClientSetting is not available")
        End If

        'If ApplyLicense() = False Then
        '    Throw New Exception("Invalid License, please contact administrator")
        'End If

        If EstablishClientConenction(clientSetting) Then
            Throw New Exception("Unable to establish client connection, please contact administrator")
        End If

    End Sub

    Public Function Send(bmMessage As BMSmsMessage) As Boolean Implements IBMInetSmsClientManager.Send
        Dim result As Boolean = False

        Try
            LogManager.Log("BMInetSmsClientManager: Send()=> method called.")

            If (_client.Status = ConnectionStatus.Open) = False Then
                LogManager.Log("BMInetSmsClientManager: Client conenction not establised.")
                Return False
            End If

            If (_client.Status = ConnectionStatus.Bound) = False Then
                LogManager.Log("BMInetSmsClientManager: Client conenction bound is not happend.")
                Return False
            End If

            If _bindResponse.Header.Status = CommandStatus.ESME_ROK Then
                Dim singleMessage = SMS.ForSubmit().
                    From(bmMessage.Source).
                    To(bmMessage.Destination).
                    Coding(DataCodings.UCS2).
                    Text(bmMessage.MessageContent)

                LogManager.Log("BMInetSmsClientManager: SMS constructed.")
                Dim submitResp = _client.SubmitAsync(singleMessage).GetAwaiter().GetResult()

                LogManager.Log("BMInetSmsClientManager: Message submitted.")

                If submitResp.All(Function(x) x.Header.Status = CommandStatus.ESME_ROK) Then
                    Dim msgIds = submitResp.Select(Function(x) x.MessageId).ToList()
                    LogManager.Log($"Message has been sent. with messageIds :{String.Join(",", msgIds)}")
                Else
                    LogManager.Log($"BMInetSmsClientManager: Message submitted. but not sent {submitResp}")
                End If
            Else
                LogManager.Log($"BMInetSmsClientManager: bind response is in {_bindResponse.Header.Status} status. Can't sent message.")
            End If

        Catch ex As Exception
            LogManager.Log("BMInetSmsClientManager: Send()=> Error occured.", ex)
            Throw
        Finally

        End Try

        Return result
    End Function

    Protected Overrides Sub Finalize()

        If _client Is Nothing Then
            Return
        End If

        LogManager.Log("BMInetSmsClientManager: Disconnecting from SMPP server")


        If _client.Status = ConnectionStatus.Bound Then
            LogManager.Log("BMInetSmsClientManager: Unbind SmppClient")

            Dim response = _client.UnbindAsync().GetAwaiter().GetResult()

            Select Case response.Header.Status
                Case CommandStatus.ESME_ROK
                    LogManager.Log($"BMInetSmsClientManager: UnBind success: Status: {response.Header.Status}")
                Case Else
                    LogManager.Log($"BMInetSmsClientManager: UnBind failed: Status: {response.Header.Status}")
                    _client.DisconnectAsync().GetAwaiter().GetResult()
            End Select
        End If

        If _client.Status = ConnectionStatus.Open Then
            _client.DisconnectAsync().GetAwaiter().GetResult()
        End If

        LogManager.Log("BMInetSmsClientManager: Connection is disconnected")
    End Sub

    ''' <summary>
    ''' Establish connection to client.
    ''' </summary>
    ''' <param name="setting">setting.</param>
    ''' <returns>bool.</returns>
    Private Function EstablishClientConenction(setting As BMSmsClientSetting) As Boolean
        Dim result As Boolean
        Try
            _client = New SmppClient

            _client.ConnectAsync(setting.HostName, setting.Port).GetAwaiter().GetResult()
            LogManager.Log("BMInetSmsClientManager: EstablishConenction()=> Connection establised")

            _bindResponse = _client.BindAsync(setting.UserName, setting.Password).GetAwaiter().GetResult()
            LogManager.Log("BMInetSmsClientManager: EstablishConenction()=> Binding complated")
            result = True
        Catch ex As Exception
            LogManager.Log("BMInetSmsClientManager: EstablishConenction()=> Error occured.", ex)
            Throw
        End Try

        Return result
    End Function

    ''' <summary>
    ''' Apply license in the constructor.
    ''' </summary>
    ''' <returns>bool.</returns>
    Private Function ApplyLicense() As Boolean
        Dim licenseResult As Boolean

        Try
            Dim licenseContent = Me.GetType().Assembly.GetManifestResourceStream(Me.GetType(), "Inetlab.SMPP.license")
            licenseResult = Inetlab.SMPP.LicenseManager.SetLicense(licenseContent)
        Catch ex As Exception
            LogManager.Log("BMInetSmsClientManager: ApplyLicense()=> Error occured.", ex)
            Throw
        End Try

        LogManager.Log($"BMInetSmsClientManager: ApplyLicense()=> called and licenseResult: {licenseResult}")

        Return licenseResult
    End Function

End Class

Thanks,
Anil
alt
Site Admin
Posts: 985
Joined: Tue Apr 25, 2006 9:45 am

Re: SMPP connection issue in VB.Net WinForms application

Post by alt » Thu Aug 12, 2021 7:59 pm

Hello Anil,

This is common problem MethodAsync().GetAwaiter().GetResult() lead to dead lock in windows form application .

I hope this article helps you to solve the issue.

Understanding Async, Avoiding Deadlocks in C#

Short answer: rewrite your classes to async await methods that return Task. See how it is implemented in SmppClientDemo
Post Reply