AccessViolationException when calling ExecuteReader of AseDataReader - ado.net

I get this error
System.AccessViolationException was unhandled
HResult=-2147467261
Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=Sybase.AdoNet4.AseClient
StackTrace:
at Sybase.Data.AseClient.Unmanaged.ModifyCommandTextForSchemaOnly(String commandText, StringBuilder modifiedCommandText, Int32 capacity)
at Sybase.Data.AseClient1.AseCommand.ModifyCommandTextForSchemaOnly(String commandText)
at Sybase.Data.AseClient1.AseCommand.GetCommandText(CommandBehavior commandBehavior)
at Sybase.Data.AseClient1.AseCommand.SetCommandStatement(CommandBehavior commandBehavior)
at Sybase.Data.AseClient1.AseCommand.Execute(CommandBehavior commandBehavior)
at Sybase.Data.AseClient1.AseCommand._ExecuteReader(CommandBehavior commandBehavior)
at Sybase.Data.AseClient1.AseCommand.ExecuteReader(CommandBehavior commandBehavior)
at Sybase.Data.AseClient.AseCommand.ExecuteReader(CommandBehavior commandBehavior)
when calling
Dim cm As AseCommand = New AseCommand("SELECT * FROM Results;", cn)
Dim rd As AseDataReader = cm.ExecuteReader(CommandBehavior.SchemaOnly)
Where cn is an AseConnection.
I am using version 4.157.1000.0 of Sybase.AdoNet4.AseClient.dll

The issue is the semicolon in the SQL text, remove it and all is well.
Dim cm As AseCommand = New AseCommand("SELECT * FROM Results", cn)

Related

PostgreSQL ODBC Connection VB .NET Data source name not found and no default driver specified

I receive the following error attempting to employ an ODBC connection to connect to a PostgreSQL DB
Error: {"ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"}
IDE: Visual Studio 2019
Language: Visual Basic .Net
PostgreSQL DB VersionL 10.0
[PostgreSQL ODBC Connection][1]
I have created a SUCCESSFUL 64bit connection to my PostgresSQL with the 64bit ODBC adapter.
My code to test the connection:
Imports System.Data.Odbc
Module Module1
Sub Main()
Dim connectionString As String = ""
connectionString = "Driver={PostgreSQL}; Server=localhost; Port=5432; Database=dvdrental2; Uid=postgres; Pwd=xxxxxx"
Dim cnn As OdbcConnection
cnn = New OdbcConnection(connectionString)
Try
cnn.Open()
MsgBox("Connection Open!")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection!")
End Try
End Sub
End Module
I understand an ODBC connection is not the best means to connect to a PostgreSQL DB; however, I was curious about implementing this type of connection.
Module Module1
Sub Main()
Dim connectionString As String = ""
connectionString = "DSN=PostgreSQL; Server=localhost; Port=5432; Database=dvdrental; Uid=postgres; Pwd=your_pwd"
Dim cnn As OdbcConnection
cnn = New OdbcConnection(connectionString)
Try
cnn.Open()
Dim sql As String = "Select * From city"
Dim ds As DataSet = GetTableData(connectionString, SQL)
MsgBox("Connection Open!")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection!")
End Try
End Sub
Public Function GetTableData(ByVal i_cs As String, ByVal sql As String) As DataSet
' Create and Initialize as Dataset
Dim ds As DataSet = New DataSet()
' Create a OdbcConnection
Using conn As OdbcConnection = New OdbcConnection(i_cs)
Try
' Open the OdbcConnection
conn.Open()
' Create a read object of type OdbcDataAdapter
Dim read As OdbcDataAdapter = New OdbcDataAdapter(sql, conn)
' Fill the DataSet using OdbcDataAdapter
read.Fill(ds)
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
' Close the Connection
conn.Close()
End Try
End Using
Return ds
End Function
End Module

Exception, but only on 3rd time - The IAsyncResult object was not returned from the corresponding asynchronous method on this class

