Connecting to SOTAMAS90 ODBC? - vb.net

How do I connect to Mas90's file using their ODBC that they setup - SOTAMAS90? how do I do this in vb.net ?

I found this as an example - I have not tried it myself to know 100% sure if it works or not, nor do I profess myself as a vb.net programmer but it's at least something to try...
Imports System.Data
Imports Microsoft.Data.Odbc
' Database Connection
Public dbConn As OdbcConnection = Nothing
Public dbCmnd As OdbcCommand
Public dbReader As OdbcDataReader
Public dbConnStr As String
Public dbError As Exception
' Connect to MAS90 using ODBC; dbError stores the
' exception if any
Sub connectToDatabase(ByVal company As String, ByVal uid As String, ByVal pwd As String)
Dim dsn As String = "SOTAMAS90"
Dim timeout As String = "360"
' Build the connection string
dbConnStr = "DSN=" + dsn + _
";Directory=M:\MAS90" + _
";Prefix=M:\MAS90\soa\" + _
";ViewDLL=M:\MAS90\Home\" + _
";SERVER=NotTheServer" + _
";Company=" + company + _
";UID=" + uid + ";PWD=" + pwd + ";"
' Connect if not already
If (dbConn Is Nothing) Then
Try
dbConn = New OdbcConnection(dbConnStr)
dbConn.ConnectionTimeout = timeout
dbConn.Open()
dbError = Nothing
Catch ex As Exception
dbError = ex
dbConn = Nothing
End Try
End If
End Sub

Related

Why is Visual Studio (VB) not reading my SQL connection string properly?

I am writing a small windows tool to search a few SQL databases. I was able to connect and search the first database without issues but I keep getting the following login error when I try to search the second database (Database 2):
'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Login failed for user '\azahir'
You will find that <Domain>\azahir is not even specified in my connection string or anywhere in my few lines of code.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim Conn As SqlConnection
Dim Conn2 As SqlConnection
Private Sub btSearch_Click(sender As Object, e As EventArgs) Handles btSearch.Click
Conn = New SqlConnection("Data Source = <SERVER>;Initial Catalog=<DATABASE>;Integrated Security=SSPI;User ID = <Domain> \ axzahir;Password=<Password>;")
Conn.Open()
Dim cmd2 As SqlCommand = Conn.CreateCommand
cmd2.CommandText = "select firstname, lastname
from systemuserbase where firstname like" + "'%" + TxFirstName.Text + "%'" +
" And lastname Like" + " '%" + TxLastname.Text + "%'"
Dim dir As SqlDataReader = cmd2.ExecuteReader()
If dir.HasRows Then
Dim dtClient As New DataTable
dtClient.Load(dir)
dtOutput.DataSource = dtClient
End If
dir.Close()
Conn.Close()
End Sub
....
Private Sub btnArgus_Click(sender As Object, e As EventArgs) Handles btnArgus.Click
Conn2 = New SqlConnection("Data Source = <SERVER2>;Initial Catalog=<DATABASE 2>;Integrated Security=SSPI;User ID = <DOMAIN> \ axzahir;Password=<PASSWORD>;")
Conn2.Open()
Dim cmd3 As SqlCommand = Conn2.CreateCommand
cmd3.CommandText = "select userID, Fullname
from Users where FullName like" + "'%" + TxFirstName.Text + "%'" +
" And Fullname Like" + " '%" + TxLastname.Text + "%'"
Dim dir3 As SqlDataReader = cmd3.ExecuteReader()
If dir3.HasRows Then
Dim dtClient As New DataTable
dtClient.Load(dir3)
dtOutput.DataSource = dtClient
End If
dir3.Close()
Conn2.Close()
End Sub
End Class
I have verified that my domain/username + password works for database 2. I am stumped as to why Visual Studio thinks my user is '\azahir' instead of the specified '\axzahir'. Any thoughts on how this can be fixed?
Thank you,
Asif
That's not how integrated security works. When using integrated security, there is no way to specify a specific username or the password. Instead, you get the user authorization for whatever user account runs your program. The entire connection string looks like this, with no specific user information:
Data Source = <SERVER>;Initial Catalog=<DATABASE>;Integrated Security=SSPI;
If you want to specify a username and password, you must use SQL authentication. If you want to access the database as a specific domain account, you use integrated security, but you have to run your app as that user. There is no way to specify Active Directory credentials in a connection string and get that user's database access.
While I'm here, let me show you a better pattern for your database connection. (One that's not crazy vulnerable to sql injection! and will remember to close the connection even if an exception is thrown.)
Assuming a valid connection string:
Private ConnString As String = "connection string here"
Private Sub btSearch_Click(sender As Object, e As EventArgs) Handles btSearch.Click
Dim SQL As String = _
"SELECT firstname, lastname " &
"FROM systemuserbase " &
"WHERE firstname like '%' + #FirstName + '%' AND lastname Like '%' + #LastName + '%';"
Using Conn As New SqlConnection(ConnString), _
cmd As New SqlCommand(SQL, Conn)
'Use actual database column types and lengths here
cmd.Parameters.Add("#FirstName", SqlDbType.NVarChar, 20).Value = TxFirstName.Text
cmd.Parameters.Add("#LastName", SqlDbType.NVarChar, 20).Value = TxLastName.Text
Conn.Open()
Using dir As SqlDataReader = cmd2.ExecuteReader()
dtOutput.DataSource = dir
dir.Close()
End Using
End Using
End Sub
Private Sub btnArgus_Click(sender As Object, e As EventArgs) Handles btnArgus.Click
Dim SQL As String = _
"SELECT userID, Fullname " &
"FROM Users " &
"WHERE FullName like '%' + #FirstName + '%' AND Fullname Like '%' + #Lastname + '%';"
'Note I can use the same variable names.
' These are scoped to the method, not the class.
' Different scope, different variables, even though the names are the same
Using Conn AS New SqlConnection(ConnString), _
cmd As New SqlCommand(SQL, Conn)
'Use actual database column types and lengths here
cmd.Parameters.Add("#FirstName", SqlDbType.NVarChar, 20).Value = TxFirstName.Text
cmd.Parameters.Add("#LastName", SqlDbType.NVarChar, 20).Value = TxLastName.Text
Conn.Open()
Using dir As SqlDataReader = cmd.ExecuteReader()
dtOutput.DataSource = dir
dir.Close()
End Using
End Using
End Sub

