Public Class Geocode
Public Structure GeocodeResult
Public Latitude As String
Public Longitude As String
Public Result As String
End Structure
Public Shared Function GetGeocode(ByVal Address As String) As GeocodeResult
Dim strLat As String = ""
Dim strLon As String = ""
Dim strResult As String = ""
Dim oXmlDoc As Object
GetGeocode.Latitude = ""
GetGeocode.Longitude = ""
GetGeocode.Result = ""
Try
Dim baseURL As String = "https://maps.google.com/maps/api/geocode/xml?sensor=false&address=" & Address
baseURL = Replace(baseURL, " ", "+")
oXmlDoc = CreateObject("Microsoft.XMLDOM")
With oXmlDoc
.Async = False
If .Load(baseURL) And Not .selectSingleNode("GeocodeResponse/status") Is Nothing Then
GetGeocode.Result = .selectSingleNode("GeocodeResponse/status").Text
If Not .selectSingleNode("GeocodeResponse/result") Is Nothing Then
GetGeocode.Latitude = .selectSingleNode("//location/lat").Text
GetGeocode.Longitude = .selectSingleNode("//location/lng").Text
Return GetGeocode
End If
End If
End With
oXmlDoc = Nothing
Return GetGeocode
Exit Function
Catch ex As Exception
Throw (ex)
End Try
Return GetGeocode
End Function
End Class
Ok so this works fine in production, qa, and localhost until we moved it to an Azure VM. From the VM we can go use a browser to get to the https://maps.google.com/maps/api/geocode/xml?sensor=false&address= URL. but when another page calls the getgeocode function the results are always blank meaning the rest api call failed in some way.
I don't think its the domain key restrictions because a) im not using a key in this call and b) i set my google api key to any domain to test it.
EDIT: I have tried using another service with the same result. It works in dev and on local machines but not on the Azure VMs. What I do not understand is how the REST apis are accessible via the browser, but return nothing when called from code.
Any ideas?
Explicitly creating a web client and loading that into the xml document has fixed this issue for me.
Imports Microsoft.VisualBasic
Imports System.Xml
Imports System.Linq
Imports System.Xml.Linq
Imports System.Net
Imports System.IO
Public Class Geocode
Public Structure GeocodeResult
Public Latitude As String
Public Longitude As String
Public Result As String
End Structure
Public Shared Function GetGeocode(ByVal Address As String) As GeocodeResult
Dim oXmlDoc As Object
GetGeocode.Latitude = ""
GetGeocode.Longitude = ""
GetGeocode.Result = ""
Try
Dim baseURL As String = "https://maps.google.com/maps/api/geocode/xml?sensor=false&address=" & Address
baseURL = Replace(baseURL, " ", "+")
Using WC As New WebClient()
oXmlDoc = CreateObject("Microsoft.XMLDOM")
With oXmlDoc
.Async = False
If .Load(WC.DownloadData(baseURL)) And Not .selectSingleNode("GeocodeResponse/status") Is Nothing Then
GetGeocode.Result = .selectSingleNode("GeocodeResponse/status").Text
If Not .selectSingleNode("GeocodeResponse/result") Is Nothing Then
GetGeocode.Latitude = .selectSingleNode("//location/lat").Text
GetGeocode.Longitude = .selectSingleNode("//location/lng").Text
Return GetGeocode
End If
End If
End With
oXmlDoc = Nothing
End Using
Return GetGeocode
Exit Function
Catch ex As Exception
Throw (ex)
End Try
Return GetGeocode
End Function
End Class
Related
I have an ms access database I need to run in different computers. My problem is that each computer is store the backend in different location. Until now, I only have 2 machines running, but know I need to run it in more. I stored the location of each computer in a Public Constant and with a simple If statement it was linking in the correct one.
Public Const strFolderDatabasePc1 as string "c:\DatabasePc1"
Public Const strFolderDatabasePc2 as string "c:\DatabasePc2"
....
Is it possible to create a Public Const with an if statement on database load?
Public Const strFolderDatabase as string
If Pc1 then
strFolderDatabase = FolderPc1
else if Pc2 then
strFolderDatabase = FolderPc2
else if Pc3 then
strFolderDatabase = FolderPc3
else
strError
EndIf
Thank you.
UPDATE:
Until now i have write the following code. It contains 4 Users.
'Database Folders
Public Const MainFolder As String = "\\localhost\c$\User\Main"
Public Const UserAFolder As String = "\\localhost\c$\User\UserA"
Public Const UserBFolder As String = "\\localhost\c$\User\UserB"
Public Function AdminFolder() As String
AdminFolder = Application.CurrentProject.Path & "\Admin\"
End Function
'Database Keys
Public Const MainUserKey As String = "\\localhost\c$\User\Main\Key.txt"
Public Const UserAKey As String = "\\localhost\c$\User\UserA\key.txt"
Public Const UserBKey As String = "\\localhost\c$\User\UserB\key.txt"
Public Function AdminKey() As String
AdminFolder = Application.CurrentProject.Path & "\Admin\key.txt"
End Function
Public Function FolderExists(ByVal path_ As String) As Boolean
On Error Resume Next
FolderExists = (GetAttr(path_) And vbDirectory) = vbDirectory
On Error GoTo 0
End Function
Public Function FileExists(ByVal path_ As String) As Boolean
On Error Resume Next
FileExists = (Len(Dir(path_)) > 0)
On Error GoTo 0
End Function
Public Function FolderDatabase()
If FileExists(AdminKey) And FolderExists(AdminFolder) Then
'Admin
FolderDatabase = AdminFolder
ElseIf FileExists(MainUserKey) And FolderExists(UserMainFolder) Then
'MainUser
FolderDatabase = UserMainFolder
ElseIf FileExists(UserAKey) And FolderExists(UserAFolder) Then
'UserA
FolderDatabase = UserAFolder
ElseIf FileExists(UserBKey) And FolderExists(UserBFolder) Then
'UserB
FolderDatabase = UserBFolder
Else
'Unknown User
'Do something else...
End If
End Function
And using the following code inside each form.
Sub Check()
If FolderExists(FolderDatabase) Then
'===> User, Continue Loading.
If Dir(FolderDatabase & "*.*") = "" Then
'===> Empty Folder.
'Do something...
Else
'===> Files On Folder.
'Do something...
End If
Else
'===> Not Known User.
Application.Quit acQuitSaveNone
End If
End Sub
Can I write it or do it with more simple way? Thank you.
PS:
I need to have in one place the location of each USER because I might change in the future the location or file name. Also I am using two more folders with different names and again I am using all the above.
In simple words no, but you could have a Function return the correct path by passing the pc number as argument:
Public Const strFolderDatabasePc1 as string "c:\DatabasePc1"
Public Const strFolderDatabasePc2 as string "c:\DatabasePc2"
Public Function FolderDatabase(ByVal pcNo As Long) As String
Select Case pcNo
Case 1:
FolderDatabase = strFolderDatabasePc1
Case 2:
FolderDatabase = strFolderDatabasePc2
End Select
End Function
Then just pass the pc number required:
Dim path_ As String
path_ = FolderDatabase(1)
To make it more readable, setup an Enum for the various pc's.
Public Enum Computers
Home
Work
End Enum
Public Function FolderDatabase(ByVal pc As Computers) As String
Select Case pc
Case Computers.Home:
FolderDatabase = strFolderDatabasePc1
Case Computers.Work:
FolderDatabase = strFolderDatabasePc2
End Select
End Function
Dim path_ As String
path_ = FolderDatabase(Computers.Home)
It doesn't make sense. Each computer has its own C: drive, that the others won't see.
So you can simply use:
Public Const strFolderDatabasePc As string "c:\DatabasePc"
That said, you might be better off to use a folder under C:\Users\Public as your database file isn't, as seen by Windows, an application but a document.
I have a program that allows users to setup a client/server to control/run commands from a remote location. Now i'm trying to implement server plugins, and I'm doing that by loading every .vb file in a folder contained inside the current running directory. Everything is great, and the code from the external files compiles just fine... Only problem is, Its returning nothing when I try to compile the script and use one of the methods inside it.
Here's some code for you to check out. My error is in the 2nd. Any idea on how to fix this?
The Interaction Interface:
Public Interface LinkingInterface
Property name As String
Property statetag As String
Sub selected(ByVal Sock As Integer)
Sub deselected(ByVal Sock As Integer)
Sub load()
Function generateOutput(ByVal input As String, ByVal Sock As Integer) As String
End Interface
Detection/Loading of the "Modes" (add-ins):
For Each file In My.Computer.FileSystem.GetFiles("modes\")
Dim thisMode As LinkingInterface = LoadMode(My.Computer.FileSystem.ReadAllText(file))
thisMode.load() '<---------------------------My error is here, saying its a null ref.
modes_InterfaceCollection.Add(thisMode) 'Public modes_InterfaceCollection As New Microsoft.VisualBasic.Collection()
modes_nameIndex.Add(thisMode.name) 'Public modes_nameIndex As New Specialized.StringCollection()
Next
'LoadMode' Function
Public Function LoadMode(ByVal code As String) As LinkingInterface
Using provider As New VBCodeProvider()
Dim parameters As New CompilerParameters()
parameters.GenerateInMemory = True
parameters.ReferencedAssemblies.Add(Reflection.Assembly.GetExecutingAssembly().Location)
parameters.MainClass = "Remote_Command_Line.MainModule"
Dim interfaceNamespace As String = GetType(LinkingInterface).Namespace
Dim codeBuilder As New Text.StringBuilder
Dim namespaces() As String = New String() {"Microsoft.VisualBasic", "System", "System.Console", "System.Collections", "System.Collections.Generic", _
"System.Data", "System.Diagnostics", "Remote_Command_Line.MainModule"}
Dim codeString As New StringBuilder
For Each namespacestring As String In namespaces
codeString.AppendLine("Imports " & namespacestring)
Next
codeString.AppendLine(code)
Dim results As CompilerResults = provider.CompileAssemblyFromSource(parameters, codeString.ToString)
'I commented out this just for debugging purposes
'If results.Errors.HasErrors Then
'For Each scriptError As CompilerError In results.Errors
'WriteLine(scriptError.ToString)
'Next
'Else
Return CType(results.CompiledAssembly.CreateInstance(results.CompiledAssembly.GetType.Name), LinkingInterface)
'End If
End Using
End Function
The Testing file 'test.vb':
Public Class test_mode
'Designed for RCL mode 1.0b
'Matthew 2013
'used for managing the local filesystem.
'####################################
#Region "Properties"
'all of these properties listed are required --------------------
Implements LinkingInterface
Property name As String Implements LinkingInterface.name 'the name the client refers to you in the 'modeswitch' command
Property statetag As String Implements LinkingInterface.statetag 'short tag displayed on the client when active before the input signal '>'
'----------------------------------------------------------------
Public curDirDatabank As New Specialized.StringCollection()
#End Region
'####################################
'####################################
#Region "Subs"
'Its required to have, but not required to do anything. This load sub is here for any modes that may require an initialization
Private Sub load() Implements LinkingInterface.load 'REQUIRED
name = "file" : statetag = "file"
MsgBox("Testing: It's loaded")
End Sub
Private Sub selected(ByVal Sock As Integer) Implements LinkingInterface.selected
MsgBox("Testing: '" & Sock & "' selected the File mode")
End Sub
Private Sub deselected(ByVal Sock As Integer) Implements LinkingInterface.deselected
MsgBox("Testing: '" & Sock & "' deselected the File mode")
End Sub
Private Function generateOutput(ByVal input As String, ByVal Sock As Integer) As String Implements LinkingInterface.generateOutput 'REQUIRED
Return ("Testing: '" & Sock & "' said '" & input & "'")
End Function
#End Region
'####################################
End Class
the following line is wrong.
Return CType(results.CompiledAssembly.CreateInstance(results.CompiledAssembly.GetType.Name), LinkingInterface)
You need to search through the loaded classes for one implementing your interface (it being VB you automatically get classes generated for the My namespace objects such as My.Computer)
Try this instead
For Each t As Type In results.CompiledAssembly.GetTypes()
If t.GetInterface(GetType(LinkingInterface).Name) IsNot Nothing Then
Return CType(results.CompiledAssembly.CreateInstance(t.Name), LinkingInterface)
End If
Next
Return Nothing
Two weeks ago I found a very interesting article: "A HTTP file server in 130 lines of code". I translated the original code in Visual basic (I use Visual Basic Net 2005 Express).
Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Web
Public Class HttpFileServer
Implements IDisposable
Public rootPath As String
Private Const bufferSize As Integer = 1024 * 512
'512KB
Private ReadOnly http As HttpListener
Public Sub New(ByVal rootPath As String)
Me.rootPath = rootPath
http = New HttpListener()
http.Prefixes.Add("http://localhost:80/")
http.Start()
http.BeginGetContext(requestWait, Nothing)
End Sub
Public Sub Dispose() Implements System.IDisposable.Dispose
http.[Stop]()
End Sub
Private Sub requestWait(ByVal ar As IAsyncResult)
If Not http.IsListening Then
Return
End If
Dim c = http.EndGetContext(ar)
http.BeginGetContext(requestWait, Nothing)
Dim url = tuneUrl(c.Request.RawUrl)
Dim fullPath = IIf(String.IsNullOrEmpty(url), rootPath, Path.Combine(rootPath, url))
If Directory.Exists(fullPath) Then
returnDirContents(c, fullPath)
ElseIf File.Exists(fullPath) Then
returnFile(c, fullPath)
Else
return404(c)
End If
End Sub
Private Sub returnDirContents(ByVal context As HttpListenerContext, ByVal dirPath As String)
context.Response.ContentType = "text/html"
context.Response.ContentEncoding = Encoding.UTF8
Using sw = New StreamWriter(context.Response.OutputStream)
sw.WriteLine("html")
sw.WriteLine("head meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8""/head")
sw.WriteLine("body ul")
Dim dirs = Directory.GetDirectories(dirPath)
For Each d As Object In dirs
Dim link = d.Replace(rootPath, "").Replace("\"c, "/"c)
sw.WriteLine("<li><DIR> a href=""" + link + """ " + Path.GetFileName(d) + "/a /li ")
Next
Dim files = Directory.GetFiles(dirPath)
For Each f As Object In files
Dim link = f.Replace(rootPath, "").Replace("\"c, "/"c)
sw.WriteLine(" li <a href=""" + link + """ " + Path.GetFileName(f) + " /a /li ")
Next
sw.WriteLine(" /ul /body /html ")
End Using
context.Response.OutputStream.Close()
End Sub
Private Shared Sub returnFile(ByVal context As HttpListenerContext, ByVal filePath As String)
context.Response.ContentType = getcontentType(Path.GetExtension(filePath))
Dim buffer = New Byte(bufferSize - 1) {}
Using fs = File.OpenRead(filePath)
context.Response.ContentLength64 = fs.Length
Dim read As Integer
While (InlineAssignHelper(read, fs.Read(buffer, 0, buffer.Length))) > 0
context.Response.OutputStream.Write(buffer, 0, read)
End While
End Using
context.Response.OutputStream.Close()
End Sub
Private Shared Sub return404(ByVal context As HttpListenerContext)
context.Response.StatusCode = 404
context.Response.Close()
End Sub
Private Shared Function tuneUrl(ByVal url As String) As String
url = url.Replace("/"c, "\"c)
url = HttpUtility.UrlDecode(url, Encoding.UTF8)
url = url.Substring(1)
Return url
End Function
Private Shared Function getcontentType(ByVal extension As String) As String
Select Case extension
Case ".avi"
Return "video/x-msvideo"
Case ".css"
Return "text/css"
Case ".doc"
Return "application/msword"
Case ".gif"
Return "image/gif"
Case ".htm", ".html"
Return "text/html"
Case ".jpg", ".jpeg"
Return "image/jpeg"
Case ".js"
Return "application/x-javascript"
Case ".mp3"
Return "audio/mpeg"
Case ".png"
Return "image/png"
Case ".pdf"
Return "application/pdf"
Case ".ppt"
Return "application/vnd.ms-powerpoint"
Case ".zip"
Return "application/zip"
Case ".txt"
Return "text/plain"
Case Else
Return "application/octet-stream"
End Select
End Function
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
target = value
Return value
End Function
End Class
But I got errors:
Error 1 Argument not specified for parameter 'ar' of 'Private Sub requestWait(ar As System.IAsyncResult)'. line 19
Error 2 Argument not specified for parameter 'ar' of 'Private Sub requestWait(ar As System.IAsyncResult)'. line 31
Both errors refer to the expression http.BeginGetContext(requestWait, Nothing). But I don't know how to handle this.
To compile your code change the lines
http.BeginGetContext(requestWait, Nothing)
to
http.BeginGetContext(AddressOf requestWait, Nothing)
You can have a look at AddressOf Operator and this question.
Hello I'm getting this error, while trying to save serial number to XML File.
If the file doesn't exist, it saves the file fine, but if i change Registered tag to False in Xml file, and try again, it says "The Process Cannot acces the file ... because it is being used by another process".
In my main form i read the information from XML, and in my regform (which i open if registered tag in xml is false) i write to the file. is it because of that?! I don't think so.
Here is my Registration class:
Imports System.IO
Imports System.Xml
Public Class RegistrationClass
Public Property SerialNumber As String
Public Property Registered As Boolean = False
Public Sub Write_Reg(ByVal FileString As String, ByVal RegisterName As String, ByVal RegisterCompany As String, ByVal RegisterSerialNumber As String)
Dim Registered As Boolean = False
Dim Comment As String = "StroySoft 2012 Register Database"
Dim SerialNumber As String = "dev-xxx-123"
Dim ClientOS As String = Trim(My.Computer.Info.OSFullName)
If RegisterSerialNumber = SerialNumber Then
Dim settings As New XmlWriterSettings()
settings.Indent = True
' Initialize the XmlWriter.
Dim XmlWrt As XmlWriter = XmlWriter.Create(FileString, settings)
With XmlWrt
' Write the Xml declaration.
.WriteStartDocument()
' Write a comment.
.WriteComment(Comment)
' Write the root element.
.WriteStartElement("Data")
' Start our first person.
.WriteStartElement("Register")
' The person nodes.
.WriteStartElement("Name")
.WriteString(RegisterName.ToString())
.WriteEndElement()
.WriteStartElement("Company")
.WriteString(RegisterCompany.ToString())
.WriteEndElement()
.WriteStartElement("SerialNumber")
.WriteString(RegisterSerialNumber.ToString())
.WriteEndElement()
Registered = True
.WriteStartElement("Registered")
.WriteString(Registered)
.WriteEndElement()
.WriteStartElement("ClientOS")
.WriteString(ClientOS)
.WriteEndElement()
' The end of this person.
.WriteEndElement()
' Close the XmlTextWriter.
.WriteEndDocument()
.Close()
End With
MsgBox("Успешна регистрация! Благодарим Ви!")
MainForm.РегистрацияToolStripMenuItem.Visible = False
Else
MsgBox("Невалиден сериен номер!")
End If
End Sub
Public Sub Check_Reg(ByVal FileString As String)
If (System.IO.File.Exists(FileString)) Then
Dim document As XmlReader = New XmlTextReader(RegForm.RegFile)
While (document.Read())
Dim type = document.NodeType
If (type = XmlNodeType.Element) Then
If (document.Name = "Registered") Then
If document.ReadInnerXml.ToString() = "True" Then
Registered = True
Else
Registered = False
End If
End If
If (document.Name = "SerialNumber") Then
SerialNumber = document.ReadInnerXml.ToString()
End If
End If
End While
Else
MessageBox.Show("The filename you selected was not found.")
End If
End Sub
End Class
is it because of that?! I don't think so.
It's exactly because of that.
You should always make sure to properly dispose IDisposable resources such as Streams and Writers/Readers by wrapping them in a Using block. In your case I don't see you closing your reader. But if you wrap it in a Using block you shouldn't worry about it. Even if an exception is thrown the resource will be properly released.
Example:
Using XmlWrt As XmlWriter = XmlWriter.Create(FileString, settings)
...
End Using
You should do the same with your XmlReader:
Using document As XmlReader = XmlReader.Create(RegForm.RegFile)
...
End Using
I made a little console application to help me with remapping client certificates to my webserver. However, when I try to run the application it is giving me an error of:
Unhandled exception at 0x00920309 in CertMapping.exe: 0xC0000005: Access violation reading location 0x00000000.
It's a pretty basic console app:
Imports Microsoft.Web.Administration
Module Module1
Sub main(ByVal cmdArgs() As String)
Dim WebSite As String = Nothing
Dim UserName As String = Nothing
Dim Password As String = Nothing
Dim Base64EncodedCertData As String = Nothing
Dim switch As String, arg As String
For Each Str As String In cmdArgs
switch = Split(Str, ":").First
arg = Split(Str, ":").Last
Select Case switch
Case "/Web"
WebSite = arg
Case "/User"
UserName = arg
Case "/Pwd"
Password = arg
Case "/Cert"
If arg = "mySecretCode" Then
Base64EncodedCertData = "ServerCertGoesHere"
Else
Base64EncodedCertData = arg
End If
End Select
Next
Using serverManager As New ServerManager
Dim config As Configuration = serverManager.GetWebConfiguration(WebSite.ToString)
Dim iisClientCertificateMappingAuthenticationSection As ConfigurationSection = config.GetSection("system.webServer/security/authentication/iisClientCertificateMappingAuthentication")
iisClientCertificateMappingAuthenticationSection("enabled") = True
iisClientCertificateMappingAuthenticationSection("oneToOneCertificateMappingsEnabled") = True
Dim oneToOneMappingsCollection As ConfigurationElementCollection = iisClientCertificateMappingAuthenticationSection.GetCollection("oneToOneMappings")
Dim addElement As ConfigurationElement = oneToOneMappingsCollection.CreateElement("add")
addElement.SetMetadata("lockItem", True)
addElement("enabled") = True
addElement("userName") = UserName.ToString
addElement("password") = Password.ToString
addElement("certificate") = Base64EncodedCertData.ToString
oneToOneMappingsCollection.Add(addElement)
Dim accessSection As ConfigurationSection = config.GetSection("system.webServer/security/access", WebSite.ToString)
accessSection("sslFlags") = "Ssl, SslNegotiateCert"
serverManager.CommitChanges()
End Using
End Sub
End Module