Avatar of T Hoecherl
T HoecherlFlag for United States of America

asked on 

System.net.Sockets Error

I have this code that is used to print labels:

    Private Sub Glass_Click(sender As System.Object, e As System.EventArgs) Handles Glass.Click
        Dim strBatch As String = lstBatch.Text
        If strBatch = "" Then
            MsgBox("Please select a batch and try again")
            Exit Sub
        End If
        'Dim cn As SqlClient.SqlConnection = New SqlClient.SqlConnection("Data Source = THOECHERL-PC;Initial Catalog = TWO; " & _
        '                                                         "Persist Security Info= True;Connection Timeout = 0;User ID=sa;Password=Great Plains!")
        Dim cn As SqlClient.SqlConnection = New SqlClient.SqlConnection("Data Source = THOR;Initial Catalog = TEST2; " & _
                                                         "Persist Security Info= True;Connection Timeout = 0;User ID=sa;Password=Great Plains!")

        'Dim Port As Devices.Ports
        Dim Port As String
        Dim Host, Button As String
        Dim Header As String
        Dim LabelFormat As String
        Dim Bin, Assorted_bin, Item_number, Custname, Order_Number, Batch_Number, Color, Order, Customer, Batch As String
        Dim Glass_Assorted_bin, Glass_Type_1, Glass_Type_2, Mull_Config, Mull_Location, Special_Instructions, WinPart, GlassSize, Glass_Field, MullInfo, Spec_Inst, AssBin, PartNum, BarcodeOrder, AssortBin As String
        Dim Line_Number, SeriesQty As Integer
        Dim Spacer_Thickness, Qty, FixedWidth, FixedHeight, VentWidth, VentHeight, ScreenHeight, ScreenWidth As String
        Dim Quantity As Double

        Button = Glass.Name.ToString

        Dim cmd As SqlClient.SqlCommand = New SqlClient.SqlCommand
        cmd.Connection = cn
        cmd.CommandType = CommandType.Text
        cn.Open()
        cmd.CommandText = "SELECT PORT FROM PCT_LABEL_CONFIG WHERE NAME = '" & Button & "'"
        Port = cmd.ExecuteScalar()

        cmd.CommandText = "SELECT HOST FROM PCT_LABEL_CONFIG WHERE NAME = '" & Button & "'"
        Host = cmd.ExecuteScalar()

        cmd.CommandText = "SELECT HEADINGFORMAT FROM PCT_LABEL_CONFIG WHERE NAME = '" & Button & "'"
        Header = cmd.ExecuteScalar()

        cmd.CommandText = "SELECT LabelFormat FROM PCT_LABEL_CONFIG WHERE NAME = '" & Button & "'"
        LabelFormat = cmd.ExecuteScalar()

        cn.Close()

        Dim IPs As IPHostEntry = Dns.GetHostEntry(Host)  ' Grab this host's IPs
        Dim IP As IPAddress = IPs.AddressList(0)    ' Let's use the first IP listed for this host.
        Dim EP As New IPEndPoint(IP, Port)          ' Establish an endpoint.

        PrintSocket.Connect(EP)   ' Connect the socket.
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX><ESC>C<ETX>" & vbCrLf)) ' Clean slate for commands.
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX><ESC>P<ETX>" & vbCrLf)) ' Enter programming mode.
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>E5;F5;<ETX>" & vbCrLf)) ' Erase format 5, Start programming format 5
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & Header & "<ETX>" & vbCrLf)) ' Send the two field definitions from our table.
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>R<ETX>" & vbCrLf)) ' End of programming mode

        ' The next four lines are the heading label's data
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX><ESC>E5<CAN><ETX>" & vbCrLf)) ' Announce label data should use format 5
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & Button & "<CR><ETX>" & vbCrLf)) ' The first field is the name of the report
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & strBatch & "<CR><ETX>" & vbCrLf)) ' The second and final field is the batch numnber.
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX><ETB><ETX>" & vbCrLf)) ' End of this label.

        ' These lines are the format info for the label body
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX><ESC>C<ETX>" & vbCrLf)) ' Clean slate for commands.
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX><ESC>P<ETX>" & vbCrLf)) ' Enter programming mode.
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>E5;F5;<ETX>" & vbCrLf)) ' Erase format 5, Start programming format 5
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & LabelFormat & "<ETX>" & vbCrLf)) ' Send the field definitions from our table.
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>R<ETX>" & vbCrLf)) ' End of programming mode
        PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX><ESC>E5<CAN><ETX>" & vbCrLf)) ' Announce label data should use format 5

        Dim selectSQL1a As String = "SELECT PCT_Glass_Labels.Bin, PCT_Glass_Labels.Assorted_Bin, PCT_Glass_Labels.Glass_Assorted_Bin, PCT_Glass_Labels.xwpSpacerThickness, PCT_Glass_Labels.Item_Number, " & _
            "PCT_Glass_Labels.xwpGlassType1, PCT_Glass_Labels.xwpGlassType2, PCT_Glass_Labels.xwpWidth, PCT_Glass_Labels.xwpHeight, PCT_Glass_Labels.Order_Number, " & _
            "PCT_Glass_Labels.CUSTNAME, PCT_Glass_Labels.Line_Number, PCT_Glass_Labels.Batch_Number, PCT_Glass_Labels.xwpMullConfig, PCT_Glass_Labels.xwpMullLocation, " & _
            "PCT_Glass_Labels.xwpSpecialInstructionsGlassTag, PCT_Glass_Labels.WinPart, PCT_Glass_Labels.xwpFixedUnitWidth, " & _
            "PCT_Glass_Labels.xwpFixedUnitHeight, PCT_Glass_Labels.xwpVentUnitWidth, PCT_Glass_Labels.xwpVentUnitHeight, PCT_Glass_Labels.Quantity, PCT_Ord_Numbers.N AS SeriesQty " & _
            "FROM PCT_Glass_Labels INNER JOIN " & _
            "PCT_Ord_Numbers ON PCT_Ord_Numbers.N <= PCT_Glass_Labels.Quantity " & _
            "WHERE (PCT_Glass_Labels.Batch_Number = '" & strBatch & "')"

        Dim com1a As New SqlCommand(selectSQL1a, cn)
        com1a.CommandType = CommandType.Text
        cn.Open()

        Dim myreader1a As SqlDataReader = com1a.ExecuteReader

        While myreader1a.Read

            Bin = myreader1a.GetString(0)
            Assorted_bin = myreader1a.GetString(1)
            Glass_Assorted_bin = myreader1a.GetString(2)
            Spacer_Thickness = myreader1a.GetString(3)
            Item_number = myreader1a.GetString(4)
            Glass_Type_1 = myreader1a.GetString(5)
            Glass_Type_2 = myreader1a.GetString(6)
            ScreenWidth = myreader1a.GetString(7)
            ScreenHeight = myreader1a.GetString(8)
            Order_Number = myreader1a.GetString(9)
            Custname = myreader1a.GetString(10)
            Line_Number = myreader1a.GetInt32(11)
            Batch_Number = myreader1a.GetString(12)
            Mull_Config = myreader1a.GetString(13)
            Mull_Location = myreader1a.GetString(14)
            Special_Instructions = myreader1a.GetString(15)
            WinPart = myreader1a.GetString(16)
            FixedWidth = myreader1a.GetString(17)
            FixedHeight = myreader1a.GetString(18)
            VentWidth = myreader1a.GetString(19)
            VentHeight = myreader1a.GetString(20)
            Quantity = myreader1a.GetDouble(21)
            SeriesQty = myreader1a.GetInt32(22)

            'Construct variables for label
            Order = "Order #:" + RTrim(Order_Number) + "-" + RTrim(Line_Number)
            Customer = RTrim(Custname)
            Batch = RTrim(Batch_Number)
            GlassSize = IIf(RTrim(WinPart) = "FIXED", RTrim(CStr(FixedWidth)) + " X " + RTrim(CStr(FixedHeight)) + "  FIXED",
                RTrim(CStr(VentWidth)) + " X " + RTrim(CStr(VentHeight)) + "  VENT")
            Glass_Field = RTrim(Glass_Type_1) + "  " + RTrim(Glass_Type_2) + "  " + RTrim(CStr(Spacer_Thickness))
            MullInfo = IIf(RTrim(Mull_Config) = "" Or RTrim(Mull_Config) = "NONE", "", RTrim(Mull_Config) + "  " + RTrim(Mull_Location) + "  ")
            Spec_Inst = RTrim(Special_Instructions)
            AssBin = RTrim(Assorted_bin)
            Bin = "Bin " + RTrim(Bin)
            Qty = " " + RTrim(CStr(SeriesQty)) + " of " + RTrim(CStr(Quantity))
            PartNum = RTrim(Item_number) + "  " + RTrim(CStr(ScreenWidth)) + "x" + RTrim(CStr(ScreenHeight))
            BarcodeOrder = "*" + RTrim(Order_Number) + "-" + Microsoft.VisualBasic.Right(("000" + RTrim(CStr(Line_Number))), 3) + "*"
            AssortBin = RTrim(Assorted_bin)

            ' Send this label.
            PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & Order & "<CR><ETX>" & vbCrLf))
            PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & Customer & "<CR><ETX>" & vbCrLf))
            PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & Batch & "<CR><ETX>" & vbCrLf))
            PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & GlassSize & "<CR><ETX>" & vbCrLf))
            PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & Glass_Field & "<CR><ETX>" & vbCrLf))
            PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & MullInfo & Spec_Inst & "               " & AssBin & "<CR><ETX>" & vbCrLf))
            PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & "                                      " & Bin & "<CR><ETX>" & vbCrLf))
            PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX><CR><ETX>" & vbCrLf))
            PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & "                                      " & Qty & "<CR><ETX>" & vbCrLf))
            PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & PartNum & "                            " & BarcodeOrder & "<CR><ETX>" & vbCrLf))
            PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX>" & AssortBin & "<CR><ETX>" & vbCrLf))
            PrintSocket.Send(System.Text.Encoding.ASCII.GetBytes("<STX><ETB><ETX>" & vbCrLf)) ' End this label

        End While

        PrintSocket.Shutdown(SocketShutdown.Both)  ' Release the socket.
        PrintSocket.Close()                        ' Close the connection.

        MsgBox("Label sent to printer " & Host)

    End Sub