I have a legacy (2008) Windows service application (using System.ServiceProcess.ServiceBase) that I need to utilize in a slightly different way to how it's working now. At the moment it starts up and creates a TCPLISTENER on a specific port, for a client app to connect to (which it does once) in order to send/receive requests to the listening port. This all works fine. However, the adaptation requires use of a web app to connect to the listener port, then send/rcv as normal but after the receive it must DISCONNECT(*)
(* - if the web app didn't have to disconnect from the listening socket after each test that'd be better, but how I might achieve this is beyond me. Can I keep a TCP connection in session state for re-use?)
Anyway, the adaptation all works fine for the first TWO connect/send/rcv/disconnect tests but on the THIRD the service throws an ArgumentException in the EndAccept of the Socket class.
I don't understand why it is failing on the 3rd test.
Here is the simple test client.
Public Class ConnectDisconnectTCP
Inherits System.Web.UI.Page
Private IP As String = "127.0.0.1"
Private port As Int32 = 10002
Private mTCP As System.Net.Sockets.TcpClient
Private netStrm As NetworkStream
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oEnc As New ASCIIEncoding
Dim ScanText As String = "100000000093001X" + vbLf
Dim mTCP As System.Net.Sockets.TcpClient
'connect and create a tcpclient
mTCP = New System.Net.Sockets.TcpClient(IP, port)
netStrm = mTCP.GetStream()
netStrm.WriteAsync(oEnc.GetBytes(ScanText.ToString), 0, ScanText.ToString.Length)
If netStrm.CanRead Then
Dim myReadBuffer(1024) As Byte
Dim myCompleteMessage As StringBuilder = New StringBuilder()
Dim numberOfBytesRead As Integer = 0
' Incoming message may be larger than the buffer size.
Do
numberOfBytesRead = netStrm.Read(myReadBuffer, 0, myReadBuffer.Length)
myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead))
Loop While netStrm.DataAvailable
End If
'CLOSE
netStrm.Close()
mTCP.Close() 'Disposes this TcpClient instance and requests that the underlying TCP connection be closed.
mTCP = Nothing
Label1.Text = "Closed"
End Sub End Class
And here is the TCPListener class on the service that does all the work
Imports System
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Public Class TCPListenerPort
Private currentAsynchResult As IAsyncResult
Private cState As ClientState
Private servSock As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Private m_connectionstate As Int32 = 0
Dim sData As String = String.Empty
'counters
Public cnt As Int32 = 0
Public rcvcnt As Int32 = 0
Public acccnt As Int32 = 0
Public sndcnt As Int32 = 0
Public sndcal As Int32 = 0
Public cncnt As Int32 = 0
'Public Events
Public Event ConnectionState(ByVal enmState As Int32)
Public Event DataArrived(ByVal strData As Object)
Public Sub New()
End Sub
Public Sub New(ByVal dr As DataRow)
End Sub
Protected Overrides Sub Finalize()
Try
If Not cState Is Nothing Then
cState.ClntSock.Close()
End If
If Not servSock Is Nothing Then
servSock.Close()
End If
Catch ex As Exception
Throw ex
Finally
MyBase.Finalize()
End Try
End Sub
Private Class ClientState
Public Const BUFSIZE As Integer = 1024
Public mrcvBuffer As Byte() = New Byte(BUFSIZE - 1) {}
Public mSendBuffer As Byte() = New Byte(BUFSIZE - 1) {}
Private mclntSock As Socket = Nothing
Public Sub New(ByRef clntSock As Socket)
mclntSock = clntSock
ReDim mrcvBuffer(BUFSIZE)
ReDim mSendBuffer(BUFSIZE)
End Sub
Public ReadOnly Property SckConnected() As Boolean
Get
SckConnected = mclntSock.Connected
End Get
End Property
Public ReadOnly Property RcvBuffer() As Byte()
Get
RcvBuffer = mrcvBuffer
End Get
End Property
Public ReadOnly Property SendBuffer() As Byte()
Get
SendBuffer = mSendBuffer
End Get
End Property
Public ReadOnly Property ClntSock() As Socket
Get
ClntSock = mclntSock
End Get
End Property
End Class
Public Sub Connect(ByVal TCPPort As Int32, ByVal Backlog As Int32)
Try
cState = New ClientState(servSock)
cState.ClntSock.Bind(New IPEndPoint(System.Net.IPAddress.Any, TCPPort))
cState.ClntSock.Listen(100) '5
While True
cncnt = cncnt + 1
System.Diagnostics.Debug.WriteLine("in connect WHILE " + cncnt.ToString)
currentAsynchResult = servSock.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), cState)
currentAsynchResult.AsyncWaitHandle.WaitOne()
End While
Catch __unusedObjectDisposedException1__ As ObjectDisposedException
Catch e As Exception
End Try
End Sub
Private Sub AcceptCallback(ByVal asyncResult As IAsyncResult)
Try
acccnt = acccnt + 1
System.Diagnostics.Debug.WriteLine("AcceptCallback Start" + acccnt.ToString)
'obtain the Socket on which the connection attempt is being made
Dim servSock As ClientState = asyncResult.AsyncState 'Asyncstate gets a user defined object that qualifies or contains info about an async operation
Dim clntSock As Socket
clntSock = servSock.ClntSock.EndAccept(asyncResult)
System.Diagnostics.Debug.WriteLine(clntSock.RemoteEndPoint)
Dim cs As New ClientState(clntSock)
clntSock.BeginReceive(cs.RcvBuffer, 0, cs.RcvBuffer.Length, SocketFlags.None, New AsyncCallback(AddressOf ReceiveCallback), cs)
Catch ar As ArgumentException
'!!!!!Test 3 errors here with
'The IAsyncResult object was not returned from the corresponding asynchronous method on this class.
Catch ex As Exception
End Try
System.Diagnostics.Debug.WriteLine("AcceptCallback End " + acccnt.ToString)
End Sub
Private Sub ReceiveCallback(ByVal asyncResult As IAsyncResult)
rcvcnt = rcvcnt + 1
System.Diagnostics.Debug.WriteLine("ReceiveCallback In " + rcvcnt.ToString)
Dim cs As ClientState = asyncResult.AsyncState
Dim AE As New System.Text.ASCIIEncoding
Dim recvMsgSize As Int32 = 0
Dim strTmp As String = String.Empty
Dim strSend As String = String.Empty
Try
recvMsgSize = cs.ClntSock.EndReceive(asyncResult)
strTmp = Replace(AE.GetString(cs.RcvBuffer), vbNullChar, "")
If recvMsgSize > 0 Then
System.Diagnostics.Debug.WriteLine("ReceiveCallback receiveMsgSize " + recvMsgSize.ToString)
If Right(strTmp, 1) = vbLf Or Right(strTmp, 1) = vbCr Then
strSend = sData + strTmp
strSend = strSend.Replace(vbLf, "")
strSend = strSend.Replace(vbCr, "")
cState = cs
sData = String.Empty
RaiseEvent DataArrived(strSend)
Else
End If
Else
End If
Catch ex As Exception
Throw ex
End Try
System.Diagnostics.Debug.WriteLine("ReceiveCallback Exit " + rcvcnt.ToString)
End Sub
Public Function SendData(ByVal strData As Object) As Boolean
' Change the data to a byte array if necessary, then send it via the socket
Dim oEncoder As New System.Text.ASCIIEncoding
Dim bytes As Byte()
Dim Result As IAsyncResult
Try
Select Case strData.GetType().ToString
Case "System.String" ' Convert a string to a byte array
bytes = oEncoder.GetBytes(strData)
Case "System.Byte[]" ' Send a byte array directly
bytes = strData
Case Else ' And just send anything else as-is
bytes = strData
End Select
sndcnt = sndcnt + 1
Result = cState.ClntSock.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, New AsyncCallback(AddressOf SendCallback), cState)
System.Diagnostics.Debug.WriteLine("SendData " + sndcnt + " " + Result.ToString)
Result.AsyncWaitHandle.WaitOne()
Catch ex As Exception
Throw ex
End Try
Return True
End Function
Private Sub SendCallback(ByVal asyncResult As IAsyncResult)
Dim cs As ClientState = asyncResult.AsyncState
Dim bytesSent As Int32 = 0
Try
bytesSent = cs.ClntSock.EndSend(asyncResult)
sndcal = sndcal + 1
cs.ClntSock.BeginReceive(cs.RcvBuffer, 0, cs.RcvBuffer.Length, SocketFlags.None, New AsyncCallback(AddressOf ReceiveCallback), cs)
System.Diagnostics.Debug.WriteLine("SendCallBack " + sndcal.ToString + " " + bytesSent.ToString)
Catch ex As Exception
Throw (ex)
End Try
End Sub
End Class
With .net trace on, plus the code's system diagnostics debug.write, here is a complete log of the TEST1, TEST2, TEST3/CRASH operation. Note the '<-- SCANTEXT RECEIVED' and '<-- RESPONSE RECEIVED' annotations. The 'in connect WHILE 4' annotation shows the arrival of the 3rd request attempt.
[12572] TcpClient#57416410::TcpClient(AddressFamily#2)
[12572] Socket#61940669::Socket(AddressFamily#2)
[12572] Exiting Socket#61940669::Socket()
[12572] Exiting TcpClient#57416410::TcpClient()
[12572] TcpClient#57416410::TcpClient()
[12572] Exiting TcpClient#57416410::TcpClient()
[12572] Socket#15193904::Socket(AddressFamily#2)
[12572] Exiting Socket#15193904::Socket()
[17872] Socket#40528290::Socket(AddressFamily#2)
[17872] Exiting Socket#40528290::Socket()
[17872] Socket#40528290::Bind(0.0.0.0:10002#10002)
[17872] Exiting Socket#40528290::Bind()
[17872] Socket#40528290::Listen(Int32#100)
[17872] Exiting Socket#40528290::Listen()
in connect WHILE 1
[17872] Socket#40528290::BeginAccept()
[17872] Exiting Socket#40528290::BeginAccept() -> AcceptAsyncResult#515737
The thread '1' (0x6674) has exited with code 0 (0x0).
The thread '<No Name>' (0x1df8) has exited with code 0 (0x0).
The thread '<No Name>' (0x5dac) has exited with code 0 (0x0).
[7984] Socket#49538252::Socket()
[7984] Exiting Socket#49538252::Socket()
in connect WHILE 2
AcceptCallback Start1
[17872] Socket#40528290::BeginAccept()
[7984] Socket#40528290::EndAccept(AcceptAsyncResult#515737)
[17872] Exiting Socket#40528290::BeginAccept() -> AcceptAsyncResult#27334100
System.Net.Sockets Information: 0 : [7984] Socket#49538252 - Accepted connection from 127.0.0.1:63817 to 127.0.0.1:10002.
[7984] Exiting Socket#40528290::EndAccept() -> Socket#49538252
127.0.0.1:63817
[7984] Socket#49538252::BeginReceive()
[7984] Exiting Socket#49538252::BeginReceive() -> OverlappedAsyncResult#62696216
AcceptCallback End 1
[22168] Data from Socket#49538252::PostCompletion
[22168] 00000000 : 32 30 30 30 30 30 30 30-30 30 38 33 30 30 31 58 : 100000000093001X <-- SCANTEXT RECEIVED, TEST1
[22168] 00000010 : 0A : .
ReceiveCallback In 1
[22168] Socket#49538252::EndReceive(OverlappedAsyncResult#62696216)
[22168] Exiting Socket#49538252::EndReceive() -> Int32#17
ReceiveCallback receiveMsgSize 17
[22168] Socket#49538252::BeginSend()
[22168] Exiting Socket#49538252::BeginSend() -> OverlappedAsyncResult#13462887
A first chance exception of type 'System.FormatException' occurred in Microsoft.VisualBasic.dll
[19228] Data from Socket#49538252::PostCompletion
[19228] 00000000 : 07 : . <-- RESPONSE RECEIVED, TEST1
[19228] Socket#49538252::EndSend(OverlappedAsyncResult#13462887)
[19228] Exiting Socket#49538252::EndSend() -> Int32#1
[19228] Socket#49538252::BeginReceive()
[19228] Exiting Socket#49538252::BeginReceive() -> OverlappedAsyncResult#25961440
SendCallBack 1 1
[7984] Data from Socket#49538252::PostCompletion
[7984] 00000000 : :
ReceiveCallback In 2
[7984] Socket#49538252::EndReceive(OverlappedAsyncResult#25961440)
[7984] Exiting Socket#49538252::EndReceive() -> Int32#0
ReceiveCallback Exit 2
ReceiveCallback Exit 2
[22168] Socket#31352595::Socket()
[22168] Exiting Socket#31352595::Socket()
AcceptCallback Start2
in connect WHILE 3
[17872] Socket#40528290::BeginAccept()
[22168] Socket#40528290::EndAccept(AcceptAsyncResult#27334100)
[17872] Exiting Socket#40528290::BeginAccept() -> AcceptAsyncResult#39421196
System.Net.Sockets Information: 0 : [22168] Socket#31352595 - Accepted connection from 127.0.0.1:63820 to 127.0.0.1:10002.
[22168] Exiting Socket#40528290::EndAccept() -> Socket#31352595
127.0.0.1:63820
[22168] Socket#31352595::BeginReceive()
[22168] Exiting Socket#31352595::BeginReceive() -> OverlappedAsyncResult#28002689
AcceptCallback End 2
[7984] Data from Socket#31352595::PostCompletion
[7984] 00000000 : 32 30 30 30 30 30 30 30-30 30 38 33 30 30 31 58 : 100000000093001X <-- SCANTEXT RECEIVED, TEST2
[7984] 00000010 : 0A : .
ReceiveCallback In 3
[7984] Socket#31352595::EndReceive(OverlappedAsyncResult#28002689)
[7984] Exiting Socket#31352595::EndReceive() -> Int32#17
ReceiveCallback receiveMsgSize 17
[7984] Socket#31352595::BeginSend()
[7984] Exiting Socket#31352595::BeginSend() -> OverlappedAsyncResult#31071611
[22168] Data from Socket#31352595::PostCompletion
A first chance exception of type 'System.FormatException' occurred in Microsoft.VisualBasic.dll
[22168] 00000000 : 07 : . <-- RESULT RECEIVED, TEST2
[22168] Socket#31352595::EndSend(OverlappedAsyncResult#31071611)
[22168] Exiting Socket#31352595::EndSend() -> Int32#1
[22168] Socket#31352595::BeginReceive()
[22168] Exiting Socket#31352595::BeginReceive() -> OverlappedAsyncResult#51673536
SendCallBack 2 1
[4640] Data from Socket#31352595::PostCompletion
[4640] 00000000 : :
ReceiveCallback Exit 3
The thread '<No Name>' (0x4b1c) has exited with code 0 (0x0).
ReceiveCallback In 4
[4640] Socket#31352595::EndReceive(OverlappedAsyncResult#51673536)
[4640] Exiting Socket#31352595::EndReceive() -> Int32#0
ReceiveCallback Exit 4
[4640] Socket#37088038::Socket()
[4640] Exiting Socket#37088038::Socket()
AcceptCallback Start3
[4640] Socket#49538252::EndAccept(AcceptAsyncResult#39421196)
in connect WHILE 4
[17872] Socket#40528290::BeginAccept()
[17872] Exiting Socket#40528290::BeginAccept() -> AcceptAsyncResult#8948635
//ERROR THROWN HERE
AcceptCallback End 3
Monitoring with netstat
When the service is started, this appears, indicating the service is listening on port 10002
TCP 0.0.0.0:10002 LON-WKS-ZER01:0 LISTENING
On the 1st and 2nd scans (ie successful) everything works fine. The test web app connects, sends 'scantext', various callback delegates are fired, and we get a good reply.
Netstat during the 1st test, after the connection is made :
TCP 0.0.0.0:10002 LON-WKS-ZER01:0 LISTENING
TCP 127.0.0.1:10002 apps:59574 ESTABLISHED
TCP 127.0.0.1:59574 apps:10002 ESTABLISHED
(then scan #1 is completed)
When testApp mTCP.Close() called, the status changes to CLOSE_WAIT and FIN_WAIT_2
TCP 0.0.0.0:10002 LON-WKS-ZER01:0 LISTENING
TCP 127.0.0.1:10002 apps:59574 CLOSE_WAIT
TCP 127.0.0.1:59574 apps:10002 FIN_WAIT_2
A few mins later, the CLOSE and FIN connections disappear but still have the LISTENER
TCP 0.0.0.0:10002 LON-WKS-ZER01:0 LISTENING
Next, send scan#2, it repeats the sequence as above, with a successful result.
On the third scan, when it attempts to make a new connection, the exception is thrown in AcceptCallback on this line :
clntSock = servSock.ClntSock.EndAccept(asyncResult)
Specifically, it's an ArgumentException, 'asyncResult was not created by a call to BeginAccept' (see EndAccept)
So, for reasons I can't quite fathom, the IASyncResult of the 3rd test is causing the EndAccept method to throw an ArgumentException.
To summarise the bug - the Connect call's BeginAccept sets up a delegate for AcceptCallback and passes an IASyncResult. The AcceptCallBacks EndAccept throws an ArgumentException
I realise the way things are being done are not very up to date and we'd be better off with something else, but with one thing and another (time, resource) I need to try and make the slight adaptation work. But I don't understand why (existing client app) CONNECT, scan,scan,scan,scan etc works, but (web app) CONNECT,scan,DISCONNECT, CONNECT, scan, DISCONNECT fails on the THIRD scan's CONNECT
Thanks in advance for any suggestions.
There is a similar issue raised and answered here
... you are holding the socket object in a class-scoped variable. So, if
somehow the socket gets disconnected while the ReadCallback is
executing and you reconnect it (thereby changing the socket object) -
now they don't match, you are trying to complete the Async request
using the new object when the old one is the one actually completing.
In your case it is the variable cState. On Connect method, if you just declare a new instance of cState locally which holds the socket then the error may stops occuring.
Dim clientState As New ClientState(servSock)
clientState.ClntSock.Bind(New IPEndPoint(System.Net.IPAddress.Any, TCPPort))
clientState.ClntSock.Listen(Backlog)
While True
Dim result As IAsyncResult = servSock.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), clientState)
result.AsyncWaitHandle.WaitOne()
End While
And also, mTCP should be disposed on the client side.