System.InvalidOperationException: ExecuteReader requires an open and available connection. The connection's current state is closed

I am having a problem with a customer service module which is in a different solution. the problem I think is in my method of calling or getting a connection
here is my class called DBConnForAccess
Imports System.Data.OleDb
Imports System.Data.Odbc
Public Class DBConnForAccess
Dim Conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim Trans As OleDbTransaction
Public Function DBConnect(ByVal filePath As String, pass As String)
Try
' open Database
'Conn = New SqlConnection("Data Source=" + ServerName + "\" + DBName + ";User ID=" + DBUsername + ";Password=" + DBPassword + ";Initial Catalog= '" + TB + "'")
Conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Jet OLEDB:Database Password=" + pass + ";")
' "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;"
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
' create transaction
Trans = Conn.BeginTransaction
Return "Ok"
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Sub ExecuteSQL(ByVal sql As String, ByVal ParamArray Obj() As Object)
' command Object
Dim CMD As New OleDbCommand(sql, Me.Conn, Me.Trans)
'add the parameters to the sql command
Dim I As Integer
For I = 0 To Obj.Length - 1
CMD.Parameters.AddWithValue("#" & I, Obj(I))
Next
'execute the sql
CMD.ExecuteNonQuery()
End Sub
Public Sub commit()
Me.Trans.Commit()
Me.Trans = Me.Conn.BeginTransaction
End Sub
Public Sub rollback()
Me.Trans.Rollback()
Me.Trans = Me.Conn.BeginTransaction
End Sub
Public Sub CloseDB()
Me.Conn.Close()
Me.Conn.Dispose()
Me.Trans.Dispose()
End Sub
Public Function ReadData(ByVal sql As String, ByVal ParamArray Obj() As Object)
' command Object
Dim CMD As New OleDbCommand(sql, Me.Conn, Me.Trans)
'add the parameters to the sql command
Dim I As Integer
For I = 0 To Obj.Length - 1
CMD.Parameters.AddWithValue("#" & I, Obj(I))
Next
Dim R = CMD.ExecuteReader()
'Do While R.Read
'Loop
Return R
End Function
End Class
Here is the Sub I use to fetch Data:
Dim connection As String = txt_util.readFromTextFile("ConnStr_2.txt", 0) + "Billing.mdb"
'connection string is in a text file with text at line 0 as "C:\BILLSERV\"
Private Sub searchAccnt(ByVal SIN As String)
'clear other fields
Clear("Acct")
Try
AccntDetail.DBConnect("ConcessionairesAccnt")
'Dim RS = AccntDetail.ReadData("Select * From AllAccounts Where SIN=#0", txtSIN.Text.Trim)
Dim RS = AccntDetail.ReadData("Select * From viewCSFAccnt Where SIN=#0", SIN)
RS.Read()
If RS.Hasrows = 0 Then
MsgBox("Accounts not found. Check the SIN you Enter.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Records not found.")
'txtAppNo.Focus()
Exit Sub
Else
'MsgBox("Accounts correct.", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Records found.")
txtZoneNo.Text = RS.Item("Zone").ToString
txtSeq.Text = RS.Item("SeqNo").ToString
txtAccntName.Text = RS.Item("AccountName").ToString
txtAccntAddress.Text = RS.Item("HouseNo").ToString + " " + RS.Item("BLDGName").ToString + " " + RS.Item("Street").ToString + _
" " + RS.Item("BRGY").ToString
txtMeterNo.Text = RS.Item("MeterNo").ToString
txtAccntStatus.Text = varA.AccntStatus(RS.Item("Status").ToString)
'Dim con = AccessAccnt.DBConnect(connection, "")
'If con <> "Ok" Then
' MsgBox("Cannot establish a Connection to the server.", MsgBoxStyle.Critical, "Connection Lost...")
'End If
Dim ZoneNo = "Z" + GetChar(txtZoneNo.Text, 1) + GetChar(txtZoneNo.Text, 2) + "B" + GetChar(txtZoneNo.Text, 3) + GetChar(txtZoneNo.Text, 4)
AccessAccnt.DBConnect(connection, "")
Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=#1", txtSeq.Text)
Acc.Read()
txtLastReading.Text = Acc.Item("LastReading").ToString
Acc.close()
AccessAccnt.CloseDB()
End If
RS.Dispose()
AccntDetail.CloseDB()
dbCounter.DBConnect("ConcessionairesAccnt")
Dim result = dbCounter.ReadData("Select Top 1 CSFNo From CSFMaster WHERE (CSFNo LIKE '%" & ctrDate() & "%') order by CSFNo Desc")
result.read()
If result.hasrows = 0 Then
txtTrackingNo.Text = ctrDate() & "-" & "000001"
Else
txtTrackingNo.Text = counter.CtrLastItemWithChar("ConcessionairesAccnt", "CSFNo", "CSFMaster", "WHERE (CSFNo LIKE '%" & ctrDate() & "%') ORDER BY CSFNo DESC", 5)
End If
dbCounter.CloseDB()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The Error is thrown here:
Dim Acc = AccessAccnt.ReadData("SELECT * FROM " & ZoneNo & " WHERE AcctNo3=#1", txtSeq.Text)
It Says:
System.InvalidOperationException: ExecuteReader requires an open and available connection. The connection's current state is closed.
The Other Parts of the Sub Works fine, The part where I fetch Data on my MSSQL Server database. The Problem lies in the Access data-Fetching Code.
I tried Using the code on another project (just the code where i fetch access data) I worked on other solutions. But I copy and paste my code on any form in this solution I keeps giving the Error.
I thought Maybe I closed the connection somewhere but this is the only instance I used this code in this entire project. (Just to get the last reading record.)
The Database is in the correct place (C:\BILLSERV)
I've Tried searching it here on SE but all I can see where suggestions about maybe forgetting to open the connection. I used this code before and this code works on my other solutions. I just cant seem to have it work here on this particular project. I wonder Why..
I tried running another project using this code and it works fine.
Is there a bug about Access connection on VB.net 2012, I have been using this code (DBConnForAccess Class) for about a year now and this is the first time I have encountered this error. btw I use Access 2003 because this database used to be for an old system created in VB6.
Lastly could this be because the solution came from another computer using a VB.Net Program same as mine. Because We work as a team here. Hope someone with a better knowledge on these systems could help. Thanks in advance.
EDIT
If a connection has been made, there should be a .ldb file in access which should appear. (I tested this on another project and an ldb file appear once a connection has been made, as we all know ldb file contains the data of the user using the db file.) I tried to re-run the system and while I'm using the system no ldb file was created.
Also,I thought Maybe I closed the connection somewhere but this is the only instance I opened a connection in access and which I used the code in this entire project. (Just to get the last reading record.)
So this is NOT a duplicate of “There is already an open DataReader…” Reuse or Dispose DB Connections? Just for clarifications
After a week of debugging and reading articles in the web.
We have found the culprit of the Error.
Seems that the Target CPU Option in Advance compiler Settings was change to AnuCPU.
We noticed this after we checked the other application projects we used.
Changing it Back to x86 solves the connection problem.
I wonder why this affected the connection to the access.
All is working fine now. thank you Plutonix and Steve for all your suggestions we'll be having a change in our codes.

