Within a JSON Geocode GetResponse, the code provided by Microsoft uses a function to return results. However, I want to use results outside of the function, but I cannot access the data from within the function afterwards. Maybe the code can explain this more clearly:
Dim geocodeRequest As New Uri(String.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}", query, key))
Dim latlong_adress As BingMapsRESTService.Common.JSON.Location = Nothing
GetResponse(geocodeRequest, Function(x)
MsgBox(x.ResourceSets(0).Resources.Length & " result(s) found.")
latlong_adress = x.ResourceSets(0).Resources(0)
'Correct results:
MsgBox(latlong_adress.Confidence)
MsgBox(latlong_adress.EntityType)
MsgBox(latlong_adress.Point.Coordinates(0) & ", " & latlong_adress.Point.Coordinates(1))
Return 0
End Function)
'Empty: --> is nothing
If latlong_adress IsNot Nothing Then
MsgBox(latlong_adress.Confidence)
MsgBox(latlong_adress.EntityType)
MsgBox(latlong_adress.Point.Coordinates(0) & ", " & latlong_adress.Point.Coordinates(1))
End If
How can I access the data from the response after the response has been made?
I solved my problem, although I am not quite sure about the correctness of the answer. My problems with understanding the issue were related to the asynchronous type of the GetResponse operation.
I added an event as follows:
Public Event NewGeocode(ByVal LocationData As BingMapsRESTService.Common.JSON.Location, ByVal successful As Boolean)
Private Sub geocodeLoop(Optional LocationData As BingMapsRESTService.Common.JSON.Location = Nothing, Optional successfull As Boolean = False) Handles Me.NewGeocode
If LocationData Is Nothing Then
geocodeAddress()
Else
If successfull = True Then
'Correct results:
MsgBox(LocationData.Confidence)
MsgBox(LocationData.EntityType)
MsgBox(LocationData.Point.Coordinates(0) & ", " & LocationData.Point.Coordinates(1))
geocodeAddress()
Else
MsgBox("Unsuccessfull")
End If
End If
End Sub
Private Sub geocodeAddress()
Dim key As String = ...
Dim query As String = "1 Microsoft Way, Redmond, WA"
Dim geocodeRequest As New Uri(String.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}", query, key))
Dim latlong_adress As BingMapsRESTService.Common.JSON.Location = Nothing
GetResponse(geocodeRequest, Function(x)
If Not x.ResourceSets(0).Resources.Length = 0 Then
RaiseEvent NewGeocode(x.ResourceSets(0).Resources(0), True)
Else
RaiseEvent NewGeocode(Nothing, False)
End If
Return 0
End Function)
End Sub
Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
geocodeLoop()
End Sub
Related
I am trying to create a image slideshow by changing the Image control .picture property by looping through all images in a predefined folder
C:\Images
The code I am using:
Public pixpaths As Collection
Public pix_path As String
Public pixnum As Integer
Public fs As YtoFileSearch
Public k As Integer
Public Sub Image_set()
Set pixpaths = New Collection
pix_path = "C:\Images"
Set fs = New YtoFileSearch
With fs
.NewSearch
.LookIn = pix_path
.fileName = "*.jpg"
If fs.Execute() > 0 Then
For k = 1 To .FoundFiles.Count
pixpaths.Add Item:=.FoundFiles(k)
Next k
Else
MsgBox "No files found!"
DoCmd.OpenForm "Fr_Sketchpad" ' If no images found in folder the set image from another form 'Sketchpad' image control
Forms!Fr_Sketchpad.Visible = False
Forms!Fr_Main!imgPixHolder.Picture = "" 'Forms!Fr_Sketchpad!Img_Std.Picture Was getting another error here so commented this
pixnum = 0
Exit Sub
End If
End With
'load first pix
Forms!Fr_Main.imgPixHolder.Picture = pixpaths(1)
pixnum = 1
End Sub
Public Sub Image_loop()
If pixnum = pixpaths.Count Then
pixnum = 1
ElseIf pixnum = 0 Then
Exit Sub
Else
pixnum = pixnum + 1
Forms!Fr_Main!imgPixHolder.Picture = pixpaths(pixnum)
End If
End Sub
Private Sub Form_Open(Cancel As Integer)
Call Image_set
End Sub
Private Sub Form_Timer()
Call Image_loop
End Sub
The Image_Set(), Image_loop() and variables are in one module and are called in Form_open and Form_timer events
The code is working fine for one loop cycle but for the next loop cycle it is showing an error:
Error 91 object variable or with block variable not set
on
If pixnum = pixpaths.Count Then
In debug mode when I check value for pixnum it is 0
[Update]
Class Module YtoFileSearch
Option Compare Database
Option Explicit
' How this is not another proof that doing VBA is a bad idea?
' Nevertheless, we'll try to make the scripts relying on Application.FileSearch works again.
' The interface of this YtoFileSearch class aims to stick to the original
' Application.FileSearch class interface.
' Cf is https://msdn.microsoft.com/en-us/library/office/aa219847(v=office.11).aspx
' For now it do not handle recursive search and only search for files.
' More precisely the following filters are not implemented:
' * SearchSubFolders
' * MatchTextExactly
' * FileType
' If that's something you need, please create an issue so we have a look at it.
' Our class attributes.
Private pDirectoryPath As String
Private pFileNameFilter As String
Private pFoundFiles As Collection
' Set the directory in which we will search.
Public Property Let LookIn(directoryPath As String)
pDirectoryPath = directoryPath
End Property
' Allow to filter by file name.
Public Property Let fileName(fileName As String)
pFileNameFilter = fileName
End Property
'Property to get all the found files.
Public Property Get FoundFiles() As Collection
Set FoundFiles = pFoundFiles
End Property
' Reset the FileSearch object for a new search.
Public Sub NewSearch()
'Reset the found files object.
Set pFoundFiles = New Collection
' and the search criterions.
pDirectoryPath = ""
pFileNameFilter = ""
End Sub
' Launch the search and return the number of occurrences.
Public Function Execute() As Long
'Lance la recherche
doSearch
Execute = pFoundFiles.Count
End Function
' Do the nasty work here.
Private Sub doSearch()
Dim directoryPath As String
Dim currentFile As String
Dim filter As String
directoryPath = pDirectoryPath
If InStr(Len(pDirectoryPath), pDirectoryPath, "\") = 0 Then
directoryPath = directoryPath & "\"
End If
' If no directory is specified, abort the search.
If Len(directoryPath) = 0 Then
Exit Sub
End If
' Check that directoryPath is a valid directory path.
' http://stackoverflow.com/questions/15480389/excel-vba-check-if-directory-exists-error
If Dir(directoryPath, vbDirectory) = "" Then
Debug.Print "Directory " & directoryPath & " does not exists"
Exit Sub
Else
If (GetAttr(directoryPath) And vbDirectory) <> vbDirectory Then
Debug.Print directoryPath & " is not a directory"
Exit Sub
End If
End If
' We rely on the Dir() function for the search.
' cf https://msdn.microsoft.com/fr-fr/library/dk008ty4(v=vs.90).aspx
' Create the filter used with the Dir() function.
filter = directoryPath
If Len(pFileNameFilter) > 0 Then
' Add the file name filter.
filter = filter & "*" & pFileNameFilter & "*"
End If
' Start to search.
currentFile = Dir(filter)
Do While currentFile <> ""
' Use bitwise comparison to make sure currentFile is not a directory.
If (GetAttr(directoryPath & currentFile) And vbDirectory) <> vbDirectory Then
' Add the entry to the list of found files.
pFoundFiles.Add directoryPath & currentFile
End If
' Get next entry.
currentFile = Dir()
Loop
End Sub
Please advice how to resolve!
I have to answer your comment question you had for me here. This may not solve your issue, but it may help you find it, especially if the error is from you setting pixpaths = nothing in another function as #dbmitch suggested.
You would refer to .FoundFiles in Image_Set the same way you would pixpath, the collection gets populated by the doSearch sub from the .Execute function so the following code should work the same. Also, unless you are using your arguments in another module, you may want to consider making them Private like I did here.
Private pix_path As String
Private pixnum As Integer
Private fs As YtoFileSearch
Public Sub Image_set()
pix_path = "C:\Images"
Set fs = New YtoFileSearch
With fs
.NewSearch
.LookIn = pix_path
.fileName = "*.jpg"
If fs.Execute() > 0 Then
'load first pix
Forms!Fr_Main.imgPixHolder.Picture = .FoundFiles(1)
pixnum = 1
Else
MsgBox "No files found!"
DoCmd.OpenForm "Fr_Sketchpad" ' If no images found in folder the set image from another form 'Sketchpad' image control
Forms!Fr_Sketchpad.Visible = False
Forms!Fr_Main!imgPixHolder.Picture = ""
'Forms!Fr_Sketchpad!Img_Std.Picture Was getting another error here so commented this
pixnum = 0
End If
End With
End Sub
Public Sub Image_loop()
With fs
If pixnum = .FoundFiles.Count Then
pixnum = 1
ElseIf pixnum <> 0 Then
pixnum = pixnum + 1
Forms!Fr_Main!imgPixHolder.Picture = .FoundFiles(pixnum)
End If
End With
End Sub
I am getting following error:
Arithmetic operation resulted in an overflow
on the code below:
Public Function DoEncode(ByVal aPassword As String, ByVal aPassword2 As String) As String
Dim ascii As New ASCIIEncoding()
Dim b As Byte() = ascii.GetBytes(aPassword)
Dim b2 As Byte() = ascii.GetBytes(aPassword2)
Dim iDiff As UInt32 = b2(0) - b(0)
For i As Integer = 0 To b.Length - 1
b(i) += CByte(iDiff)
Next
Return ascii.GetString(b)
End Function
I have used the function in my login form:
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
If UsernameTextBox.Text.Trim() = "" Then
MessageBox.Show("Please enter your user id", "User ID", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Return
End If
If PasswordTextBox.Text.Trim() = "" Then
MessageBox.Show("Please enter your password", "User ID", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Return
End If
If O.AppMan.DoLogin(UsernameTextBox.Text, PasswordTextBox.Text) Then
DialogResult = System.Windows.Forms.DialogResult.OK
End If
End Sub
Upper code is used in:
Public Class TApplicationManager
Public Class O
Public Shared AppMan As New TApplicationManager()
End Class
Public Function DoEncode(ByVal aPassword As String, ByVal aPassword2 As String) As String
Dim ascii As New ASCIIEncoding()
Dim b As Byte() = ascii.GetBytes(aPassword)
Dim b2 As Byte() = ascii.GetBytes(aPassword2)
Dim iDiff As UInt32 = b2(0) - b(0)
For i As Integer = 0 To b.Length - 1
b(i) += CByte(iDiff)
Next
Return ascii.GetString(b)
End Function
Public Function DoLogin(ByVal strUser As String, ByVal strPwd As String) As Boolean
Dim dtbUser As New DataTable()
Dim dtbUserCare As New DataTable()
Dim UserName As String
Dim UserPass As String
Dim cnn As New MySqlConnection(My.Settings.sys_dbConnectionString)
Dim strLoginCare As String = "SELECT * FROM tblusers where Username = '" + strUser + "'"
Dim daUser As New MySqlDataAdapter(strLoginCare, cnn)
dtbUser.Clear()
daUser.Fill(dtbUser)
If dtbUser.Rows.Count = 0 Then
MessageBox.Show("User does not exist", "User status", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Return False
End If
Dim drwUser As DataRow = dtbUser.Rows(0)
UserPass = drwUser("Password").ToString()
UserName = drwUser("Username").ToString()
Dim daUserCare As New MySqlDataAdapter(strLoginCare, cnn)
dtbUserCare.Clear()
daUserCare.Fill(dtbUserCare)
If dtbUserCare.Rows.Count = 0 Then
MessageBox.Show("Invalid user id", "User status", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Return False
End If
Dim drwUserCare As DataRow = dtbUserCare.Rows(0)
If drwUserCare("Password").ToString() <> DoEncode(strPwd, drwUserCare("Password").ToString()) Then
MessageBox.Show("Invalid password. Please try again", "User status", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Return False
End If
If drwUserCare("status").ToString() <> "Y" Then
MessageBox.Show("User is not active", "User status", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Return False
End If
UserPass = drwUserCare("Password").ToString()
UserName = drwUserCare("Username").ToString()
Return True
End Function
End Class
Why am I getting this error?
Ok I'm going to take a stab it's this:
Dim iDiff As UInt32 = b2(0) - b(0)
For i As Integer = 0 To b.Length - 1
b(i) += CByte(iDiff)
Next
A) Uint32 can't be negative - and you are performing a subtraction between two bytes.
B) You are then casting that subtracted value to a Byte - bytes can't be negative, and from memory will throw this exception if you attempt to do so.
I don't actually understand what you're attempting to do in the above loop.
EDIT
As per your comment about this code working in c#, but not in VB, my answer still applies. The conversion is failing, because of either negative numbers or greater than 255.
c# does not automatically check for overflow errors where VB does.
You can disable this behaviour although changing the code to not overflow would be better in my opinion. You may get unexpected results.
See: https://msdn.microsoft.com/en-us/library/aa716336(v=vs.60).aspx
You can disable it by:
Project properties, enable Configuration Properties => Optimizations
=> Remove Integer Overflow Checks.
The same behaviour can be implemented in c# by wrapping the conversion / calculation in a 'checked' block.
I have one method
Public CurrentFileNameNoExtension As String
Public Sub importexcelfile()
CurrentFileNameNoExtension ="Filename"
'do something
End Sub
I want to use CurrentFileNameNoExtension value in onEnter event of the dropdown list(cmvalues) event. That Value use in sql query. My code is
Private Sub cmvalues_Enter()
Dim qstng As String
qstng = CurrentFileNameNoExtension
Me.cmvalues.RowSourceType = "Table/Query"
Me.cmvalues.RowSource = "Select F1 from " & qstng & " WHERE F1 <> 'Control Model';"
End Sub
But qstng value is empty. it is not giving the value in the importexcelfile() function.
EDIT: As I've just noticed, thanks to #simoco, that this is indeed for a userform, there are actually a couple of things to pull this off. One is using globals, which is quite tricky, and another is to use a function to get the string you want.
Function CurrentFileNameNoExtension() As String
'Do some FSO or GetOpenFileName here.
CurrentFileNameNoExtension = "Filename"
End Sub
Private Sub cmvalues_Enter()
qstng = CurrentFileNameNoExtension
Me.cmvalues.RowSourceType = "Table/Query"
Me.cmvalues.RowSource = "Select F1 from " & strFileName & " WHERE F1 <> 'Control Model';"
End Sub
There is not much of an issue using the code you have, really. You just have to make sure that the first sub is called before the second one so that cmvalues_Enter has a valid string to process.
Place this function under Microsoft Access Class Objects Form control,Where cmvalues dropdown exists
Public CurrentFileNameNoExtension As String
Public Sub importexcelfile()
CurrentFileNameNoExtension ="Filename"
'do something
End Sub
Ok so i have this situation where i need to dynamically open a form, see code below, and, if possible, execute a known method for that form.
Open Form Method:
Public Sub ShowForm(par As Form, nm As String)
DoCmd.OpenForm nm
While IsOpen(nm)
DoEvents
Wend
End Sub
Caveat:
Not all forms will have the same method. So if possible add an additional optional parameter to pass through the method call, probably as a string value.
Some examples:
Form1:
public sub InitItem(id as string)
....
end sub
Form2:
public sub InitCategory(id as string)
....
end sub
How about going mad?
Private Sub Form_Open(Cancel As Integer)
Cancel = Not BuildForm(Me.Name, True)
End Sub
Function BuildForm(strFormName, blnRS, Optional strParent = "None", _
Optional strSubname = "", Optional strParentS = "", _
Optional NameMod = "", _
Optional strFormReport = "Form") As Boolean
OpenArgs, some notes
If Me.OpenArgs & "" = "" Then
Cancel = True
Exit Sub
End If
astrOpenArgs = Split(Me.OpenArgs, ",")
I am new to programming in c# and visual basic. I am using visual studio 2010 and I am trying to retrieve some data from a mysql database. Installed using wamp.
I have already set connection to the database by going to 'Project', 'Application Properties', 'Settings'.
I have this error "'mAuto1' is not declared. It may be inaccessible due to its protection level" and I cant seem to solve it.
The code below is for a simple retrieve:
Public Class Form1
Private procAuto As CALCOM.Auto
Private Function Connect_To_Database() As Boolean
Dim mErrorNumQuery As Long
Dim mReturn As Boolean
procAuto = New CALCOM.Auto
procAuto.Connect(mErrorNumQuery)
If mErrorNumQuery = 0 Then
mReturn = True
Else
mReturn = False
End If
Connect_To_Database = mReturn
End Function
Private Function Get_Weight_By_TicketNumber(ByVal mTicketNumber As String, ByRef mAuto1 As Long, ByRef mAuto2 As Long, ByRef mTotalWeight As Long) As Boolean
Dim mErrorNumQuery As Long
Dim mXtr As New CALCOM.xTr
Dim mRec As ADODB.Recordset
Dim mReturn As Boolean
mRec = mXtr.GetList("Select Auto1,Auto2,TotalWeight From txticket Where TicketCode = '" & mTicketNumber & "'", , , mErrorNumQuery)
If mErrorNumQuery = 0 Then
mReturn = True
If mRec.RecordCount <> 0 Then
mRec.MoveFirst()
mRec.MoveFirst()
mAuto1 = mRec.Fields("Auto1").Value
mAuto2 = mRec.Fields("Auto2").Value
mTotalWeight = mRec.Fields("TotalWeight").Value
End If
Else
mReturn = False
End If
Get_Weight_By_TicketNumber = mReturn
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Label1.Text = mAuto1 <--------------------problem here
End Sub
End Class
This program was just a test to see if I can display results of a mysql query on a form label. I wanted to display results on the click of a button
How do I fix the error? Any help appreciated.
The mAuto1 variant is a local one at Get_Weight_By_TicketNumber function, you can't use it outside the function. If you want, declare a class-level variant and set it to the value of mAuto1.