Using ADO in VBA to connect to PostgreSQL

I am having trouble finding clear and reliable examples of connecting to a PostgreSQL database from Excel using VBA ADO. Admittedly, I am new to VBA and most examples and tutorials are very Access or MSSQL centered. (I work mostly in Ruby, Rails, Perl and PostgreSQL.)
I am looking for code to connect and return a simple query (SELECT * FROM customers;) to an Excel sheet. Connection parameters (server ip, user, pass, database) are located within cells in a separate worksheet.
I appreciate your help and patience.
Code:
Sub ConnectDatabaseTest()
Dim cnn As ADODB.connection
Dim cmd As ADODB.Command
Dim param As ADODB.Parameter
Dim xlSheet As Worksheet
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim i As Integer
' Connection Parameters
Dim strUsername As String
Dim strPassword As String
Dim strServerAddress As String
Dim strDatabase As String
' User:
strUsername = Sheets("CONFIG").Range("B4").Value
' Password:
strPassword = Sheets("CONFIG").Range("B5").Value
' Server Address:
strServerAddress = Sheets("CONFIG").Range("B6").Value
' Database
strDatabase = Sheets("CONFIG").Range("B3").Value
Set xlSheet = Sheets("TEST")
xlSheet.Activate
Range("A3").Activate
Selection.CurrentRegion.Select
Selection.ClearContents
Range("A1").Select
Set cnn = New ADODB.connection
sConnString = "DRIVER={PostgreSQL Unicode};DATABASE=" & strDatabase & ";SERVER=" & strServerAddress & _
";UID=" & strUsername & ";PWD=" & strPassword
cnn.Open sConnString
cmd.ActiveConnection = cnn
Dim strSQL As String
strSQL = "SELECT * FROM customers"
cmd.CommandType = ADODB.CommandTypeEnum.adCmdText
cmd.ActiveConnection = cnn
cmd.CommandText = strSQL
...
It seems to break here: cmd.ActiveConnection = cnn
EDIT: added sample code.
EDIT: sConnString gets set to:
DRIVER={PostgreSQL35W};DATABASE=my_database;SERVER=1.2.3.4;UID=analyst;PWD=sekrit
UPDATE 2/7: I changed the 'DRIVER' parameter in the connection string:
sConnString = "DRIVER={PostgreSQL Unicode};DATABASE=" & strDatabase & ";SERVER=" & strServerAddress & _
";UID=" & strUsername & ";PWD=" & strPassword & ";"
...and I get a different error: 'Run-time error 91: Object variable or With block variable not set'
Hm. Ideas?
I wan't using a DSN as I am using an ODBC driver as opposed to OLE DB. By referencing a DSN, the above code works with very few changes.
See this question for how I found the answer once I began to suspect OLE DB/ODBC to the issue.
Does ADO work with ODBC drivers or only OLE DB providers?
New Code here:
Sub GetCustomers()
Dim oConn As New ADODB.connection
Dim cmd As New ADODB.Command
' Connection Parameters
Dim strUsername As String
Dim strPassword As String
Dim strServerAddress As String
Dim strDatabase As String
' User:
strUsername = Sheets("CONFIG").Range("B4").Value
' Password:
strPassword = Sheets("CONFIG").Range("B5").Value
' Server Address:
strServerAddress = Sheets("CONFIG").Range("B6").Value
' Database
strDatabase = Sheets("CONFIG").Range("B3").Value
oConn.Open "DSN=my_system_dsn;" & _
"Database=" & strDatabase & ";" & _
"Uid=" & strUsername & ";" & _
"Pwd=" & strPassword
Set xlSheet = Sheets("CUSTOMERS")
xlSheet.Activate
Range("A3").Activate
Selection.CurrentRegion.Select
Selection.ClearContents
Range("A1").Select
Dim strSQL As String
strSQL = "SELECT * FROM customers"
cmd.CommandType = ADODB.CommandTypeEnum.adCmdText
cmd.ActiveConnection = oConn
cmd.CommandText = strSQL
Set rs = New ADODB.Recordset
Set rs = cmd.Execute
For i = 1 To rs.Fields.Count
ActiveSheet.Cells(3, i).Value = rs.Fields(i - 1).Name
Next i
xlSheet.Range(xlSheet.Cells(3, 1), _
xlSheet.Cells(3, rs.Fields.Count)).Font.Bold = True
ActiveSheet.Range("A4").CopyFromRecordset rs
xlSheet.Select
Range("A3").Select
Selection.CurrentRegion.Select
Selection.Columns.AutoFit
Range("A1").Select
rs.Close
oConn.Close
Set cmd = Nothing
Set param = Nothing
Set rs = Nothing
Set cnn = Nothing
Set xlSheet = Nothing
End Sub
The System DSN is configured to use the PostgreSQL Unicode driver. I chose not to use OLE DB even though there is a provider available. If you look at PGFoundry, you will see it has many problems and has not been updated in several years.
In the original Code, "PostgreSQL35W" is a DSN name which included the default host and port. When you changed to "PostgreSQL Unicode", it is a driver and your connection string is lacking the value for the port. Remember to access PostgreSQL directly from driver, you need at least 5 parameters:
host
port
userid
password
database
If you are using DSN, some parameters may be defined as default.
Not sure about the details of the actual DB connection, but there is a simple although common mistake with your statement: you need to use 'set' when working with objects:
set cmd.ActiveConnection = cnn
Set cmd = New ADODB.Command
cmd.ActiveConnection = cnn