How to handle database connectivity in entire project

I have created a function in a module to connect to database for a windows application
Imports System.Data.SqlClient
Module mod_main
Public Function connectDB() As SqlConnection
Dim Connection As New SqlConnection
Try
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
If IntegratedSecurity Then
Connection.ConnectionString = "Data Source = " & server & ";Initial Catalog = " & db & ";Connection TimeOut =0;Integrated Security=True"
Else
Connection.ConnectionString = "Data Source = " & server & ";Initial Catalog = " & db & ";Connection TimeOut =0;User ID='" & usr & "';Password='" & pwd & "'"
End If
Connection.Open()
Return Connection
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
End Module
I have so many functions and classes that uses plethora of db activities for that I use aforementioned connection function.For exmample:
Public Sub FillComboBox(ByVal ComboBox As C1.Win.C1List.C1Combo, ByVal Query As String, ByVal DisplayMember As String, ByVal ValueMember As String)
Dim SourceDataSet As New DataSet
Dim adapter As New SqlDataAdapter(Query, connectDB) /*Assigning connection here */
adapter.Fill(SourceDataSet)
ComboBox.DataSource = SourceDataSet.Tables(0)
ComboBox.ColumnHeaders = False
ComboBox.ColumnWidth = 0
ComboBox.ExtendRightColumn = True
ComboBox.DisplayMember = DisplayMember
ComboBox.ValueMember = ValueMember
End Sub
Since I'm a beginner in programming my question is , Is this a correct way of handling db connection?
I suggest you to make following changes:
make Connection as public for global accessibility
save connection string in config file and access it from there
need not to close and re open connection open connection only when there is no available connection
In your case all time it creates a new connection when the function is
invoked since you are declaring and initializing connection inside the
function. so checking connection state is meaning less:
so your function looks like following:
public Connection As New SqlConnection
Public Function connectDB() As SqlConnection
Try
Dim Constr As String =""
If IntegratedSecurity Then
Constr = ConfigurationManager.AppSetting("IconnectionString")
Else
Constr = ConfigurationManager.AppSetting("connectionString")
End If
If Connection Is Nothing Then
Connection = New SqlConnection(Constr)
End If
If Connection.State <> ConnectionState.Open Then
Connection.Open()
End If
Return Connection
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function

