I need to detect if an iPhone is plugged in. I don't know how to make that in VB.NET. I tried to play around with WMI but I'm just a beginner.
Can everyone help me?
I tried this but it only detects Mass Storage
Public Class Form1
Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher
Public USBDriveName As String
Public USBDriveLetter As String
Public Sub StartDetection()
' __InstanceOperationEvent will trap both Creation and Deletion of class instances
Dim query2 As New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 " _
& "WHERE TargetInstance ISA 'Win32_DiskDrive'")
m_MediaConnectWatcher = New ManagementEventWatcher
m_MediaConnectWatcher.Query = query2
m_MediaConnectWatcher.Start()
End Sub
Private Sub Arrived(ByVal sender As Object, ByVal e As System.Management.EventArrivedEventArgs) Handles m_MediaConnectWatcher.EventArrived
Dim mbo, obj As ManagementBaseObject
' the first thing we have to do is figure out if this is a creation or deletion event
mbo = CType(e.NewEvent, ManagementBaseObject)
' next we need a copy of the instance that was either created or deleted
obj = CType(mbo("TargetInstance"), ManagementBaseObject)
Select Case mbo.ClassPath.ClassName
Case "__InstanceCreationEvent"
If obj("InterfaceType") = "USB" Then
MsgBox(obj("Caption") & " (Drive letter " & GetDriveLetterFromDisk(obj("Name")) & ") has been plugged in")
Else
MsgBox(obj("InterfaceType"))
End If
Case "__InstanceDeletionEvent"
If obj("InterfaceType") = "USB" Then
MsgBox(obj("Caption") & " has been unplugged")
If obj("Caption") = USBDriveName Then
USBDriveLetter = ""
USBDriveName = ""
End If
Else
MsgBox(obj("InterfaceType"))
End If
Case Else
MsgBox("nope: " & obj("Caption"))
End Select
End Sub
Private Function GetDriveLetterFromDisk(ByVal Name As String) As String
Dim oq_part, oq_disk As ObjectQuery
Dim mos_part, mos_disk As ManagementObjectSearcher
Dim obj_part, obj_disk As ManagementObject
Dim ans As String = ""
' WMI queries use the "\" as an escape charcter
Name = Replace(Name, "\", "\\")
' First we map the Win32_DiskDrive instance with the association called
' Win32_DiskDriveToDiskPartition. Then we map the Win23_DiskPartion
' instance with the assocation called Win32_LogicalDiskToPartition
oq_part = New ObjectQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=""" & Name & """} WHERE AssocClass = Win32_DiskDriveToDiskPartition")
mos_part = New ManagementObjectSearcher(oq_part)
For Each obj_part In mos_part.Get()
oq_disk = New ObjectQuery("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""" & obj_part("DeviceID") & """} WHERE AssocClass = Win32_LogicalDiskToPartition")
mos_disk = New ManagementObjectSearcher(oq_disk)
For Each obj_disk In mos_disk.Get()
ans &= obj_disk("Name") & ","
Next
Next
Return ans.Trim(","c)
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
StartDetection()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
m_MediaConnectWatcher.Stop()
Application.Exit()
End Sub
End Class
Related
I have a code that I was able to string together that logs my sent emails into an excel sheet so i can use that data for other analysis.
In it, I have it resolving the name into an email as outlook shortens it ("Jimenez, Ramon" = email#address.com) as outlook configured this and it works when i send an email to anyone in my company as they are in my address book.
Now, when I email anyone outside it defaults to lastName, firstName so it is not converting this and logging it.
I thought the code I have in here already does this, but I guess not. I have already come this far and I am NOT a software guru at all. Does anyone have insight on how I can also include this as well?? Please see code below:
Private WithEvents Items As Outlook.Items
Const strFile As String = "C:\Users\a0227084\Videos\work\test.xlsx"
Private Sub Application_Startup()
Dim OLApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set OLApp = Outlook.Application
Set objNS = OLApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderSentMail).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
FullName = Split(Msg.To, ";")
For i = 0 To UBound(FullName)
If i = 0 Then
STRNAME = ResolveDisplayNameToSMTP(FullName(i))
Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
ElseIf ResolveDisplayNameToSMTP(FullName(i)) <> "" Then
STRNAME = ResolveDisplayNameToSMTP(FullName(i))
Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
End If
Next i
'Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
Sub tes2t()
End Sub
Function getRecepientEmailAddress(eml As Variant)
Set out = CreateObject("System.Collections.Arraylist") ' a JavaScript-y array
For Each emlAddr In eml.Recipients
If Left(emlAddr.Address, 1) = "/" Then
' it's an Exchange email address... resolve it to an SMTP email address
out.Add ResolveDisplayNameToSMTP(emlAddr)
Else
out.Add emlAddr.Address
End If
Next
getRecepientEmailAddres = Join(out.ToArray(), ";")
End Function
Function ResolveDisplayNameToSMTP(sFromName) As String
' takes a Display Name (i.e. "James Smith") and turns it into an email address (james.smith#myco.com)
' necessary because the Outlook address is a long, convoluted string when the email is going to someone in the organization.
' source: https://stackoverflow.com/questions/31161726/creating-a-check-names-button-in-excel
Dim OLApp As Object 'Outlook.Application
Dim oRecip As Object 'Outlook.Recipient
Dim oEU As Object 'Outlook.ExchangeUser
Dim oEDL As Object 'Outlook.ExchangeDistributionList
Set OLApp = CreateObject("Outlook.Application")
Set oRecip = OLApp.Session.CreateRecipient(sFromName)
oRecip.Resolve
If oRecip.Resolved Then
Select Case oRecip.AddressEntry.AddressEntryUserType
Case 0, 5 'olExchangeUserAddressEntry & olExchangeRemoteUserAddressEntry
Set oEU = oRecip.AddressEntry.GetExchangeUser
If Not (oEU Is Nothing) Then
ResolveDisplayNameToSMTP = oEU.PrimarySmtpAddress
End If
Case 10, 30 'olOutlookContactAddressEntry & 'olSmtpAddressEntry
Dim PR_SMTP_ADDRESS As String
PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
ResolveDisplayNameToSMTP = oRecip.AddressEntry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS)
End Select
End If
End Function
Sub Write_to_excel(str1 As String, str2 As String, str3 As String)
Dim xlApp As Object
Dim sourceWB As Workbook
Dim sourceWH As Worksheet
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
End With
Set sourceWB = Workbooks.Open(strFile, False, False)
Set sourceWH = sourceWB.Worksheets("Sheet1")
sourceWB.Activate
With sourceWH
lastrow = .Cells(.rows.Count, "A").End(xlUp).Row
End With
sourceWH.Cells(lastrow + 1, 1) = str1
sourceWH.Cells(lastrow + 1, 2) = str2
sourceWH.Cells(lastrow + 1, 3) = str3
sourceWB.Save
sourceWB.Close
End Sub
Error message and corrected code
Regards,
Ramon
First of all, there is no need to create a new Application instance in the ResolveDisplayNameToSMTP method:
Set OLApp = CreateObject("Outlook.Application")
Instead, you can use the Application property available in the Outlook VBA editor out of the box.
Second, you need to use the following code to get the SMTP address from the AddressEntry object:
Dim PR_SMTP_ADDRESS As String
Set PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
ResolveDisplayNameToSMTP = oRecip.AddressEntry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS)
Instead of the following line:
ResolveDisplayNameToSMTP = oRecip.AddressEntry.Address
Read more about that in the How to get the SMTP Address of the Sender of a Mail Item using Outlook Object Model? article.
I have following code block which is working perfectly for OpenOffice SDK to automate Mail merge functionality.
Public Function runQueryOnDataSource(ByVal nameOfdDtaource As String, ByVal query As String) As Boolean
strLog = strLog + vbCrLf + Now.ToString() + ": runQueryOnDataSource nameOfdDtaource:" + nameOfdDtaource + ",query:" + query + "-Started"
Dim oDB As Object, oBase As Object
Dim oStatement As Object
Dim rSQL As String
Dim oRequete As Object
Dim oServiceManager As Object, CreateUnoService As Object
Try
'Creation instance Open office
oServiceManager = CreateObject("com.sun.star.ServiceManager")
CreateUnoService = oServiceManager.createInstance("com.sun.star.sdb.DatabaseContext")
mxMSFactory = (uno.util.Bootstrap.bootstrap()).getServiceManager()
oDB = CreateUnoService.getByName(nameOfdDtaource) 'oDB=XDataSource
'Connection
oBase = oDB.getConnection("", "") 'oBase=XConnection
oStatement = oBase.createStatement 'XStatement
'rSQL = "SELECT * FROM ""26_MailMergeResult_DEMO"
rSQL = query
oRequete = oStatement.execute(rSQL)
Return True
Catch ex As Exception
strLog = strLog + vbCrLf + Now.ToString() + ": Exception" + ex.ToString()
Throw ex
Finally
oDB = Nothing
oBase.Close()
oBase.Dispose()
End Try
strLog = strLog + vbCrLf + Now.ToString() + ": runQueryOnDataSource-Finished"
Return True
End Function
Above code is used to insert data into the DataSource already registered with libre office.But Now when I try to use it, line oServiceManager = CreateObject("com.sun.star.ServiceManager") generates error "Error Creating ActiveX object".
Do anyone have idea, How do I fix this.
This code does not look right, so I'm surprised it ever worked. In other examples, the bootstrap() line always goes first. Then use that service manager instead of a separate oServiceManager variable.
For example, see the Java code at https://www.openoffice.org/udk/common/man/spec/transparentofficecomponents.html.
EDIT:
You're almost there. The getByName() method returns uno.Any, which has a property called Value that DirectCast can use.
Dim oDB As XDataSource
Dim oBase As XConnection = Nothing
Dim xContext As XComponentContext = uno.util.Bootstrap.bootstrap()
Dim xMSFactory As XMultiServiceFactory = DirectCast(
xContext.getServiceManager(), XMultiServiceFactory)
Dim xNameAccess As XNameAccess = DirectCast(
xMSFactory.createInstance("com.sun.star.sdb.DatabaseContext"), XNameAccess)
oDB = DirectCast(xNameAccess.getByName("Bibliography").Value, XDataSource)
oBase = DirectCast(oDB.getConnection("", ""), XConnection)
I am writing an VB6 application in which I'm making use of cdosys.dll in order to send mails. I am able to attach and send the mails but the problem that I'm facing is the attached file icon image is not getting displayed correctly (default icon image is getting displayed). Also I am not able to attach the files between two paragraphs in the body part. I am using IBM Lotus Notes mail system. Please find below the code that I'm using and also the screenshot of issue that I'm facing
Set objEmail = CreateObject("CDO.Message")
objEmail.MimeFormatted = True
objEmail.To = to address
objEmail.From = from address
objEmail.Subject = "Additional Replacement Letters : " & Format(Now, "mm/dd")
objEmail.TextBody = "Hello Team," & vbCrLf & vbCrLf & "find below the attached letters"
Set fld = FSO.GetFolder(path)
For Each fil In fld.Files
Set iBp = objEmail.AddAttachment(fil)
Next
objEmail.TextBody = "Revert to me for any concerns"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.domain.com"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send
Please help me how to solve this issue.
First, for the icons of files appearing in the attachments section. If a generic file icon is displayed, it may be because either:
your system doesn't have any/the correct MIME type defined for *.doc files (shouldn't be the case if you have Word installed);
the client cannot match any extension (and thus an icon) to the MIME type included with an attached file; or
if the recipient is viewing the emails through a web-based email system, the provider might not have/provide an image to show as an icon for those types of files.
In most cases it's the client software that is too lazy to display the appropriate icon.
Now, if you want the files to appear amid the email body, this is another story. Here an overview of what needs to be done:
First, you don't add files through IMessage.AddAttachment() but with IMessage.AddRelatedBodyPart();
When called, IMessage.AddRelatedBodyPart() will return an IBodyPart object;
Using the IBodyPart object, you need to assign a unique content ID to the piece – you can use the file name, but whatever the CID it must not contain spaces;
You then need to write your email body in HTML (so you can link to them);
In the message you'll add links to related parts as such:
Link to the file
where %CONTENT_ID_OF_THE_FILE% is the content ID you set for the file. Example:
Link to the file
There are two things you'll have to remember if you insert files this way:
You won't see any icon aside or elsewhere related to the file(s) attached, i.e. they'll appear as you set them through your HTML code. If you want any, you'll have to add images (not icon files) the same way and refer to them using the <img> tag and their content ID.
In many clients, you won't see the files in the attachments section, unless they're not being referred to in the body (or their content ID doesn't match, which is the same thing)
Here is some code. It's pretty complete, as I had to test it because I wasn't sure to remember everything correctly. Also, it is assumed you have among the references for your project Microsoft CDO for Windows 2000 Library and Microsoft Scripting Runtime.
Public Function SendNewLetters(ByVal PathForLetters As String, ByVal FromName As String, ByVal FromEmail As String, ByVal ToName As String, _
ByVal ToEmail As String, ByVal SMTPServer As String, ByVal SMTPPort As Long, ByVal SMTPUser As String, _
ByVal SMTPPassword As String, Optional ByVal UseSSL As Boolean = False, Optional ByRef ErrorCode As Long = 0, _
Optional ErrorDesc As String = vbNullString) As Boolean
On Error GoTo ErrorHandler
Const CdoReferenceTypeName = 1
Dim iMsg As CDO.Message ' Not using CreateObject() because I have the reference added
Dim sFileCID As String, sFileExt As String
Dim sIconImageSrc As String, sIconImageCID As String
Dim iBpAttachment As CDO.IBodyPart ' Will be reused more than once
Dim iBpIconImage As CDO.IBodyPart
Dim oFSO As Scripting.FileSystemObject
Dim oFolder As Scripting.Folder
Dim oFile As Scripting.File
Dim oDictAddedExtIcons As Scripting.Dictionary
Set iMsg = New CDO.Message
' Configure SMTP parameters
With iMsg.Configuration
.Fields(cdoSMTPServer) = SMTPServer
.Fields(cdoSMTPServerPort) = SMTPPort
.Fields(cdoSMTPUseSSL) = UseSSL
.Fields(cdoSMTPAuthenticate) = cdoBasic
.Fields(cdoSendUserName) = SMTPUser
.Fields(cdoSendPassword) = SMTPPassword
.Fields(cdoSMTPConnectionTimeout) = 60
.Fields(cdoSendUsingMethod) = cdoSendUsingPort
.Fields.Update
End With
' Set From and To fields
If Len(FromName) > 0 Then
' Let's say we already QP-encoded any special chars for the name
' and checked the email address
iMsg.From = FromName & " <" & FromEmail & ">"
Else
iMsg.From = FromEmail
End If
If Len(ToName) > 0 Then
' Same thing here
iMsg.To = ToName & " <" & ToEmail & ">"
Else
iMsg.To = ToEmail
End If
' Set subject (would need QP encoding as well)
iMsg.Subject = "Additional Replacement Letters : " & Format(Now, "mm/dd")
' Build the body
iMsg.HTMLBody = "<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional //EN""><html><body><p>Hello Team,<br/><br/>" & _
"Please find below the attached letters</p><div style=""display: table"">"
' Will be used to make sure icon images are only added once
Set oDictAddedExtIcons = New Scripting.Dictionary
' Add files here, one new body part for each
Set oFSO = New Scripting.FileSystemObject
If oFSO.FolderExists(PathForLetters) Then
Set oFolder = oFSO.GetFolder(PathForLetters)
For Each oFile In oFolder.Files
' IMPORTANT: Content-IDs should not contain spaces
sFileCID = Replace$(oFile.Name, " ", "_")
Set iBpAttachment = iMsg.AddRelatedBodyPart(oFile.Path, oFile.Name, CdoReferenceTypeName)
iBpAttachment.Fields.Item("urn:schemas:mailheader:content-id") = "<" & sFileCID & ">"
iBpAttachment.Fields.Update ' Dont' forget that line
sFileExt = LCase$(GetFileExtension(oFile.Name))
sIconImageSrc = vbNullString
Select Case sFileExt
Case "doc"
' We provide here the path to a 32x32 image of the doc file icon
sIconImageSrc = "C:\Users\MyUserName\Desktop\DocIcon.png"
' We could also provide images for other extensions, or
' (more involved) query the DefaultIcon for any extension from
' the registry, load the icon from the ico/exe/dll file and
' find the best size/resize if necessary (already have the
' code, but it's a *lot* of code).
Case ".."
' Add support for more
End Select
If Len(sIconImageSrc) > 0 Then
If Not oDictAddedExtIcons.Exists(sFileExt) Then
sIconImageCID = GetFilePart(sIconImageSrc) ' Is the filename for this and the next line
Set iBpIconImage = iMsg.AddRelatedBodyPart(sIconImageSrc, sIconImageCID, CdoReferenceTypeName)
' IMPORTANT: Content-IDs should not contain spaces
sIconImageCID = Replace$(sIconImageCID, " ", "_")
iBpIconImage.Fields.Item("urn:schemas:mailheader:content-id") = "<" & sIconImageCID & ">"
iBpIconImage.Fields.Update ' Dont' forget that line
oDictAddedExtIcons.Add sFileExt, sIconImageCID
sIconImageSrc = "cid:" & sIconImageCID
Else
sIconImageSrc = "cid:" & oDictAddedExtIcons.Item(sFileExt)
End If
End If
iMsg.HTMLBody = iMsg.HTMLBody & "<div style=""display: table-row""><div style=""text-align: left; " & _
"vertical-align: middle; margin-right: 10px;"">"
If Len(sIconImageSrc) > 0 Then
iMsg.HTMLBody = iMsg.HTMLBody & "<img src=""" & sIconImageSrc & """ border=""0"" />"
Else
iMsg.HTMLBody = iMsg.HTMLBody & " "
End If
iMsg.HTMLBody = iMsg.HTMLBody & "</div><div style=""display: table-cell; text-align: left; vertical-align: middle;"">"
iMsg.HTMLBody = iMsg.HTMLBody & "" & oFile.Name & ""
iMsg.HTMLBody = iMsg.HTMLBody & "</div></div>"
Next
End If
iMsg.HTMLBody = iMsg.HTMLBody & "</div><br/>"
iMsg.HTMLBody = iMsg.HTMLBody & "<p>Revert to me for any concerns.</p></body></html>"
' Send away!
iMsg.Send
SendNewLetters = True
Exit Function
ErrorHandler:
ErrorCode = Err.Number
ErrorDesc = Err.Description
SendNewLetters = False
End Function
Public Function GetFilePart(ByVal FilePath As String) As String
Dim lPos As Long
lPos = InStrRev(FilePath, "\")
If lPos > 0 Then
GetFilePart = Right$(FilePath, Len(FilePath) - lPos)
End If
End Function
Public Function GetFileExtension(ByVal FilePath As String, Optional ByVal WithDot As Boolean = False) As String
Dim lPos As Long
lPos = InStrRev(FilePath, ".")
If InStr(1, FilePath, ".") Then
If WithDot Then
GetFileExtension = Right$(FilePath, Len(FilePath) - lPos + 1)
Else
GetFileExtension = Right$(FilePath, Len(FilePath) - lPos)
End If
End If
End Function
Here is the image I used for the *.doc icon:
And this is what it would look like when sent:
I hope it works for you!
I have the following property in my clsdata class:
Public Property Get PatientCount() As Long
PatientCount = UBound(maobjPatient)
End Property
I also have this function in my class:
Private Function CountNonEmptyLines(ByVal strfile As String) As Long
Dim intFile As Integer
Dim strLine As String
Dim lngcount As Long
intFile = FreeFile
Open strfile For Input As intFile
lngcount = 0&
Do While Not EOF(intFile)
Line Input #intFile, strLine
If Len(strLine) > 0 Then
lngcount = lngcount + 1
End If
Loop
Close #intFile
CountNonEmptyLines = lngcount
End Function
the code of InputData is the following:
Public Sub InputData()
Dim blnLoaded As Boolean
Dim path As String
Dim file As String
Dim lnglines As Long
path = MyForm.TextPath
file = MyForm.TextFile
If LoadData(path, file) = False Then
MsgBox FileErrorString
Else
blnLoaded = LoadData(path, file)
End If
End Sub
and the code of LoadData is:
Private Function LoadData( _
ByVal strPath As String, _
ByVal strfile As String) _
As Boolean
Dim strPathFile As String
Dim lngRows As Long
LoadData = False
EraseData
InitialiseState
strPathFile = strPath & "\" & strfile
If Not FileExists(strPathFile) Then
Exit Function
End If
lngRows = CountNonEmptyLines(strPathFile)
If lngRows = 0 Then
Exit Function
End If
If Not LoadPatientLines(strPathFile, lngRows) Then
Exit Function
End If
mFileError = leNOERROR
LoadData = True
End Function
In my form I have a button which loads some data from a file:
Private Sub CmdLoad_Click()
Dim myData As New clsData
Call myData.InputData
End Sub
I also have a textbox:
Private Sub TextEntries_Change()
End Sub
How can I have the value of PatientCount or the lngcount from countnonemptylines function, in my textbox when I click CmdLoad, something like TextEntries.text=...?
As follow up from comments, this one works:
TextEntries.text = myData.PatientCount
I upgraded my server yesterday from Postgres 9.1 to 9.3 and since then I've been getting an error: Backend sent unrecognized response type: u
I'm using npgsql to connect from my application to the server.
I remember that I used to get this error a while back and I haven't seen it in a while.
A full line from my log is:
Backend sent unrecognized response type: u
INSERT INTO stockcodes_rating (item_code,rating,price_range,user_id,timestamp_of_rating) VALUES ('10245684','5','Reasonable','10832',now())
My code for the procedure is:
Public Function InsertRating(ByVal Stockcode As String, ByVal Rating As Integer, ByVal PriceRange As String, ByVal UserId As String) As String
Dim objDBWrite As dlNpgSQL
objDBWrite = New dlNpgSQL("PostgreConnectionStringWrite", ConfigurationManager.AppSettings("CurrentDatabase"))
tmpSQL = "INSERT INTO stockcodes_rating (item_code,rating,price_range,user_id,timestamp_of_rating) VALUES " & _
"('" & Stockcode.ToUpper & "','" & Rating & "','" & PriceRange & "','" & UserId & "',now())"
Try
objDBWrite.ExecuteQuery(tmpSQL)
Catch ex As Exception
objDBWrite.CloseConnection()
Return ex.Message
Finally
objDBWrite.CloseConnection()
End Try
Return "Success"
End Function
My code for the dlNpgSQLclass is:
Imports Npgsql
Public Class dlNpgSQL
Dim _sqlConnection As NpgsqlConnection
Dim _sqlCommand As NpgsqlCommand
Dim _sqlDataAdapter As NpgsqlDataAdapter
Dim _dataset As DataSet
Public Sub New()
On Error GoTo ErrZ
_sqlConnection = New NpgsqlConnection(ConfigurationManager.ConnectionStrings("PostgreRemoteConnectionString").ConnectionString)
Exit Sub
End Sub
Public Sub New(ByVal WhichConnectionString As String)
On Error GoTo ErrZ
_sqlConnection = New NpgsqlConnection(ConfigurationManager.ConnectionStrings(WhichConnectionString).ConnectionString)
Exit Sub
End Sub
Public Sub New(ByVal WhichConnectionString As String, ByVal WhichDB As String)
On Error GoTo ErrZ
_sqlConnection = New NpgsqlConnection(ConfigurationManager.ConnectionStrings(WhichConnectionString).ConnectionString & "database=" & WhichDB & ";")
Exit Sub
End Sub
Public Function OpenConnection() As NpgsqlConnection
Try
If _sqlConnection.State = ConnectionState.Closed Then
_sqlConnection.Open()
End If
Catch ex As Exception
End Try
Return _sqlConnection
End Function
Public Sub CloseConnection()
Try
If _sqlConnection.State = ConnectionState.Open Then
_sqlConnection.Close()
End If
Catch ex As Exception
End Try
End Sub
Public Function GetDataSet(ByVal strQuery As String) As DataSet
'NpgsqlEventLog.Level = LogLevel.Normal
'NpgsqlEventLog.LogName = ("c:\npgsql.log")
'NpgsqlEventLog.EchoMessages = True
_dataset = New DataSet
Try
_sqlDataAdapter = New NpgsqlDataAdapter(strQuery, OpenConnection)
_sqlDataAdapter.Fill(_dataset)
Catch ex As Exception
End Try
Return _dataset
End Function
Public Function ReleaseDataSet(ByRef ds As DataSet) As Boolean
Try
ds.Clear()
ds.Dispose()
Catch ex As Exception
End Try
Return True
End Function
Public Function ExecuteQuery(ByVal strQuery As String) As String
'NpgsqlEventLog.Level = LogLevel.Normal
'NpgsqlEventLog.LogName = ("c:\npgsql.log")
'NpgsqlEventLog.EchoMessages = True
Dim RecordsReturned As String = ""
Try
_sqlCommand = New NpgsqlCommand(strQuery, OpenConnection)
RecordsReturned = _sqlCommand.ExecuteNonQuery()
Catch ex As Exception
Return ""
End Try
Return RecordsReturned
End Function
Public Function isR(ByVal tmpDs As DataSet, Optional ByVal tablename As Integer = 0) As Boolean
Try
If tmpDs.Tables.Count > 0 Then
If tmpDs.Tables(0).Rows.Count > 0 Then
isR = True
Else
isR = False
End If
End If
Catch ex As Exception
isR = False
End Try
End Function
End Class
What version of npgsql are you using? You probably need to upgrade to 2.0.14.3.
Better yet, try out the 2.1.0-beta1 which is quite stable and about to be released.
The same thing happened to me using Npgsql 2.0.12.0 sharing the connection between threads. Making a new connection in each thread was the solution!