It works, but it I try to click the button to send the label a second time I get the error on the attached Word doc.  The error says:

"Cannot access a disposed object.
Object name:  "System.Net.Sockets.Socket"

Does anyone know how to resolve this error?

TSocketsError.docx
Visual Basic.NET

Avatar of undefined
Last Comment
T Hoecherl
Avatar of Dong Luu Thoai Ngoc
Dong Luu Thoai Ngoc

Hi,
It's because you closed the PrintSocket at the end of your code. Do not close it or you have to re-open it before call Connect() function.

Cheer.
Avatar of T Hoecherl
T Hoecherl
Flag of United States of America image

ASKER

When I don't close the PrintSocket at the end of the code I get the error message on the attachment when I try to reopen the socket at the beginning of the code (PrintSocket.Connect(EP)).  I have two other labels that I am printing that have the same code as far as connecting and disconnecting the socket, but neither of them give me the error.

There must be something else in this code that is causing the problem.

TSocketClosingError.docx
ASKER CERTIFIED SOLUTION
Avatar of Dong Luu Thoai Ngoc
Dong Luu Thoai Ngoc

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of T Hoecherl
T Hoecherl
Flag of United States of America image

ASKER

I was able to resolve the issue.  By comparing this code with the code of an identical process that was working, I realized that I was missing this line:

        ' Create the TCP socket.
        Dim PrintSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

Once I added that back in the problem disappeared.
Avatar of T Hoecherl
T Hoecherl
Flag of United States of America image

ASKER

Thanks for your help.
Visual Basic.NET
Visual Basic.NET

Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to Visual Basic pre-2002, it is not the same technology,

96K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo