Writing Queries in sqlite with vb.net & uwp - vb.net

I have searched most of SO, and spent countless hours googling, so I'm going to post in the hopes that someone can help or just tell me it can't be done!
I am trying to make my vb.net uwp application be able to query a local sqlite database with a test query, but I am at a complete loss trying to find an example or any sort of documentation that isn't in c# without a clear parallel to how to translate to vb.net.
I have a base test class that can successfully connect with my database file, but I can't find anywhere how to do a query - all the resources online just link me to either vb.net without uwp or c# with uwp! I'll paste my code, but links to any resources or any advice would be so so helpful :)
Public Class dtbTest
Private conn As SQLiteConnection
Private sqcommand As SQLiteCommand
Private query As String = "SELECT * FROM userdetails"
Private cnn As SQLiteConnection
Private DBConnection As String = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "test.s3db")
Private tableInfo As List(Of SQLiteConnection.ColumnInfo)
Public Sub New()
Try
conn = New SQLiteConnection(DBConnection)
conn.BeginTransaction()
tableInfo = conn.GetTableInfo("userdetails")
sqcommand.CommandText = query
Catch
End Try
End Sub
End Class

In case people are interested, I got it working by trying the new Microsoft.Data.SQL package, so would recommend checking that if anyone is having similar problems!

Related

VB.Net and SQL Communication

I haven't done any serious programming in years, and I don't have much experience manipulating SQL data indirectly anyway, but I'm trying to create a program for my employer and running into confusion. Many of the answers here and college books i have are helpful, but just when I think I understand what's going on, I get lost again, often because people use variables and column names that are identical, leaving it hard to figure out what is going where.
So let's say I have a database called Attendance on SQL server localhost. Inside is a table called employees which consists of the columns: employee_id, name_last, name_first, and points. The first three are varchar and the last is a decimal(2,1). Using Visual Studio for Visual Basic, I've created a program which contains several textboxes. The user enters the employee id which becomes var_empid when they hit the Load button.
How would I proceed so that the program executes an SQL query which pulls the name_last and name_first from the table where the employee_id matches the var_empid as input by the user and puts that data into the var_last_name and var_first_name variables?
Secondly, if the user entered into other textboxes information that became var_empid, var_last_name, var_first_name and then clicked the Add Employee button, how I would i proceed so that the information added by the user is written to the SQL table?
For clarification, moving data between textboxes and variables isn't the problem. I can do that all day. It's moving the variables between the VB and SQL that is causing me problems. I realize this is basic stuff, but any help would be great.
To answer your second request, try to execute the following query:
Dim Query = "INSERT INTO Attendance (name_first, name_last, points) VALUES(var_first_name, var_last_name, var_points)"
Note that i did not insert the var_empid because if you have created your table correctly, this id should be an auto-generated primary key that increments itself automatically.
It's not easy to start because at first you see so many different names and technologies and they all seem to promise, more or less, the same thing. Especially if you want to build a database-connected application, and start doing basic stuff like CRUD operations (inserts, updates, deletes...), it's easy to get confused.
Start reading here about ADO.NET Architecture. You hopefully will understand something more about DataSet, Linq To SQL, Entity Framework, but probably not much. This is why I strongly suggest to take a few days and slowly watch the tutorial videos by Beth Massi, on VB.Net and Data.
On this page, How Do I Videos for Visual Basic, you will find a lot of useful information to start building simple but very effective applications and database.
Be sure to watch Forms over Data Video Series, Visual Basic 2008 Forms over Data Videos (using DataSets) and then Language Integrated Query (LINQ) Series (using LINQ To SQL where you'll understand why in your vb.net application your object variables have the same name as your database columns). FInally you can take a look at the Entity Framework tutorial (that you will find very similar to Linq To SQL).
After these basic tutorials you'll be able to choose your path and start programming. Once you grasp the basic concepts it's a lot easier to search and understand what you find on the internet.
This is more than what you asked for, because I'm trying to push you into some good practices at the same time:
Public Class Employee
Public Property ID As String
Public Property Points As Double 'why is this a decimal(2,1)?
Public Property LastName As String
Public Property FirstName As String
Public Shared Function FromDataRow(ByVal data As IDataRecord) As Employee
Dim result As New Employee()
result.ID = CDbl(data("ID"))
result.LastName = CStr(data("LastName"))
result.FirstName = CStr(data("FirstName"))
Return result
End Function
End Class
Public Module DataLayer
'Check www.connectionstring.com for more info on connection strings
Private Property ConnectionString As String = "database connection string here"
Private Iterator Function GetRecords(ByVal sql As String, ByVal addParams As Action(Of SqlParameterCollection)) As IEnumerable(Of IDataRecord)
Using cn As New SqlConnection(ConnectionString), _
cmd As New SqlCommand(sql, cn)
addParams(cmd.Parameters)
cn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read)
Yield Return rdr
End While
End Using
End Using
End Function
Private Function GetRecords(Of T)(ByVal sql As String, ByVal addParams As Action(Of SqlParameterCollection), ByVal translate As Function(Of IDataRecord, T)) As IEnumerable(Of T)
Return GetRecords(sql, addParams).Select(translate)
End Function
Public Function GetEmployeeData(ByVal EmployeeID As String) As Employee
Dim sql As String = _
"SELECT employee_id, name_last, name_first " & _
"FROM employees " & _
"WHERE employee_id= #ID"
Return GetRecords(sql, _
Sub(p) p.Add("#ID", SqlDbType.NVarChar, 10).Value = EmployeeID, _
Employee.FromDataRow).First()
End Function
End Class

