Print MS ACCESS table with while loop in VB.net - php

Like we can do easily in php with mysql we execute a query and then run a while loop on that to print all result records of that query. How do we perform this function in vb.net (2008) with ms access db. here is my code which I use for printing now
sql = "SELECT * From Inventory "
Dim da As New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Inventory")
Label1.Text = ds.Tables("Inventory").Rows(0).Item(2)
Label2.Text = ds.Tables("Inventory").Rows(1).Item(2)
Label3.Text = ds.Tables("Inventory").Rows(2).Item(2)

Try this :
Dim rowCount As Integer = ds.Tables('Inventory').Rows.Count
Dim Labels() As Label = {Label1, Label2, Label3}
foreach label As Label In Labels
label.Test = ds.Tables('Inventory').Rows(Array.IndexOf(Labels, label)).Item(2)
Next
Or if you want to get the Labels() array dynamically by getting all the Labels on your form, replace this with Line 2 of the above :
Dim Labels() As Label
For Each ctrl In Form1.Controls
If TypeOf ctrl Is TextBox Then
nextNum = Labels.Length +1
ReDim Preserve Labels(nextNum)
TeamIndex(nextNum) = ctrl
End If
Next

Related

How can I get MS Access to read from a .txt file at certain intervals?

I have coded a basic PHP script that collects the data from a few HTML forms and writes it to a text document, and then configured Access to link this text document to a table and import automatically. This all works fine but the problem is that Access seems to be always using this file meaning that my script can't write to it. How can I get Access to check the document every so often, look at what is there and import it without any duplicate data?
two ways:
Dim strFilename As String: strFilename = "C:\temp\yourfile.txt"
Dim strTextLine As String
Dim iFile As Integer: iFile = FreeFile
Open strFilename For Input As #iFile
Do Until EOF(1)
Line Input #1, strTextLine
Loop
Close #iFile
or you can use below code:
Dim intFile As Integer
Dim strFile As String
Dim strIn as String
Dim strOut As String
strOut = vbNullString
intFile = FreeFile()
strFile = "C:\Folder\MyData.txt"
Open strFile For Input As #intFile
Do While Not EOF(intFile)
Line Input #intFile, sIn
If Left(strIn, 7) = "KeyWord" Then
strOut = Mid(strIn, 8)
booFound = True
Exit Do
Loop
Close #intFile
If Len(strOut) > 0 Then
MsgBox "Your Data is " & strOut
Else
MsgBox "Keyword Not Found"
End If
more info . . .More Info . . .

How to send array in http get request

private void timer1_Tick(object sender, System.EventArgs e)
{
int iIdx;
int[] iData;
bool[] bData;
if (m_bRegister) // Read registers (4X references)
{
// read register (4X) data from slave
if (adamTCP.Modbus().ReadHoldingRegs(m_iStart, m_iLength, out iData))
{
m_iCount++; // increment the reading counter
txtStatus.Text = "Read registers " + m_iCount.ToString() + " times...";
// update ListView
label1.Text = HttpGet("http://127.0.0.1/misc/api1.php?value0=" + iData[0].ToString());
label2.Text = HttpGet("http://127.0.0.1/misc/api1.php?value1=" + iData[1].ToString());
label3.Text = HttpGet("http://127.0.0.1/misc/api1.php?value2=" + iData[2].ToString());
label4.Text = HttpGet("http://127.0.0.1/misc/api1.php?value3=" + iData[3].ToString());
label5.Text = HttpGet("http://127.0.0.1/misc/api1.php?value4=" + iData[4].ToString());
for (iIdx = 0; iIdx < m_iLength; iIdx++)
{
listViewModbusCur.Items[iIdx].SubItems[2].Text = iData[iIdx].ToString(); // show value in decimal
listViewModbusCur.Items[iIdx].SubItems[3].Text = iData[iIdx].ToString("X04"); // show value in hexdecimal
}
How do i send array using httpget method? The code on top show that i'm sending data one by one. I need to send it in array and retrieve it back in api,php so that i could insert it into database in one row. currently, it's 1 data for 1 row.
Here is a example to convert array to json in PHP
$arr=array(
"varl1"=>1,
"varl2"=>"example",
"varl3"=>3,
);
$json_arr=json_encode($arr);
Now you can send $json_arr
and then you can decode it using json_decode()
you should passing 'value0' become just one querystring, ex : value[]
so the url will become
http://127.0.0.1/misc/api1.php?value[]="+ iData[0].ToString()"&value[]="+ iData[1].ToString() and etc what you want to send it "
or you should use http_build_query to the param array data
the code you show is php ??
the api maybe php but the code style more like .NET c#
correct me if im wrong.
//Update Response
string[] param = new string[(how many your counter param)];
param [0] = "test0";
param [1] = "test1";
param [2] = "test2";
in my example i give you 3
string sParams = JsonConvert.SerializeObject(param) ;
HttpGet("http://127.0.0.1/misc/api1.php?value=" + sParams);

How do I loop through an MS SQL database with VB.NET?

I'm trying to implement the following php code in visual basic. I wrote it in PHP because I knew I could do what I wanted to in that language, but I can't for the life of me figure out how to get it working in Visual Basic to loop through a MS SQL database.
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'FakeDB');
$result = mysqli_query($con,"SELECT * FROM FakeDB");
$concatDupes = Array();
for ( $i = 0, $i< count($result), $i++) {
if ( $result[$i] == $result[$i + 1] {
array_push($concatDupes,$result[$i] + $result[$i + 1])
} else {
array_push( $concatDupes, $result[$i])
}
}
I've tried to use the code in this post but to no avail. (I put MsgBox("hello") inside the while loop and nothing happened) I've also attempeted the following, also with zero success.
Dim i = Me.PaymentTableAdapter.GetData().HazWasteAmtColumn.ToString()
MsgBox(i) 'no message box
Dim i = Me.PaymentTableAdapter.GetData().Count
MsgBox(i) ' also no message box
Dim i = Me.PaymentTableAdapter.GetData().Count
MsgBox(GetType(i)) 'type of i is not defined
I know my query is returning results because it works fine in a DataGridView.
Other useful info:
Watching the i (any of the i's referenced above) always shows Nothing, no matter what I've tried.
Here's what happens when I call Public Sub ReadData(ByVal connectionString As String, ByVal queryString As String) (full function in linked page) with:
Dim connect = WindowsApplication1.My.Settings.ShopMgtConnectionString
Dim querty As String = "SELECT * "
querty = querty + "FROM SM.PartItem "
ReadData(connect, querty)
immediate window output (the error list shows nothing):
A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll
A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll
A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll
A first chance exception of type 'System.Data.ConstraintException' occurred in System.Data.dll
A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll
EDIT: Here's the ReadData() method
Public Sub ReadData(ByVal connectionString As String, _
ByVal queryString As String)
Using connection As New OleDbConnection(connectionString)
Dim command As New OleDbCommand(queryString, connection)
connection.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
Console.WriteLine(reader(0).ToString())
End While
reader.Close()
End Using
End Sub
EDIT, Again...
I've taken a screen recording of the program running. It's just not doing anything useful.
http://youtu.be/i7oNVDXUw78
Make sure you are reading non null data:
While reader.Read()
If reader.IsDBNull(0) = False Then
Console.WriteLine(reader.GetValue(0).ToString())
End If
End While

Excel VBA: Dynamic Variable Name

Note: I am limited to PHP <-> VBA. Please do not suggest anything that requires an Excel Addon, or any other language/method.
I have a function that connect to a specified URL, submits data, and then retrieves other data. This works great. I'm trying to write it so i can use it as a generic function I can use to connect to any file I need to connect to - each would return different data (one could be user data, one could be complex calculations etc).
When it retrieves the data from PHP, is there a way to dynamically set the variables based on what is received - even if i do not know what has been received.
I can make PHP return to VBA the string in any format, so I'm using the below as an example:
String that is received in vba:
myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday
If i were to parse this in PHP, I could do something similar to (not accurate, just written for example purposes);
$myData = "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday"
$myArr = explode("&",$myData)
foreach($myArr as $key => $value){
${$key} = $value;
}
echo $someOtherValue; //Would output to the screen 'Hockey';
I would like to do something similar in VBA. The string I am receiving is from a PHP file, so I can format it any way (json etc etc), I just essentially want to be able to define the VARIABLES when outputting the string from PHP. Is this possible in VBA?.
The current state of the function I have that is working great for connections is as below:-
Function kick_connect(url As String, formdata)
'On Error GoTo connectError
Dim http
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "POST", url, False
http.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
http.send (formdata)
kick_connect = http.responseText
Exit Function
connectError:
kick_connect = False
End Function
Ultimately, I want to be able to do something like
sub mySub
myData = "getId=" & Range("A1").Value
myValue = kick_connect("http://path-to-my-php-file.php",myData)
if myValue = False then
'Handle connection error here
exit sub
end if
'do something snazzy here to split "myValue" string (eg "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday") into own variables
msgbox(myValue1) 'Should output "Dave"
end sub
Obviously I could put the values into an array, and reference that, however I specifically want to know if this exact thing is possible, to allow for flexibility with the scripts that already exist.
I hope this makes sense, and am really grateful for any replies i get.
Thank you.
You can use a Collection:
Dim Tmp As String
Dim s As String
Dim i As Integer
Dim colVariabili As New Collection
Tmp = "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday"
Dim FieldStr() As String
Dim FieldSplitStr() As String
FieldStr = Split(Tmp, "&")
For Each xx In FieldStr
FieldSplitStr = Split(xx, "=")
colVariabili.Add FieldSplitStr(1), FieldSplitStr(0)
Next
Debug.Print colVariabili("myValue1")
Debug.Print colVariabili("someOtherValue")
Debug.Print colVariabili("HockeyDate")
It's ok if you don't have the correct sequence of var...
I am not sure if this can help you, but as far as I understand your question you want to be able to create the variables dynamically based on the query string parameters. If so then here is example how to add this variables dynamically. Code needs standard module with a name 'QueryStringVariables'. In this module the query string will be parsed and each query string parameter will be added as get-property. If you wish to be able to change the value as well then you will need to add let-property as well.
Add reference to Microsoft Visual Basic For Applications Extensibility
Option Explicit
Private Const SourceQueryString As String = "myValue1=Dave&someOtherValue=Hockey&HockeyDate=Yesterday"
Sub Test()
Dim queryStringVariablesComponent As VBIDE.vbComponent
Dim queryStringVariablesModule As VBIDE.CodeModule
Dim codeText As String
Dim lineNum As Long: lineNum = 1
Dim lineCount As Long
Set queryStringVariablesComponent = ThisWorkbook.VBProject.VBComponents("QueryStringVariables")
Set queryStringVariablesModule = queryStringVariablesComponent.CodeModule
queryStringVariablesModule.DeleteLines 1, queryStringVariablesModule.CountOfLines
Dim parts
parts = Split(SourceQueryString, "&")
Dim part, variableName, variableValue
For Each part In parts
variableName = Split(part, "=")(0)
variableValue = Split(part, "=")(1)
codeText = "Public Property Get " & variableName & "() As String"
queryStringVariablesModule.InsertLines lineNum, codeText
lineNum = lineNum + 1
codeText = variableName & " = """ & variableValue & ""
queryStringVariablesModule.InsertLines lineNum, codeText
lineNum = lineNum + 1
codeText = "End Property"
queryStringVariablesModule.InsertLines lineNum, codeText
lineNum = lineNum + 1
Next
DisplayIt
End Sub
Sub DisplayIt()
MsgBox myValue1 'Should output "Dave"
End Sub

Visual Basic + PHP Server

I need a PHP Server to interact with my wireless sensors. But I also need that server to be controlled by a Visual Basic Application.
Some of the features I need in the Visual Basic Application:
Start/Stop Server
Server Configuration
Access files on the server directory.
The PHP file (server application) is simply to accept data from the wireless sensor module and store in a flat database file (CSV, XML). After this data has been written Visual Basic must access the flat database file to perform analysis.
Any suggestions on what server to use and what particular methods might provide the easiest solution?
Well, what you want is broad and yet, there is not enough information about your PHP part.
But I can help you with VB.NET. Here is a Class (And a Sub and an Event) that can really help.
Some Examples first
Simply loads a HTML code:
Dim Page As New WEBhtml("http://www.example.com/index.php?get=something")
While Page.IsReady = False
End While
If IsNothing(Page.Exception) Then
MsgBox(Page.GetHtml)
Else
MsgBox(Page.Exception.Message)
End If
Sends POST to destination (just the Dim line):
Dim Page As New WEBhtml("http://www.example.com/index.php?get=something", {"a=alpha", "b=beta", "c=I Don't Know :D !"})
Use Handling:
Private Sub form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Page As New WEBhtml("http://www.e.com/i.php")
End Sub
Private Sub html_done(ByRef sender As WEBhtml) Handles Me.WebHtml_Done
MsgBox("Timetook: " & sender.TimeTook / 1000 & "s")
MsgBox("Url: " & sender.Url)
If IsNothing(sender.Exception) Then
MsgBox("Bandwidth: " & sender.Bytes / 1024 & "kb")
MsgBox("HTML: " & sender.GetHtml)
Else
MsgBox("Error: " & sender.Exception.Message)
End If
End Sub
See? very easy.
Now to Start
Follow these two steps
First: Add System.Web Reference
Go to Project > [Project name] Properties > Reference
After that press the "Add..." button, and check 'System.Web'
Then press Ok. also check it in 'Imported namespaces'
Second: Copy this block before the 'End Class'
Public Shared Event WebHtml_Done(ByRef sender As WEBhtml)
Friend Shared Sub RaiseDone(ByRef wh As WEBhtml)
RaiseEvent WebHtml_Done(wh)
End Sub
Public Class WEBhtml
Private thrd As Threading.Thread
Private Err As Exception
Private BytesUsed As ULong = 0
Private Time As UInteger = 0
Private Html As String = ""
Private _Url As String
Private tmr As New Timer
Private Sub initialize()
tmr.Interval = 50
AddHandler tmr.Tick, AddressOf Tick
tmr.Enabled = True
tmr.Start()
End Sub
Public Sub New(ByVal Url As String)
thrd = New Threading.Thread(Sub() WEB_POST(Url))
initialize()
thrd.Start()
End Sub
Public Sub New(ByVal Url As String, ByVal PostData As String())
thrd = New Threading.Thread(Sub() WEB_POST(Url, PostData))
initialize()
thrd.Start()
End Sub
Private Sub Tick(sender As Object, e As EventArgs)
If thrd.IsAlive = False Then
tmr.Enabled = False
RaiseDone(Me)
End If
End Sub
Private Sub WEB_POST(ByVal url As String, Optional ByVal values() As String = Nothing)
_Url = url
Dim data As String = ""
Dim a, b As Integer
b = My.Computer.Clock.TickCount
Try
For i = 0 To values.GetLength(0) - 1
a = values(i).IndexOf("=")
If a >= 0 Then
data += System.Web.HttpUtility.UrlEncode(Mid(values(i), 1, a)) & "=" & System.Web.HttpUtility.UrlEncode(Mid(values(i), a + 2))
If i < values.GetLength(0) - 1 Then data += "&"
End If
Next
Catch
data = ""
End Try
Try
Dim request As System.Net.WebRequest = System.Net.WebRequest.Create(url)
request.Method = "POST"
Dim postdata As String = data
Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(postdata)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
request.Timeout = 100000
Dim dataStream As IO.Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As Net.WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New IO.StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
BytesUsed += responseFromServer.Length + byteArray.Length
Time = My.Computer.Clock.TickCount - b
Html = (responseFromServer)
Catch ex As Exception
Err = ex
Time = My.Computer.Clock.TickCount - b
Html = ""
End Try
End Sub
Public ReadOnly Property Exception() As Exception
Get
Return Err
End Get
End Property
Public ReadOnly Property TimeTook() As UInteger
Get
Return Time
End Get
End Property
Public ReadOnly Property Bytes() As ULong
Get
Return BytesUsed
End Get
End Property
Public ReadOnly Property GetHtml() As String
Get
Return Html
End Get
End Property
Public ReadOnly Property IsReady() As Boolean
Get
Return Not thrd.IsAlive
End Get
End Property
Public ReadOnly Property Url() As String
Get
Return _Url
End Get
End Property
End Class
I believe this works properly.
Hope It Helps.

Categories