Compacting Database Error Message - vb.net

When I am trying to compact my Access 2010 database (no password), I am getting the error message Class Not Registered I am using Visual Studio 2010, and I have not idea what this problem is. Here Is the code i'm using:
Private Sub Compactdb()
Dim JRO As JRO.JetEngine
JRO = New JRO.JetEngine
'The first source is the original, the second is the compacted database under an other name.
JRO.CompactDatabase("Provider=Microsoft.Jet.OLEDB.5.0;Data Source=C:\Forte\Ex.mdb; Jet OLEDB:Engine Type=5", "Provider=Microsoft.Jet.OLEDB.5.0;Data Source=C:\Forte\Temp.mdb; JetOLEDB:Engine Type=5")
'Original (not compacted database is deleted)
System.IO.File.Delete("C:\Forte\Ex.mdb")
'Compacted database is renamed to the original databas's neme.
Rename("C:\Forte\Temp.mdb", "C:\Forte\Ex.mdb")
'User notification
MsgBox("The database was compacted successfully")
End Sub
If I change the Jet.OLEDB.5.0 to 4.0 I get a different error message of Unrecognized databse format

Try
Dim ParentCNN As String
Dim CloneCNN As String
Dim JrO As New JRO.JetEngine
ParentCNN = "PROVIDER = MICROSOFT.ACE.OLEDB.12.0;DATA SOURCE = C:\Forte\Fortedb.accdb;JET OLEDB:DATABASE PASSWORD = 21061975;"
CloneCNN = "PROVIDER = MICROSOFT.ACE.OLEDB.12.0;DATA SOURCE = C:\Forte\Temp.accdb;JET OLEDB:DATABASE PASSWORD = 21061975;Jet OLEDB:Engine Type=5"
'If cnnMDE.State = ConnectionState.Open Then
' cnnMDE.Close()
'End If
JrO.CompactDatabase(ParentCNN, CloneCNN)
If System.IO.File.Exists("C:\Forte\Temp.accdb") Then
System.IO.File.Delete("C:\Forte\Fortedb.accdb")
Rename("C:\Forte\Temp.accdb", "C:\Forte\Fortedb.accdb")
End If
Catch ex As Exception
MainTextBox.AppendText(Environment.NewLine & "Database Compression Failure :" & vbCr & ex.Message)
End Try

Related

VB NET AND SQLITE : file is encrypted or is not a database

I am trying to create an apps with VB.NET and SQLite, i have create the database and table with SQLiteManager and I HAVE SET ENCRYPTION TO THE DATABASE and THE PASSWORD IS SAME AS WHAT IN THE CONNECTION STRING.
However when i am trying to insert sample record to table, it gave an error file is encrypted or is not a database
This is the sample of the code that produce the error.
Using ConLite = OpenConLite()
Using LiteCmd As New SQLiteCommand
Dim TglWaktuSekarang As String = CurrentDateTime()
LiteCmd.CommandText = "INSERT INTO finger_stamp(emp_id,emp_name,date_time) VALUES('1','DIANA','" & TglWaktuSekarang & "')"
LiteCmd.CommandType = CommandType.Text
LiteCmd.Connection = ConLite
LiteCmd.ExecuteNonQuery()
End Using
End Using
and this is my connection code
Public Function OpenConLite() As SQLiteConnection
Dim SQLiteCon As SQLiteConnection
Try
Dim ConLiteString As String = "Data Source=C:\SQLiteDB\attendance.sqlite;Version=3;Password=hahaha;"
SQLiteCon = New SQLiteConnection(ConLiteString) ' Connection DataSource
SQLiteCon.Open()
OpenConLite = SQLiteCon
Catch ex As Exception
OpenConLite = Nothing
MsgBox("Failed to connect to Database", MsgBoxStyle.Information, "Warning")
End Try
End Function

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.

Document Upload to SharePoint with VB.NET

