Putting column names from database table into a list - database

I am trying to put columns names from a table inside a Microsoft Access database inside a list variable. I have done this so far but the line where I am trying to add it to the topic variable does not work and is coming up with the error
predefined type ‘valuetuple(of,,,)’ is not defined or imported.
The code is:
Dim topic = topic()
Dim filtervalues = {Nothing, Nothing, "Results", Nothing}
Dim counter As Integer = 0
Using con = _
New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Database.mdb")
Dim columns = con.GetSchema("columns", filtervalues)
For Each row As DataRow In columns.Rows
topic(counter) = ("{0,-20}{1}", row("column_name"), row("data_type"))
counter = +1
Next
End Using

According to the documentation on Value Tupels you must get the NuGet package System.ValueTuple, if you are working with Framework version prior to 4.7:
Important
Tuple support requires the ValueTuple type. If the .NET Framework 4.7 is not installed, you must add the NuGet package System.ValueTuple, which is available on the NuGet Gallery. Without this package, you may get a compilation error similar to, "Predefined type 'ValueTuple(Of,,,)' is not defined or imported."
In Visual Studio 2017 right click on your solution and select "Manage NuGet Packages for Solution...". In the search-box enter "valuetuple". Select "System.ValueTuple" and on the right click the check boxes of the projects where you want to install the package and click Install.
See: NuGet Package Manager UI
Also, you must declare the list variable as
Dim topic = New List(Of (String, String, String))
and add new elements with
topic.Add(("{0,-20}{1}", row("column_name"), row("data_type")))
The counter is not needed anymore.
Alternatively, you could use a list of strings and format the string with string interpolation
Dim topic = New List(Of String)
Dim filtervalues = {Nothing, Nothing, "Results", Nothing}
Using con =
New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Database.mdb")
Dim columns = con.GetSchema("columns", filtervalues)
For Each row As DataRow In columns.Rows
topic.Add($"{row("column_name"),-20}{row("data_type")}")
Next
End Using

Judging from the "{0,-20}{1}", you forgot the String.Format in
topic(counter) = String.Format("{0,-20}{1}", row("column_name"), row("data_type"))
and did not intend to use a tuple.

Related

Why is my vb code not updating the ms access database (only cached temporarly)

