I've made a VSTO addin for outlook, and it works fine in both release and debug modes on my development machine. Even if I manually delete all the build files and the sqllite database it creates everything from scratch the next time you launch outlook, and carries on as though nothing happened.
When I then install it on the target computer, it simply won't create a sqllite database file. It'll make the directory to put it in, tell me where it's going to put it, and then it just doesn't make the file. It then can't store what it's doing later on, and so just falls over. Unfortunately I copied the command to make the connection from a tutorial, and so don't know what to try!
My code is below:
Public Class ClsSqlLiteDatabase
Public sub new ClsSqlLiteDatabase
Try
Dim sqlite_cmd As SQLiteCommand
Dim dataFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\SBDR Toolbox\"
If (Not System.IO.Directory.Exists(dataFolder)) Then
System.IO.Directory.CreateDirectory(dataFolder)
End If
Debug.WriteLine(dataFolder & "database.sqlite")
' create a new database connection:
conn = New SQLiteConnection("Data Source=" & dataFolder & "database.sqlite;Version=3;")
' open the connection:
conn.Open()
sqlite_cmd = conn.CreateCommand()
' Let the SQLiteCommand object know our SQL-Query:
sqlite_cmd.CommandText = "CREATE TABLE IF NOT EXISTS
[MyBids] (
[pReference] NVARCHAR(2048) NULL PRIMARY KEY,
[sReference] NVARCHAR(2048) NULL,
[AM] NVARCHAR(2048) NULL,
[CC] NVARCHAR(2048) NULL,
[Customer] NVARCHAR(2048) NULL,
[Vendor] NVARCHAR(2048) NULL,
[Distributor] NVARCHAR(2048) NULL,
[NDT] NVARCHAR(2048) NULL)"
' Now lets execute the SQL ;-)
sqlite_cmd.ExecuteNonQuery()
Catch
Debug.WriteLine("Could not initialise SQLLite Database")
End Try
End Sub
Related
Now I know right off the bat that Microsoft access isn't the ideal client for multiple users accessing it but it's the only one I've got right now. I have built a small program as a sort of inventory management system. There are currently three users that will be using it regularly and at the same time. One issue I am running into with this is that sometimes the database will not be accessible and will give an error stating that the file is already in use by "so and so" user. The other issue is that I'm getting a similar error every now and then where it states "The database has been placed in a state by user on machine that prevents it from being opened or locked". I am connecting to the database through an ACE OLEDB connection using the line below
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"
I have also changed some of the settings in the actual access database such as:
Enable all macros
Add the folder the database is in to the trusted locations list
Confirm that the database is set to open in shared mode by default
I don't know if there is something small I've missed or a setting I need to change but as of yet, the problem is still persisting.
Below is an example of how I am using the database. I am using string based SQL commands but am not too familiar with DataSet/DataTable/etc. items, so I may be doing something incorrectly.
'close connection from any previous session
con.Close()
'clear dataset so as not to append data
ds.Clear()
'Select SQL query that selects ALL records from a table
Dim str As String = "SELECT * FROM " & "[" & table & "]" & ""
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"
'use try catch statement to open the connection
Try
con.Open()
Catch ex As Exception
MsgBox(Convert.ToString(ex))
End Try
'use try catch statement to add a table (dt) to the dataset (ds) in order to store values
Try
ds.Tables.Add(dt)
Catch ex As Exception
End Try
'create new dataadapter object using the sql string from above and the connection created above
da = New OleDbDataAdapter(str, con)
'create new command builder in order to excecute the SELECT SQL statement using the dataadapter created (da)
'specify prefix and suffix for cb
Dim cb = New OleDbCommandBuilder(da) With {
.QuotePrefix = "[",
.QuoteSuffix = "]"
}
'use try catch statement to fill the datatable (dt) using the dataadapter (da)
Try
da.Fill(dt)
Catch ex As Exception
MsgBox(Convert.ToString(ex))
End Try
'set the datasource of the datagridview to the datatable
dgv.DataSource = dt.DefaultView
'close the connection to the database
con.Close()
Go to your Back-End Access DB file. File > Options > Client Settings. For your Use Case No Locks should be fine, but Edited record setting will work as well if you need it
but its [sic] the only one I've got right now
Actually, it's not.
Have a look at SQL Server Compact. It's free, it's small and it handles multiple users with aplomb.
You can add all the references you need using NuGet.
I've added an access db to my project as a datasource. So I get the automatically generated tableadapters class and therefore, access to the table adapter instance which includes the connection string. I'm using this to open a connection to my db so I can first, delete some records, and then replace them with new records.
The queries seem to work because the .executenonquery does return the rows affected. I even tried a delete * command to be sure. But, when I open the database everything is the same.
I had some ideas as to why. I thought the connection string returned by the tableadapter might be goofy because it contains a generic pointer to the project's data directory.
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DupeMDB.mdb;Persist Security Info=True
I also thought maybe I had a problem with the Build Action or the Copy to Output Directory. I really don't understand the mechanics behind these two things. I think maybe the copy to output directory thing might be the culprit.
Here's me goal. I want to deploy this project to my secretary so she can use the program to deal with a duplicate record list etc. The data has to go with the program. I want to package this .mdf file with the deployment and get it back from her when she's done with it. I am so close to the end here (writing back to the table). Does anyone know why the table won't update?
Dim Connector As DupeTblTableAdapter = New DupeTblTableAdapter
Dim Conn As New System.Data.OleDb.OleDbConnection
Conn = Connector.Connection
Conn.ConnectionString = Connector.Connection.ConnectionString
MsgBox(Conn.ConnectionString)
Dim Comm As System.Data.OleDb.OleDbCommand
Conn.Open()
For Each DR In DeleteRecords
Comm = New System.Data.OleDb.OleDbCommand($"DELETE from DupeTbl where DupeTbl.CUST_NO={DR.ToString}", Conn) '
Dim aff As Integer = Comm.ExecuteNonQuery
'MsgBox(aff)
Comm = Nothing
Next
For Each RR In ReplaceRecords
Comm = New System.Data.OleDb.OleDbCommand($"INSERT INTO DupeTbl ( CUST_NO, PREDIR, POSTDIR, SUFFIX, CUSTSIZE, AddFlag, IgnoreRecord ) VALUES ({RR.Cust_No}, '{RR.PreDir}', '{RR.PostDir}', '{RR.Suffix}', {RR.Size}, {RR.AddFlag}, {RR.Ignore});", Conn)
Comm.ExecuteNonQuery()
Comm = Nothing
Next
Conn.Close()
The issue in such cases is usually the working database being overwritten on each build. When adding a local data file to your project, it is added as a source file in the project folder. By default, the Copy to Output Directory property is set to Copy Always. That means that every time you build your project, which will happen each time you make a code change and run the project by default, the source file will be copied over the top of the working database in the output folder, thus wiping out any changes you made while debugging. To prevent this, change that property to Copy if Newer, which means that the working database will only be overwritten if you make a change to the source database, e.g. modify the schema.
Dim Connector As DupeTblTableAdapter = New DupeTblTableAdapter
Dim Conn As New System.Data.OleDb.OleDbConnection
Conn = Connector.Connection
Conn.ConnectionString = Connector.Connection.ConnectionString
MsgBox(Conn.ConnectionString)
Dim Comm As System.Data.OleDb.OleDbCommand
Conn.Open()
For Each UR In UpdateRecords
Comm = New System.Data.OleDb.OleDbCommand($"UPDATE DupeTbl SET CUST_NO = <NewValue>, PREDIR = <NewValue, POSTDIR = <NewValue> etc. where DupeTbl.CUST_NO={DR.ToString}", Conn) '
Dim aff As Integer = Comm.ExecuteNonQuery
'MsgBox(aff)
Comm = Nothing
Next
Conn.Close()
I'm trying to read from some DBF files that use NTX files for indexing within VB.NET. Currently, I'm having to read directly from the DBF files using OLEDB, which is ridiculously slow due to dbase's flat file method of data storage. So, I'm wondering if someone could tell me how to access the DBF files through their NTX index files within VB.NET.
If I need to download a third party library I'm okay with that, But I don't have money to pay for a third party library if it costs money. It would need to be free.
This is what I'm currently using to access the DBF Files.
Private Shared ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & My.Settings.DataPath & ";Extended Properties=dBase IV"
Public Shared dBaseConnection As New System.Data.OleDb.OleDbConnection(ConnectionString)
Dim dBaseCommand As New System.Data.OleDb.OleDbCommand("SELECT * FROM `PAGES.NTX` WHERE `PAGE_NUM` BETWEEN 241 AND 270", dBaseConnection)
Dim dBaseDataReader As System.Data.OleDb.OleDbDataReader = dBaseCommand.ExecuteReader(CommandBehavior.SequentialAccess)
This however still reads directly from the DBF file and ignores the NTX indexing. Any help?
Note: I cannot "choose" to use SQL for this project as the DataBases are ones created and maintained by another application (One of considerable age). I need only access them for the data stored within.
Download Advantage .NET Data Provider
This is the only example I could find. Since I do not have the files to test with this is only an example:
'Set the TypeTable to NTX
Dim conn As New AdsConnection("data source=c:\data;" + "ServerType=remote|local; TableType=NTX")
Dim cmd As AdsCommand
Dim reader As AdsDataReader
Dim iField As Integer
Try
' make the connection to the server
conn.Open()
' create a command object
cmd = conn.CreateCommand()
' specify a simple SELECT statement
cmd.CommandText = "select * from departments"
' execute the statement and create a reader
reader = cmd.ExecuteReader()
' dump the results of the query to the console
While reader.Read()
For iField = 0 To reader.FieldCount - 1
Console.Write(reader.GetValue(iField) + " ")
Next
Console.WriteLine()
End While
conn.Close()
Catch e As AdsException
' print the exception message
Console.WriteLine(e.Message)
End Try
I have an access application (VBA) ( access 2003 ) , which generates 4 different text file based on its database at specific path on pressing of 4 respective different buttons.
But this is something manual , which i do everyday for the file generation.
Im in need of its automation.For example my file should get automatically generate at any specific time.
One of the button's event procedure is menitoned below :
I tried doing with help of VB script , but this is giving error .
"Provider cannot be found.May not be properly installed "
Set objAccess = CreateObject("Access.Application")
Set conn = CreateObject("ADODB.Connection")
strConnect = "Provider=Microsoft.JETs.OLEDB.12.0;
Data Source=E:\Project\test.mdb"
conn.Open strConnect
test()
function test()
objAccess.DoCmd.Hourglass True
objAccess.DoCmd.SetWarnings False
objAccess.DoCmd.RunSQL ("INSERT INTO Table1 ( name, FileName, [DateTime] ) SELECT Environ(""UserName"") AS name, ""test.mdb Generate ABCD File"" AS FileName, Format(Now(),""yyyyMMddhhmmss"") AS [DateTime];")
objAccess.DoCmd.OpenQuery ("qry_ABCD")
objAccess.DoCmd.TransferText acExportDelim, "qry_ABCD_Formatted Export Specification", "qry_ABCD_Formatted", "E:\Ouputs\" & Format(Now(), "yyyymmdd") & ".txt", False
objAccess.DoCmd.SetWarnings True
objAccess.DoCmd.Hourglass False
End function
I dnt know how to resolve this issue. Or is there any other better way to resolve this.
There is no need to setup or create some connection string in your script. Once you opened Access, then you have use of all tables in that application. And in fact in your example you create a conneciton object, but it not really required.
So, lets assume your VBA code to run is this:
Sub MyExport()
Dim strSQL As String
strSQL = "INSERT INTO Table1 ( name, FileName, [DateTime] ) " & _
"SELECT Environ(""UserName"") AS name, ""test.mdb Generate ABCD File"" AS FileName, " & _
"Format(Now(),""yyyyMMddhhmmss"") AS [DateTime];"
CurrentDb.Execute strSQL
DoCmd.TransferText acExportDelim, "qry_ABCD_Formatted Export Specification", _
"qry_ABCD_Formatted", _
"E:\Ouputs\" & Format(Now(), "yyyymmdd") & ".txt", _
False
End Sub
The above code is assumed to be saved as a sub (not a function) in a STANDARD MS Access VBA code module.
Now, your VBS scrip can call the above code like this:
dim accessApp
set accessApp = createObject("Access.Application")
accessApp.OpenCurrentDataBase("C:\some path name\someMdb.accDB")
accessApp.Run "MyExport"
accessApp.Quit
So it now a simple matter to run the above VBS script. And such a script should also just run fine via the windows task scheduler. As above shows there is LITTLE need to put the SQL and code in the VBS script. You BEST get the sub working in VBA and MAKE SURE it works. Test it many times, and THEN and ONLY then do you create the VBS cript to call that sub. So FIRST get the routine working, and get it working WITHOTU any prompts etc. You can call and test the VBA sub by placing your cursor in the VBA editor in that routine, and then hit F5 to run the sub. Once you get it working the way you want, then you use the above second VBS (not VBA script to call + run that working sub that you are NOW 100% SURE it works and runs correctly)
Goal
I am attempting to do the following from Microsoft Access:
Insert into a SQL 2008 database a varbinary(max) field
Read binary file (Excel/Word)
Insert into SQL database
This seems like it would be straightforward.
Background
It would appear ADODB.Stream is the best way to do this. I am not convinced this is best. Filestream is disabled on my SQL server environment.
I have written code which will accomplish what I want in VBA for all files which are not opened. I do not want to require users to close the files prior to reading them with VBA.
This is my current code:
Dim mStream As ADODB.Stream
Set mStream = New ADODB.Stream
Dim fName As String
fName = "C:\tmp.docx"
mStream.Type = adTypeBinary
mStream.Open
mStream.LoadFromFile fName 'this fails if the file is open
Dim mCmd As ADODB.Command
Set mCmd = New ADODB.Command
With mCmd
' define query
.CommandText = "INSERT INTO testingvarbinary (testVarBinary) " & _
"VALUES (?)"
.CommandType = adCmdText
' add parameter
.Parameters.Append .CreateParameter("#P1", adVarBinary, adParamInput, mStream.Size, mStream.Read)
End With
mCmd.ActiveConnection = CurrentProject.Connection
mCmd.Execute
I've thought about trying to simply copy the file to C:\tmp or something and read that one, but it just seems like there should be a way to do this.
Question
How can I modify the above code to work for files which a user has opened? In this thread it seems there is a way to use the .Open command to do this, but I've been unsuccessful in even getting the .Open to return ANYTHING let alone the entire file. I've not found a single example using Open rather than LoadFromFile for an actual file on my computer.
If there is a different way in VBA than using ADODB.Stream that would be great too, I'm not tied to using it at all.