Opening/closing sql connection - redundant code

I was wondering what is the most basic way to avoid the following.
con.ConnectionString = connection_String
con.Open()
cmd.Connection = con
'database interaction here
cmd.Close()
I keep making those lines all over in my project, but I figure there has to be a better way to save on typing this over and over. It makes the code look even more sloppy than it already is!
Ended up with this, works well for me. Thanks for the help :)
Public Sub connectionState()
If con.State = 0 Then
con.ConnectionString = connection_String
con.Open()
cmd.Connection = con
Else
con.Close()
End If
End Sub
This is where a lot of programmers are tempted to create a "database layer" with a variations on method signatures that look like this:
Public DataSet ExecuteSQL(ByVal sql As String) As DataSet
That allows you to isolate all that boilerplate connection code in one place. An sql command string goes in, and data comes out. Easy.
Don't do it!
This is headed in the right direction, but has one very big flaw: it forces you to use string manipulation to substitute parameter values into your sql queries. That leads to horrible sql injection security vulnerabilities.
Instead, make sure you include some mechanism in your methods to prompt for the sql parameters separately. This usually comes in the form of an additional argument to the function, and could be as simple as an array of KeyValuePairs. If you're comfortable with lambdas, my preferred pattern looks like this:
Public Iterator Function GetData(Of T)(ByVal sql As String, ByVal addParameters As Action(Of SqlParameterCollection), ByVal translate As Func(Of IDatarecord, T)) As IEnumerable(Of T)
Using cn As New SqlConnection("connection string"), _
cmd As New SqlCommand(sql, cn)
addParameters(cmd.Parameters)
cn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
Yield(translate(rdr))
End While
End Using
End Using
End Function
To call that function, you would do something like this:
Dim bigCustomers = GetData("SELECT * FROM Customers WHERE SalesTotal > #MinSalesTotal", _
Sub(p) p.Add("#MinSalesTotal", SqlDbType.Decimal, 1000000), _
MyCustomerClass.FromIDataRecord)
You can try creating a class ( a singleton class ), and write the database connection syntax code and exceptions in that class, then call one object to the main class to create the database connection, that's the best way in performance and keep writing the same code on and on...
You can use just using block, using execute dispose on non managed object in the end of treatment.
Link : http://msdn.microsoft.com/en-us/library/htd05whh(v=vs.80).aspx

How to get hardware print?

Can someone tell me how to get the hardware print of my computer, on VB 2010 express, or where and how is that stored? Thanks in advance.
The best way to figure out what hardware is attached to your computer is to use WMI to get the information. Microsoft has created a tool that will create C#, VB.Net and VBScript sample code which you can run with the program and see what the values are, you can then add it to your program. This tool is called the WMI Code Creator. I would start out by exploring the Classes starting with Win32_
Now that I know what you are trying to do I can be a little more specific. The WMI NameSpace you are needing is root\CIMV2 the Class is Win32_DiskDrive or Win32_PhysicalMedia and the Property is SerialNumber. I made a small console test app in Vb.net. It will print out the drive serialnumbers on your PC, if you need it in c# I can modify. There are also numerous other SO Questions about the same subject.
Imports System
Imports System.Management
Module Module1
Sub Main()
For Each sn As String In GetDriveSerialNumber()
Console.WriteLine(sn.Trim)
Next
Console.ReadLine()
End Sub
Function GetDriveSerialNumber() As List(Of String)
Dim snList As List(Of String) = New List(Of String)
Try
Dim searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_DiskDrive")
For Each queryObj As ManagementObject In searcher.Get()
snList.Add(queryObj("SerialNumber").ToString())
Next
Catch err As ManagementException
Throw
End Try
Return snList
End Function
End Module

Returning a DataTable in WCF and .NET