VB.NET connection to MS Access

I get an error when I am trying to connect to a Microsoft Access DB using VB.NET. I see examples all over the web. My code looks like those examples, however I am getting a build error message stating:
Type 'System.Data.OleDb.OleDbConnection' is not defined.
I have tried adding some kind of import statement for the system.data.oledb... but that does not seem to work. My code is below. It is a basic connection so I am thinking that I am missing some kind of add in, library, or setting. Any and all help would be greatly appreciated.
Public Function TestMain(ByVal args() As Object) As Object
' Connection String to MS Access DB
Dim connectStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\DMalerman\keyword.accdb;" & _
"Persist Security Info=False;"
MsgBox(connectStr)
' Create connection to the db
Using connection As New System.Data.OleDb.OleDbConnection(connectStr)
' Create the SQL Query
Dim readQuery As String = "Select KeywordDriver.ScriptName from KeywordDriver " & _
"where KeywordDriver.Keyword = test"
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery, connection)
'Open the Connection
connection.Open()
' Query the Database
Dim dbReader As System.Data.OleDb.OleDbDataReader = queryCommand.ExecuteReader()
' Loop until there is nothing left to read
While dbReader.Read()
Dim sKeyword As String = ""
sKeyword = dbReader.GetString(0)
MsgBox(sKeyword)
End While
' Close the Reader
dbReader.Close()
End Using
Return Nothing
End Function
did you try
imports System.Data.OleDb
?
if so, did it give you an error?
Please try to modify this line:
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery, connection)
by putting these only:
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery)
queryCommand.Connection = connection
Imports System.Data
Imports System.Data.OleDb
Module Module1
Public str As String
Public con As OleDbConnection
Public cmd As OleDbCommand
Public dtreader As OleDbDataReader
Public dtadapter As OleDbDataAdapter
Public Sub openconn()
str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database2.mdb"
con = New OleDbConnection(str)
Try
con.Open()
Catch ex As Exception
MessageBox.Show("gagal koneksi")
End Try
End Sub
End Module