How do I include scripting (classic ASP pages, vbscript, etc.) to TcpListener and Socket Web Server Console Application?

Forgive me, as I am new to this. I found some code online that I'm using in a console application that can set up a local web server, and serve HTML pages locally. I will post the code - but I need to be able to serve ASP pages and pages with vbscripting. Is it possible with this code below, and if so, what can I add to do so? Since this code is so simple, I'm really hoping to modify it to add ASP/Vbscript, and continue on. Thanks in advance!!
Public ip As String = "127.0.0.1"
Public port As String = "80"
Public rootpath As String = "C:\wwwroot\"
Public defaultpage As String = "default.asp"
Public Sub Main()
Try
Dim hostName As String = Dns.GetHostName()
Dim serverIP As IPAddress = IPAddress.Parse(ip)
Dim tcpListener As New TcpListener(serverIP, Int32.Parse(port))
tcpListener.Start()
Console.WriteLine("Web server started at: " & serverIP.ToString() & ":" & Port)
Dim httpSession As New HTTPSession(tcpListener)
Dim serverThread As New Thread(New ThreadStart(AddressOf httpSession.ProcessThread))
serverThread.Start()
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
End Try
End Sub
Public Class HTTPSession
Private tcpListener As System.Net.Sockets.TcpListener
Private clientSocket As System.Net.Sockets.Socket
Public Sub New(ByVal tcpListener As System.Net.Sockets.TcpListener)
Me.tcpListener = tcpListener
End Sub
Public Sub ProcessThread()
While (True)
Try
clientSocket = tcpListener.AcceptSocket()
' Socket Information
Dim clientInfo As IPEndPoint = CType(clientSocket.RemoteEndPoint, IPEndPoint)
Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString())
' Set Thread for each Web Browser Connection
Dim clientThread As New Thread(New ThreadStart(AddressOf ProcessRequest))
clientThread.Start()
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
If clientSocket.Connected Then
clientSocket.Close()
End If
End Try
End While
End Sub
Protected Sub ProcessRequest()
Dim recvBytes(1024) As Byte
Dim htmlReq As String = Nothing
Dim bytes As Int32
Try
' Receive HTTP Request from Web Browser
bytes = clientSocket.Receive(recvBytes, 0, clientSocket.Available, SocketFlags.None)
htmlReq = Encoding.ASCII.GetString(recvBytes, 0, bytes)
Console.WriteLine("HTTP Request: ")
Console.WriteLine(htmlReq)
Dim strArray() As String
Dim strRequest As String
strArray = htmlReq.Trim.Split(" ")
' Determine the HTTP method (GET only)
If strArray(0).Trim().ToUpper.Equals("GET") Then
strRequest = strArray(1).Trim
If (strRequest.StartsWith("/")) Then
strRequest = strRequest.Substring(1)
End If
If (strRequest.EndsWith("/") Or strRequest.Equals("")) Then
strRequest = strRequest & defaultPage
End If
strRequest = rootPath & strRequest
sendHTMLResponse(strRequest)
Else ' Not HTTP GET method
strRequest = rootPath & "Error\" & "400.html"
sendHTMLResponse(strRequest)
End If
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
If clientSocket.Connected Then
clientSocket.Close()
End If
End Try
End Sub
' Send HTTP Response
Private Sub sendHTMLResponse(ByVal httpRequest As String)
Try
' Get the file content of HTTP Request
Dim streamReader As StreamReader = New StreamReader(httpRequest)
Dim strBuff As String = streamReader.ReadToEnd()
streamReader.Close()
streamReader = Nothing
' The content Length of HTTP Request
Dim respByte() As Byte = Encoding.UTF8.GetBytes(strBuff)
'Dim respByte() As Byte = Encoding.ASCII.GetBytes(strBuff)
' Set HTML Header
Dim htmlHeader As String = _
"HTTP/1.0 200 OK" & ControlChars.CrLf & _
"Server: WebServer 1.0" & ControlChars.CrLf & _
"Content-Length: " & respByte.Length & ControlChars.CrLf & _
"Content-Type: " & getContentType(httpRequest) & _
ControlChars.CrLf & ControlChars.CrLf
' The content Length of HTML Header
'Dim headerByte() As Byte = Encoding.ASCII.GetBytes(htmlHeader)
Dim headerByte() As Byte = Encoding.UTF8.GetBytes(htmlHeader)
Console.WriteLine("HTML Header: " & ControlChars.CrLf & htmlHeader)
' Send HTML Header back to Web Browser
clientSocket.Send(headerByte, 0, headerByte.Length, SocketFlags.None)
' Send HTML Content back to Web Browser
clientSocket.Send(respByte, 0, respByte.Length, SocketFlags.None)
' Close HTTP Socket connection
clientSocket.Shutdown(SocketShutdown.Both)
clientSocket.Close()
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
If clientSocket.Connected Then
clientSocket.Close()
End If
End Try
End Sub
' Get Content Type
Private Function getContentType(ByVal httpRequest As String) As String
If (httpRequest.EndsWith("html")) Then
Return "text/html"
ElseIf (httpRequest.EndsWith("asp")) Then
Return "text/html"
ElseIf (httpRequest.EndsWith("htm")) Then
Return "text/html"
ElseIf (httpRequest.EndsWith("txt")) Then
Return "text/plain"
ElseIf (httpRequest.EndsWith("gif")) Then
Return "image/gif"
ElseIf (httpRequest.EndsWith("jpg")) Then
Return "image/jpeg"
ElseIf (httpRequest.EndsWith("jpeg")) Then
Return "image/jpeg"
ElseIf (httpRequest.EndsWith("pdf")) Then
Return "application/pdf"
ElseIf (httpRequest.EndsWith("pdf")) Then
Return "application/pdf"
ElseIf (httpRequest.EndsWith("doc")) Then
Return "application/msword"
ElseIf (httpRequest.EndsWith("xls")) Then
Return "application/vnd.ms-excel"
ElseIf (httpRequest.EndsWith("ppt")) Then
Return "application/vnd.ms-powerpoint"
Else
Return "text/plain"
End If
End Function
End Class
I think you have two choices.
Stop doing that because its certain to be world of pain and cost.
However if you are determined to try and make it happen then take a look at the ASP Classic Compiler codeplex project.