At my company we have an initiative that allows users to submit "Winning Ideas". There is a form to fill out, and the user can upload documents on the form. The ideas are voted on by other employees, reviewed by a committee, and the user has the ability to win cash prizes and have their idea implemented in the company.
I created a custom webpart using ASP.NET that allows users to insert a row into a SQL table, and add documents to a SharePoint document list. The list of documents they upload is added to a field in the SQL table, and displayed as hyperlinks on the .aspx page.
Here are some of the issues I have seen with the document upload:
- Document is not uploaded at all.
- Document is uploaded, but not checked in.
- Document is uploaded and checked in, but not linked to a record (the field did not update in SQL).
- If adding multiple documents, both documents are uploaded but the content of the first document is repeated for all documents.
- Multiple entries are created with the Insert statement.
I can't figure out if this is a problem with my SQL or my VB. Is there a better way I should be doing this? Any help would be appreciated.
My current environment is as such:
- SharePoint 2013
- SQL Server 2012
- Microsoft Visual Studio Professional 2013
Partial Public Class WinningIdeasFormUserControl
Inherits UserControl
Public conn As SqlConnection
Public strDatabase As String
Public MyUserInfo As SPUser
Public strFiles As String
Public IdeaId As String
Public uploads As HttpFileCollection
Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
'reference to file collection that was sent by the browser request'
uploads = HttpContext.Current.Request.Files
Try
conn = New SqlConnection(strDatabase)
Dim cmd As SqlCommand = New SqlCommand()
strFiles = ""
'SQL command to insert results into the database'
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO [WinningIdeas] (Title, Idea, Submitter, SPUserID) OUTPUT INSERTED.ID VALUES (#Title, #Idea, #Submitter, '" & MyUserInfo.ID & "')"
cmd.Parameters.AddWithValue("#Title", txtTitle.Text)
cmd.Parameters.AddWithValue("#Idea", txtIdea.InnerText)
cmd.Parameters.AddWithValue("#Submitter", MyUserInfo.Name)
'confirms that the database has been updated'
cmd.Connection.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
reader.Read()
'set IdeaId to the output of the record that was just added (ID it was assigned in database)'
IdeaId = reader(0).ToString
cmd.Connection.Close()
cmd.Connection = Nothing
If uploads.Count > 1 Then
Try
'if the user uploaded documents, make sure we add them'
uploadDocuments()
Catch ex As Exception
Span1.InnerHtml = "An error has occurred while trying to upload your document(s). Please contact WinnDESK#winnco.com for more information. " & ex.Message & "."
End Try
ElseIf (reader.RecordsAffected = 1) Then 'if a record has been successfully created'
SendEmail()
Response.Redirect("/Pages/Submitted.aspx?IdeaId=" & IdeaId)
End If
Catch ex As Exception
'change the <span> to show the error message'
Span1.InnerHtml = ex.Message
End Try
End Sub
Public Sub uploadDocuments()
'upload files'
For i As Integer = 0 To (uploads.Count - 1)
Dim fileSize As Int64
fileSize = uploads(i).ContentLength
'get the file name from whichever file we are currently saving'
Dim filName As String = System.IO.Path.GetFileName(uploads(i).FileName)
'TODO: Size exception is bringing the user to an exception page. catch as my exception'
'make sure there are no empty files, make sure file is less than 50MB'
If (fileSize > 0 And fileSize < 52428800) Then
Dim spfile As SPFile = SPContext.Current.Web.Files.Add("/Documents/User%20Uploads/" + IdeaId + "_" + filName, FileField.PostedFile.InputStream)
spfile.CheckIn("Checked in by " & MyUserInfo.Name & " for Idea " & IdeaId, SPCheckinType.MajorCheckIn)
spfile.Publish("Published by " & MyUserInfo.Name & " for Idea " & IdeaId)
'separate files with a ";" in the database'
strFiles = strFiles + IdeaId + "_" + filName + ";"
Else
Throw New Exception("Your file, " & filName & ", was not uploaded correctly due to its size.")
End If
Next
Try
conn = New SqlConnection(strDatabase)
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "UPDATE WinningIdeas SET Documents = #Documents WHERE ID = " & IdeaId
cmd.Parameters.AddWithValue("#Documents", strFiles)
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
cmd.Connection = Nothing
Response.Redirect("/Pages/Submitted.aspx?IdeaId=" & IdeaId)
Catch ex As Exception
'change the <span> to show the error message'
Span1.InnerHtml = ex.Message
End Try
End Sub

Error connecting to Oracle database (ORA-12560)

I'm hitting the error mentioned in the Title when attempting to connect to the database in the VB.net application I'm developing. I know it's not the listener or any service issue, as I'm able to connect to the same database, with the same credentials in a different application I developed (I ran that application after failing to connect with the one I'm developing, so it's not the Windows Event log).
Both use an Oracle.DataAccess.Client.OracleConnection to reference an existing ODBC connection. The connections are created and opened in slightly different ways so I figure it's something in my VB code that's causing the issue, but I can't for the life of me think of what it might be.
The non-functional code:
Public Function EstablishCon(ByVal odbc As String,
ByVal uname As String,
ByVal pass As String) As Oracle.DataAccess.Client.OracleConnection
'
Dim constr As String
Dim scon As Oracle.DataAccess.Client.OracleConnection = Nothing
Try
constr = "Data Source=" & odbc & ";User Id=" & uname & ";Password=" & pass & ";"
scon = New Oracle.DataAccess.Client.OracleConnection(constr)
scon.Open()
Catch ex As Exception
MsgBox("Encountered an error while creating the Oracle connection string and opening the connection. This will cause the application to be unable to access any data." _
& " As such the application will close following the closure of this error message." & Chr(10) & Chr(10) & "Error Details: " & ex.Message, vbOKOnly, _
"Critical Error: Failed to the Oracle Database")
scon.ConnectionString = Nothing
End Try
Return scon
End Function
Whereas my working code looks like:
Private Sub MainWin_Shown(sender As Object, e As EventArgs) Handles Me.Shown
'
'Dim scmd As New SqlClient.SqlCommand
Dim QTxt As String = ""
Dim ConStr As String = "Data Source=existing ODBC connection name;User Id=user_name;Password=pass;"
Dim scon As New Oracle.DataAccess.Client.OracleConnection(ConStr)
Dim d As New DataStore
Dim scmd As New Oracle.DataAccess.Client.OracleCommand
Dim odr As Oracle.DataAccess.Client.OracleDataReader
'Setup the datatable in d
Try
d.DT.Columns.Add("App_Type")
d.DT.Columns("App_Type").DataType = GetType(String)
d.DT.Columns.Add("CPU_Seconds")
d.DT.Columns("CPU_Seconds").DataType = GetType(Double)
'd.DT.Columns.Add("Pct_Of_CPU")
'd.DT.Columns("Pct_Of_CPU").DataType = GetType(Double)
d.DT.Columns.Add("RunDate")
d.DT.Columns("RunDate").DataType = GetType(Date)
Catch ex As Exception
Me.Errors.Text = "Encountered an error setting up the data table that will receive the query data. Details: " & ex.Message
d = Nothing
scon = Nothing
scmd = Nothing
ConStr = Nothing
QTxt = Nothing
odr = Nothing
Exit Sub
End Try
Me.Status.Text = Now() & " - Building the SQL executor"
Me.Refresh()
'Build the query executor
Try
scmd.CommandType = CommandType.Text
scmd.Connection = scon
'Capture the query text
QTxt = 'Some text that makes a valid query
scmd.CommandText = QTxt
Catch ex As Exception
Me.Errors.Text = "An error occurred while building the SQL Executor. Details: " & ex.Message & Chr(10) & Chr(10) & Me.Errors.Text
d = Nothing
scon = Nothing
scmd = Nothing
ConStr = Nothing
QTxt = Nothing
odr = Nothing
Exit Sub
End Try
Me.ProgBar.Step = 5
Me.ProgBar.PerformStep()
Me.Status.Text = Now() & " - Connecting to the database" & Chr(10) & Me.Status.Text
Me.Refresh()
Try
'Open the connection
scon.Open()
Catch ex As Exception
Me.Errors.Text = "An error occurred while opening the SQL connection. Details: " & ex.Message & Chr(10) & Chr(10) & Me.Errors.Text
d = Nothing
scon.Close()
scon = Nothing
scmd = Nothing
ConStr = Nothing
QTxt = Nothing
odr = Nothing
Exit Sub
End Try
'Some more stuff that's not relevant
End Sub
Sorry for the messy formatting, I spent 15 minutes trying to keep the two blocks of code separate, but StackOverflow just wasn't having it.
So the only real difference between the two is that one filled in the connection string when declaring the Connection variable, and the other does so later and in a separate function. The function aspect doesn't appear to factor as the error is thrown and caught inside the function. I
So the problem was how I was invoking the form that calls for the function. I had use .Show rather than .ShowDialog.
This resulted in the form variables (which hold the values that get passed in as odbc, uname, & pass) being cleared prior to hitting the Shown event (where the connection function is invoked).

OleDB Exception: Could not find installable ISAM

Dim con As New OleDb.OleDbConnection
Sub connecttodatabase(ByVal fileselected As String)
Dim databasepassword
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = " & fileselected
Try
con.Open()
Catch e As OleDb.OleDbException
If e.Message = "Not a valid password." Then
Console.WriteLine("Database has a password. Please enter password to continue.")
databasepassword = Console.ReadLine()
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = " & fileselected & ";JetOLEDB:Database Password=" & databasepassword & ";"
con.Open()
End If
errorid = 1
Finally
End Try
End Sub
The error I am encountering occurs at the second con.Open() when I try to connect to a .mdb database file which I created in access, the function correctly tells me I have a password, but then once I enter my password I get the error defined in the title, and I have no idea why. Any help would be greatly appreciated.
Try this instead:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;User Id=admin;Password=YOURPASS;
Also, what exception are you getting from the first call to open the db? Maybe it's same problem: the ISAM isn't present. Try reinstalling MDAC:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=78cac895-efc2-4f8e-a9e0-3a1afbd5922e