vb.net writer to excel function working on one pc but not on another

I have a vb.net function which uses oledb to create a spreadsheet, then treat it like a database, creating tables and inserting values. The function takes in a filename and a dataset, and returns the filename if it worked. The function works beautifully on my dev machine, but not other PCs. Below is my function, is there anything wrong with the code? Any suggestions?
EDIT: There are no errors being thrown, the resulting file doesn't contain any data.
Imports System
Imports System.Configuration
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.IO
Imports System.Net.Mail
Imports System.Text
Imports System.Web
Imports Microsoft.Office.Interop
....
Public Shared Function writeToExcelFile(ByVal template As String, ByVal filename As String, ByVal data As DataSet) As String
If File.Exists(filename) Then
File.Delete(filename)
End If
If template <> String.Empty AndAlso filename <> String.Empty Then
File.Copy(template, filename)
End If
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=""Excel 8.0;HDR=Yes;"""
Dim conn As New OleDbConnection(connString)
Try
conn.Open()
Dim cmd As New OleDbCommand()
For Each table As DataTable In data.Tables
Dim tableName As String = table.TableName.Replace(" ", "")
Dim tableCreate As String = "CREATE TABLE [" + tableName + "] ("
Dim sql As String = "INSERT INTO [" + tableName + "$]("
Dim colName As String = String.Empty
For Each col As DataColumn In table.Columns
colName = col.ColumnName.Replace("#", "num")
If colName.Contains(" ") Then
sql += " [" + colName.Replace("'", "") + "],"
Else
sql += " " + colName.Replace("'", "") + ","
End If
tableCreate += " [" + colName + "] varchar(255),"
Next
If tableCreate.EndsWith(",") Then
tableCreate = tableCreate.TrimEnd(New [Char]() {","c})
End If
tableCreate += ") "
cmd = New OleDbCommand(tableCreate, conn)
cmd.ExecuteNonQuery()
If sql.EndsWith(",") Then
sql = sql.TrimEnd(New [Char]() {","c})
End If
sql += ") "
For Each row As DataRow In table.Rows
Dim values As String = " VALUES("
For Each col As DataColumn In table.Columns
Try
values += "'" + cleanString(row(col).ToString()).Substring(0, 250) + "...',"
Catch e As Exception
values += "'" + cleanString(row(col).ToString()) + "',"
End Try
Next
If values.EndsWith(",") Then
values = values.TrimEnd(New [Char]() {","c})
End If
values += ") "
cmd = New OleDbCommand(sql + values, conn)
cmd.ExecuteNonQuery()
Next
Next
conn.Close()
Return filename
Catch e As Exception
Throw New Exception(e.Message)
Return String.Empty
End Try
End Function
Check your system's Regional Settings vs other machines' Regional Settings.
If they differ, try to match them.
Also, when working with Office Automation you should force the thread's culture to en-US.
Set this just before calling writeToExcelFile() (C# syntax):
System.Threading.Thread.CurrentThread.CultureInfo = new System.Globalization.CultureInfo("en-US");
After calling the method, restore the culture (if needed).
Problem is not with this code. Problem is with the dataset that's being passed in.