Thanks William, that was the ticket. Had to assign the name property on both ends [DataTable.TableName].
On a side note here: There appears to be some school of thought (no offense Marc) that the following statement is always true:
"Everything in the world can and should be made into an object."
It is, simply, not always true. There are cases where you cannot cram your 'object' into any cookie-cutter or class no matter how you try to customize it. For me to objectize this beast, I'd have to create roughly 4,000 objects. I don't have time to do that, and yet this project must run as a service. Frankly I think the developers at MickeySoft need to get out more into the real world, and see for themselves that although theory is great it does not represent true-life challenges. I am all for working with objects for the obvious benefits, but there is a reality that universals do not exist. In my trade, even 'most of the time' rarely happens.
Before they push out a new technology set, and cease support of an old one, they need to make sure that the new technology has the same capabilities the old one had.
For the record: The people who believe the above statement to be true are also the same people who would refuse to take the project I'm currently working on.
Just the same -- thank you both for your time, efforts and opinions!
I'm trying to create a WCF function that will return a table to my console testing app. I am a total noob. The data is 2-dimensional and looks like this:
23 Letter
42 Another Letter
43 Document
...
Here's what I'm trying to do:
<ServiceContract()> _
Public Interface ILetterWriter
<OperationContract()> _
Function GetLetter(ByVal LetterID As String, ByVal StateID As String, ByVal CompID As String, ByVal tblVar As DataTable) As String
<OperationContract()> _
Function GetLetterNames(ByVal DepartmentType As Integer) As DataTable
End Interface
Public Function GetLetterNames(ByVal DepartmentType As Integer) As DataTable Implements ILetterWriter.GetLetterNames
Dim SQLCon As New SqlClient.SqlConnection
Dim SQLCmd As New SqlClient.SqlCommand
'Connect to the database
SQLCon.ConnectionString = "Data Source=VMSQL08-SRV1;Initial Catalog=DotNetDev;User ID=aiis_pgmr;Password=ag58102;"
SQLCon.Open()
'Grab the stored procedure, which returns the letter names
SQLCmd.CommandText = "sp_GetLetters"
SQLCmd.CommandType = CommandType.StoredProcedure
SQLCmd.Connection = SQLCon
'Pass the parameters
SQLCmd.Parameters.AddWithValue("#LetterType", DepartmentType)
'Execute the stored procedure, fill the datatable from a data adapter
GetLetterNames = New DataTable
GetLetterNames.Load(SQLCmd.ExecuteReader)
'Shut it down
SQLCmd.Dispose()
SQLCon.Close()
SQLCon.Dispose()
End Function
...Of course, it won't work. I just need to get the WCF to pass a basic table to my console application. The execute SQL seems to work just fine, I just can't get the data back to my application.
Any help would be greatly appreciated.
Thanks,
Jason
I agree with the other poster.
However, if you are returning a DataTable, you have to set the "Name" property of the DataTable if you want to return it from a WCF Service.

Dynamic programming in VB

We develop applications for SAP using their SDK. SAP provides a SDK for changing and handling events occuring in the user interface.
For example, with this SDK we can catch a click on a button and do something on the click. This programming can be done either VB or C#.
This can also be used to create new fields on the pre-existing form. We have developed a specific application which allows users to store the definition required for new field in a database table and the fields are created at the run time.
So far, this is good. What we require now is that the user should be able to store the validation code for the field in the database and the same should be executed on the run time.
Following is an example of such an event:
Private Sub SBO_Application_ItemEvent(ByVal FormUID As String, ByRef pVal As SAPbouiCOM.ItemEvent, ByRef BubbleEvent As Boolean) Handles SBO_Application.ItemEvent
Dim oForm As SAPbouiCOM.Form
If pVal.FormTypeEx = "ACC_QPLAN" Then
If pVal.EventType = SAPbouiCOM.BoEventTypes.et_LOST_FOCUS And pVal.BeforeAction = False Then
oProdRec.ItemPressEvent(pVal)
End If
End If
End Sub
Public Sub ItemPressEvent(ByRef pVal As SAPbouiCOM.ItemEvent)
Dim oForm As SAPbouiCOM.Form
oForm = oSuyash.SBO_Application.Forms.GetForm(pVal.FormTypeEx, pVal.FormTypeCount)
If pVal.EventType = SAPbouiCOM.BoEventTypes.et_LOST_FOCUS And pVal.BeforeAction = False Then
If pVal.ItemUID = "AC_TXT5" Then
Dim CardCode, ItemCode As String
ItemCode = oForm.Items.Item("AC_TXT2").Specific.Value
CardCode = oForm.Items.Item("AC_TXT0").Specific.Value
UpdateQty(oForm, CardCode, ItemCode)
End If
End If
End Sub
So, what we need in this case is to store the code given in the ItemPressEvent in a database, and execute this in runtime.
I know this is not straight forward thing. But I presume there must be some ways of getting these kind of things done.
The SDK is made up of COM components.
Thanks & Regards,
Rahul Jain
I've not done this myself, but I think you're going to have to actually use the Systems.Runtime.CompilerServices functions to dynamically compile an assembly and then link it in. Another solution if you are using SQL Server might be to take advantage of the fact that you can write C# or VB.NET code in stored procedures. That might be a way.
Dim sqlstring1 As String = "Blah Blah Blah SQL here"
Dim Rs SAPbobsCOM.Recordset
Rs = GetDIConnection.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset)
rs.doquery(SqlString1)
You can create the code dynamically and compile it..
Have some simple interfaces to call the validation code and in all your dynamic code, implement the interface(s). This way, you can load assembly dynamically and get the class as an interface and use that interface directly..