Crystal Report viewer- Server has not yet been opened

I Have a vb6 application using crystal report 8.5 and sql server 2005.My issue is that when I print report i get Server has not yet been opened.Here is my code in vb.:
Option Explicit
Dim ctr As Integer
Dim cn As New ADODB.Connection--Provider=SQLOLEDB.1;Password=password;Persist Security Info=True;User ID=user ID;Initial Catalog=database Name;Data Source=server Name
Dim crApp As CRAXDRT.Application
Dim crReport As CRAXDRT.Report
Dim crtable As CRAXDRT.DatabaseTable
Private Sub prin_Click()
Dim rs As New ADODB.Recordset
Set cn = New ADODB.Connection
cn.ConnectionString = MDI1.txtado
cn.Open
Set rs = New ADODB.Recordset
rs.Open "select * from temp_abs_yes", cn, adOpenKeyset, adLockOptimistic
Set crApp = New CRAXDRT.Application
Set crReport = crApp.OpenReport("C:\Users\user1.dom\Desktop\ANP\abs_yes.rpt")
crReport.Database.Tables.Item(1).SetLogOnInfo "servername", "databasename", "user", "password"
crReport.Database.Tables.Item(1).SetDataSource rs, 3
crReport.DiscardSavedData
Viewer.ReportSource = crReport
Viewer.ViewReport
rs.close
Set rs = Nothing
Set crReport = Nothing
Set crApp = Nothing
End Sub
I think doing "SetLogOnInfo" is innecesary in that case, as you are assigning the data to report
Probably is not your case, but for the help of someone else.
I got that error when I assigned the servername parameter incorrectly.
The correct parameters I used for logon (for an oracle DB):
[...]Item(1).SetLogOnInfo "[tnsnames]", "", "[db user]", "[db password]"
I resolved by updating dll
p2soledb.dll
in c:\Windows\Crystal I got the details from here