I am doing a small system using Ms. Access (the database has more than 10 tables ) connecting to visual studio. I made a public class for opening the connection to the database so I can use it in every form. Everything is working and I can get the data from the database But any inserting or deleting data in forms, the database in ms access not getting the update. I can see the new records in forms but nothing in the database.
Imports System.Data.OleDb
Public Class dbconnectClass1
'create db connection
Private DBcon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=dental_clinic.accdb;")
'prepare db command
Private dbcmd As OleDbCommand
' db data
Public DBDA As OleDbDataAdapter
Public DBDT As DataTable
'query parameters
Public params As New List(Of OleDbParameter)
'query statics
Public recordcount As Integer
Public Exception As String
Public Sub ExecQuery(query As String)
'reset query status
recordcount = 0
Exception = ""
Try
'open connection
DBcon.Open()
'create db command
dbcmd = New OleDbCommand(query, DBcon)
'load params into dbcommand
params.ForEach(Sub(p) dbcmd.Parameters.Add(p))
'clear params list
params.Clear()
'excute command and fill dataset
DBDT = New DataTable
DBDA = New OleDbDataAdapter(dbcmd)
recordcount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
'close the database connection
If DBcon.State = ConnectionState.Open Then DBcon.Close()
End Sub
'include query and command parameters
Public Sub addparam(name As String, value As Object)
Dim newparam As New OleDbParameter(name, value)
params.Add(newparam)
End Sub
End Class
This my code inside the forms:
Public Class NewExpense
Private access As New dbconnectClass1
' a varuble having the appointment Id to connect between 2 forms
Private appointmentNo As Integer
Private Function NoError(Optional report As Boolean = False) As Boolean
If Not String.IsNullOrEmpty(access.Exception) Then
If report = True Then MsgBox(access.Exception)
Return False
Else
Return True
End If
End Function
Private Sub Savebuttum_Click(sender As Object, e As EventArgs) Handles
Savebuttum.Click
Dim oDate As DateTime = Convert.ToDateTime(DateTimePicker1.Value)
access.addparam("#expensenme", expensenmtXT.Text)
access.addparam("#expensedetail", ExpenseDetailTXT.Text)
access.addparam("#expenseamount", ExpenseAmountTXT.Text)
access.addparam("#expensedate", oDate)
access.addparam("#expensepaidTo", paidtoTXT.Text)
access.ExecQuery("INSERT INTO Expense (Expenses_name, expense_details,
expenses_amount, ExpenseDate_Paid, ExpensePaid_To) Values (#expensenme,
#expensedetail, #expenseamount, #expensedate, #expensepaidTo);")
'report on errors
If Not String.IsNullOrEmpty(access.Exception) Then
MsgBox(access.Exception) : Exit Sub
'success
access.DBDA.Update(access.DBDT)
MsgBox("Expense Has been Added Successfully")
End Sub
End Class
Hum, you have this:
params.ForEach(Sub(p) dbcmd.Parameters.Add(p))
Great, we add the parmaters - looks good to go!!!
then, next line CLEARS all the work above!!! (the parameters are removed!!!!)
'clear params list
params.Clear()
Next up? Many will build a connection object, then a reader, and then a adaptor. But you ONLY need a data adaptor if you going to update a data table. if you just going to execute a command, then you don't need the data table, and you don't need a adaptor FOR that table. Adaptor = ability to modify a existing datatable (or dataset).
You are MUCH better to use the command object.
Why?
Because the command object has a connection object (don't need a separate one)
Because the command object has a data reader for you (no need for a whole data adaptor to JUST fill a table. And remember, you don't need a whole data adaptor UNLESS you are going to send/update a data table back to the database.
And because the command object has the command text, then you don't even need a variable for that!!!
And because all objects are in "one object", then really all you need is something to handy get you the connection.
So, for your insert example, we really don't gain by having that object, do we?
Ok, so here is your insert code without using those extra objects:
so in the following, I declare ONE variable, - the sql command object.
And do the insert
And as FYI? Your save button is not a save - but a insert button - every time you hit it, you will insert a new row. Lets deal with that issue in a bit.
So, here is our code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using cmdSQL As New OleDbCommand("INSERT INTO Expense
(Expenses_name, expense_details,expenses_amount, ExpenseDate_Paid, ExpensePaid_To)
Values (#expensenme,#expensedetail, #expenseamount, #expensedate, #expensepaidTo)",
New OleDbConnection(My.Settings.TESTOLEDB))
With cmdSQL.Parameters
.Add("#expensenme", OleDbType.WChar).Value = expensenmtXT.Text
.Add("#expensedetail", OleDbType.WChar).Value = ExpenseDetailTXT.Text
.Add("#expenseamount", OleDbType.Currency).Value = ExpenseAmountTXT.Text
.Add("#expensedate", OleDbType.DBDate).Value = DateTimePicker1.Value
.Add("#expensepaidTo", OleDbType.WChar).Value = paidtoTXT.Text
End With
cmdSQL.Connection.Open()
cmdSQL.ExecuteNonQuery()
End Using
So things in above:
We have strong data typing and converstion.
Because of this, note how I did NOT have to create a separate date/time variable here.
Note the SAME for "money" or so called currency conversion - again strong data type by using parameters this way.
And is this a date only, or a date+ time value? If it is date, then
.Add("#expensedate", OleDbType.DBDate).Value = DateTimePicker1.Value
If it was/is a date + time, then this:
.Add("#expensedate", OleDbType.DBTimeStamp).Value = DateTimePicker1.Value
So, notice how all your object stuff REALLY did not help one bit, and in fact you did not really save code, and above actually had LESS variables defined to do the whole job.
Now, back to the insert issue/problem. (you save is doing a insert). But what about editing existing records?
So, I would suggest you work out the problem this way:
You create/get/have/assume a data row for the form.
The form takes the data row, fills the controls. You edit, and when you hit save, the data row is sent back to the datbase. So, once this works, then to add? Well, the add code will CREATE a new data row, save to database and THEN you send that new data row to the above eixsting form that can edit a data row, and can save a data row. So the form now is able to deal with both issues (adding vs editing existing). If the user dont' want the row, then you offer a delete button.
And REALLY nice is a data row means you don't deal with SQL, and don't deal with parmaters!!
So the code (desing pattern) I use is thus this:
dim da as oledbDataAdaptor
dim myTable as DataTable = MyRstEdit("SELECT * from tblHotels WHERE ID = " & lngID,da)
dim MyDataRow as DataRow = myTable.Rows(0)
' code to fill controls
txtHotelName.Text = MyDataRow("HotelName")
txtCity.Text = MyDataRow("City")
' etc. etc. etc.
Now to save? Well I put the values back into that DataRow like this:
MyDataRow("HotelName") = txtHotelName.Text
MyDataRow("City") = txtCity.Text
MyDateRow("BookingDate") = txtTimePick1.Value
da.Update(MyTable)
Notice how I don't have parameters, and even strong data type checking occurs for say the above Date/Time booking date column.
And the above is nice, since I don't have to deal with ANY parmaters to udpate a row of data.
The MyRstEdit routine looks like this and returns byREf a "da" (data adaptor).
Public Function MyrstEdit(strSQL As String, Optional strCon As String = "", Optional ByRef oReader As SqlDataAdapter = Nothing) As DataTable
' Myrstc.Rows(0)
' this also allows one to pass custom connection string - if not passed, then default
' same as MyRst, but allows one to "edit" the reocrdset, and add to reocrdset and then commit the update.
If strCon = "" Then
strCon = GetConstr()
End If
Dim mycon As New SqlConnection(strCon)
oReader = New SqlDataAdapter(strSQL, mycon)
Dim rstData As New DataTable
Dim cmdBuilder = New SqlCommandBuilder(oReader)
Try
oReader.Fill(rstData)
oReader.AcceptChangesDuringUpdate = True
Catch
End Try
Return rstData
End Function
So, now in vb.net, I actually find it is LESS code then even writing + using recordsets in MS-Access VBA code.
However, BEFORE you go down ANY of the above road?
Have you considered using the vb.net data binding features. Data-binding in vb.net means that you do NOT write ANY of the above code. it means that vb.net will do all of the dirty work, and write and setup ALL OF the code for you to edit data on a form. The end result is you don't write any code to update a table.
You do have to use + create a "data set". Once done, then you just drag controls onto the form, and you even get this. So you just drop in a dataset, table adaptor, Binding navagator, and you get this:
Note now the tool bar at the top (and you can place it on teh bottom if you wish). So you get this:
So that WHOLE form was created without having to write ONE line of code. And you can see we have navigation, edits and saves and even the ability to add. So, you can build up a editing form - and it thus becomes similar to say working in MS-Access and ZERO lines of code is required to build the above form.
However, if you ARE going to roll your own code? Then use a data row. That way you can shuffle data to/from the table, and NOT have to use parmaters and SQL update and insert statements - but ONLY have nice clean code in which you shove, or get values from that data row. .net will "write" all the update stuff for you.

Exception with sqlite database "no such table"

First of all I´m developing a database with autosuggest box. I´ve created a database with DB Browser and imported data. I was reading documentation in C# how connect database and retrieve data. The issue is show up an exception error:
enter image description here
I´ve connected the database in properties with content option. I paste the code:
Public NotInheritable Class METARTAF
Inherits Page
Dim dbpath As String = Path.Combine(ApplicationData.Current.LocalFolder.Path, "airportsdb.sqlite3")
Dim conn As SQLite.Net.SQLiteConnection = New SQLite.Net.SQLiteConnection(New WinRT.SQLitePlatformWinRT(), dbpath)
Dim airportinfo As List(Of String) = Nothing
Public Sub New()
' This call is required by the designer.
InitializeComponent()
End Sub
Private Sub AutoSuggestBox_TextChanged(sender As AutoSuggestBox, args As AutoSuggestBoxTextChangedEventArgs)
Dim datairport As New List(Of String)
Dim retrieve = conn.Table(Of flugzeuginfo)().ToList
If args.Reason = AutoSuggestionBoxTextChangeReason.UserInput Then
If sender.Text.Length > 1 Then
For Each item In retrieve
datairport.Add(item.IATA)
datairport.Add(item.ICAO)
datairport.Add(item.Location)
datairport.Add(item.Airport)
datairport.Add(item.Country)
Next
airportinfo = datairport.Where(Function(x) x.StartsWith(sender.Text)).ToList()
sender.ItemsSource = airportinfo
End If
Else
sender.ItemsSource = "No results..."
End If
End Sub
Private Sub AutoSuggestBox_SuggestionChosen(sender As AutoSuggestBox, args As AutoSuggestBoxSuggestionChosenEventArgs)
Dim selectedItem = args.SelectedItem.ToString()
sender.Text = selectedItem
End Sub
Private Sub AutoSuggestBox_QuerySubmitted(sender As AutoSuggestBox, args As AutoSuggestBoxQuerySubmittedEventArgs)
If args.ChosenSuggestion Is Nothing Then
stationidtxt.Text = args.ChosenSuggestion.ToString
End If
End Sub
Anyone could help about this?
Before you query or insert into a table, you should CREATE it. This tells SQLite what columns you have and suggests datatypes (on other rdbms's you get actual data type enforcement but SQLite does not do that). If this is your problem, you will want to spend some time with the SQLite documentation on data types and the ability to hook them into your application.
On the other hand, as you seem to be trying to retrieve data, this suggess one of two things is wrong. Either you care connecting to the wrong db (in which case SQLite will usually helpfully create an empty db for you!) or else you are specifying the wrong table.

Using SSIS Environment Variables With VB Program

Good Afternoon,
I have created an SSIS Project with a single package in it. The SSIS Project and Package work as I expect when I manually executed from the server. I thought that if I set an environment variable on the server and mapped it to the project. That the project would then use those variables every time the package was executed unless otherwise told. The following code is my VB code
'VB.Net code
Imports System.Data.SqlClient
Imports Microsoft.SqlServer.Management.IntegrationServices
Imports System.Collections.ObjectModel
Public Class Form1
Private Sub StartPackageButton_Click(sender As System.Object, e As System.EventArgs) Handles StartPackageButton.Click
Try
' Connection to the database server where the packages are located
Dim ssisConnection As New SqlConnection("Data Source=" + txtServerName.Text + ";Integrated Security=SSPI;")
' SSIS server object with connection
Dim ssisServer As New IntegrationServices(ssisConnection)
' The reference to the package which you want to execute
Dim ssisPackage As PackageInfo = ssisServer.Catalogs("SSISDB").Folders("SSIS_PROJECTS").Projects("AgressoExport").Packages("File56Export.dtsx")
' Add a parameter collection for 'system' parameters (ObjectType = 50), package parameters (ObjectType = 30) and project parameters (ObjectType = 20)
Dim executionParameters As New Collection(Of PackageInfo.ExecutionValueParameterSet)
' Add execution parameter to override the default asynchronized execution. If you leave this out the package is executed asynchronized
Dim executionParameter1 As New PackageInfo.ExecutionValueParameterSet
executionParameter1.ObjectType = 50
executionParameter1.ParameterName = "SYNCHRONIZED"
executionParameter1.ParameterValue = 1
executionParameters.Add(executionParameter1)
' Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)
Dim executionParameter2 As New PackageInfo.ExecutionValueParameterSet
executionParameter2.ObjectType = 50
executionParameter2.ParameterName = "LOGGING_LEVEL"
executionParameter2.ParameterValue = 3
executionParameters.Add(executionParameter2)
' Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)
Dim executionParameter3 As New PackageInfo.ExecutionValueParameterSet
If (Trim(txtPreviousID.Text) <> "") Then
executionParameter3.ObjectType = 20
executionParameter3.ParameterName = "PreviousBatchID"
executionParameter3.ParameterValue = txtPreviousID.Text
executionParameters.Add(executionParameter3)
End If
' Get the identifier of the execution to get the log
Dim executionIdentifier As Long = ssisPackage.Execute(False, Nothing, executionParameters)
' Loop through the log and add the messages to the listbox
For Each message As OperationMessage In ssisServer.Catalogs("SSISDB").Executions(executionIdentifier).Messages
SSISMessagesListBox.Items.Add(message.MessageType.ToString() + ": " + message.Message)
Next
Catch ex As Exception
If ex.InnerException IsNot Nothing Then
SSISMessagesListBox.Items.Add(ex.Message.ToString() + " : " + ex.InnerException.Message.ToString())
Else
SSISMessagesListBox.Items.Add(ex.Message.ToString())
End If
End Try
End Sub
End Class
I'm starting to think that I did not understand environments correctly when it comes to SSIS. My environment was setup as TEST and PROD on their respective servers with the same variable names mapped to the same parameters but with different values. I am starting to believe I should have had the same Environment name on both the TEST and PROD server, which I would then refer too using my VB code. I have not been able to find out how to refer to the Environment using VB yet either though.
I would appreciate any help on the matter.
Cheers,
Johnathan
For the purpose ssis have given facility of configuration and you have to just create separate cofig file or db entry for your different environment .
https://msdn.microsoft.com/en-us/library/ms141682.aspx
You need to set the reference property of the package to be the ID of the environment.
To get the environment ID try:
DECLARE #environment_id AS BIGINT
SELECT #environment_id = reference_id FROM SSISDB.internal.environment_references where environment_name = 'your environment name'
To be able to use Environments inside a Visual Basic .NET program. You need to declare the Environment Reference and pass the reference to the Execute Method of the SSIS Package.
The following block of code is how it is done:
Dim re As EnvironmentReference
re = ssisServer.Catalogs("SSISDB").Folders("SSIS_PROJECTS").Projects("AgressoExport").References("AgressoExport", ".")
Dim executionIdentifier As Long = ssisPackage.Execute(False, re, executionParameters)
SSISDB is the catalog name, SSIS_PROJECTS is the folder name under the catalog that I am using. AgressoExport is my Project Name. ("AgressoExport", ".") refers to the Environment named AgressoExport under my project in the root of the Environment Folder.
Cheers

snapshotID parameter type mismatch when calling Render method on ReportExecution2005.asmx SSRS service

I am trying to render reports as PDF using the ReportExecution2005.asmx service endpoint on a SSRS 2012 server with MSSQL 2012 backend. When I call the Render method on the web service, I get the following error:
The parameter value provided for 'snapshotID' does not match the parameter type. ---> Microsoft.ReportingServices.Diagnostics.Utilities.ParameterTypeMismatchException: The parameter value provided for 'snapshotID' does not match the parameter type. ---> System.FormatException: String was not recognized as a valid DateTime
This error occurs with any report I try to render, snapshotID is not a parameter on the reports, and checking the configuration of the reports, they are not set up to be cached or use snapshots. We just recently moved from MSSQL 2005 to 2012, using the ReportExecution2005 endpoint with SSRS and SQL 2005 I never saw this error, it worked fine. I've tried adding snapshotID as a parameter with different values such as empty string, current time, etc. but that's apparently not what it's looking for. Below is the code I'm using to set up and call the Render method on the service. pstrExportFormat in my case will be "PDF"
Public Function ExportReport(pstrReportPath As String, plstParams As List(Of ReportParameter), pstrExportFormat As String) As Byte()
Dim lResults() As Byte = Nothing
Dim lstrSessionId As String
Dim execInfo As New reporting.ExecutionInfo
Dim execHeader As New reporting.ExecutionHeader
Dim lstrHistoryId As String = String.Empty
Try
Dim rs As New reporting.ReportExecutionService
Dim deviceInfo As String = "<DeviceInfo><PageHeight>8.5in</PageHeight><PageWidth>11in</PageWidth><MarginLeft>0.25in</MarginLeft><MarginRight>0.25in</MarginRight><MarginTop>0.25in</MarginTop><MarginBottom>0.25in</MarginBottom></DeviceInfo>"
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim params As New List(Of reporting.ParameterValue)
Dim param As reporting.ParameterValue
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
For Each lInputParam In plstParams
param = New reporting.ParameterValue
param.Name = lInputParam.Name
param.Value = lInputParam.Value
params.Add(param)
Next
rs.ExecutionHeaderValue = execHeader
execInfo = rs.LoadReport(pstrReportPath, lstrHistoryId)
rs.SetExecutionParameters(params.ToArray, "en-us")
lResults = rs.Render(pstrExportFormat, deviceInfo, "", "", "", Nothing, Nothing)
Catch ex As Exception
Throw
End Try
Return lResults
End Function
Some additional information, this code is from an app built in VS 2012 Pro and targets the .NET 2.0 framework. I have tried targeting a newer framework but that gives me a different ReportExecutionService object altogether and I can't assign credentials in the same way, the Render method is also different in that case.
Any ideas on a workaround, or a better way to render reports programmatically? Thanks.
I had this exact same problem today and figured out that, in the LoadReport method, you want to make sure the HistoryID has a value of Nothing (null in C#). Right now, you're passing it in with an empty string - change the declaration to
Dim lstrHistoryId As String = Nothing
Or change your method call to
rs.LoadReport(pstrReportPath, Nothing)

Convert list (of string) from datareader to string

I've captured some data from a datareader into a list and now I'm wondering what's the best way to put these out into strings.
The requirement I have is I need to grab field names from a table and then out put these as headings on a page.
objConn = New SqlConnection(strConnection)
objConn.Open()
objCmd = New SqlCommand(strSQL, objConn)
rsData = objCmd.ExecuteReader(0)
If rsData.HasRows Then
Do While (rsData.Read())
Dim SubjectNames As New List(Of String)
SubjectNames.Add(rsData.GetString("subject"))
Loop
SubjectList = SubjectNames.ToArray
Now I was thinking ToArray and was wondering how then to output all of the list entries into strings that I can then use later on.
It's also prudent to note that I'm doing this all inline as the CMS I have to use doesn't allow any code behind.
If i understand you correctly you don't know how to convert a List(Of String) to a string. You can use String.Join and specify which string you want to use to join the words:
Dim SubjectNames As New List(Of String)
Do While (rsData.Read())
SubjectNames.Add(rsData.GetString("subject"))
Loop
Dim headers As String = String.Join(", ", SubjectNames)
Note that i've moved the declaration of the list outside of the loop because otherwise you would always create a new list for every record.
Edit: So you don't know how to access elements in a List or Array.
Elements in a List(Of String) or String() are already individual strings. You access each element via indexer. For example: Dim firstSubject = SubjectNames(0) or via Linq: firstSubject = SubjectNames.First(). For the 10th element: Dim subject10 = SubjectNames(9) since indexes are zero based.
MSDN: Arrays in Visual Basic

Resources