Webclient unable to connect to remote server - vb.net

I am trying to read a text file on a website using a PC that appears to be behind a proxy server. Originally I had 407 errors but then I added;
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy usesystemdefault="True" />
</defaultProxy>
</system.net>
to the app.config and now I get "Unable to connect to the remote server".
My code is:
' Make a WebClient.
myWebClient = New System.Net.WebClient
' Get the indicated URI.
Dim response As Stream = myWebClient.OpenRead("mySite/myfile.txt")
' Read the result.
Dim objreader As New IO.StreamReader(response)
If I enter "mySite/myfile.txt" into a browser from the same PC the website file is displayed on the screen.
Do I have a code error or is there a way my app can get around this?
I have solved the problem by reverting to the VB5 version which uses API calls to download the text file before reading it.
Thanks Randy Birch.
'//API to download file
Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
(ByVal pCaller As Integer, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Integer, ByVal lpfnCB As Integer) As Integer
Private Declare Function DeleteUrlCacheEntry Lib "Wininet.dll" Alias "DeleteUrlCacheEntryA" (ByVal lpszUrlName As String) As Integer
Private Const ERROR_SUCCESS As Integer = 0
Private Const BINDF_GETNEWESTVERSION As Integer = &H10
'//
Private Function DownloadFileAPI(ByRef sSourceUrl As String, ByRef sLocalFile As String) As Boolean
'http://vbnet.mvps.org/index.html?code/internet/urldownloadtofile.htm
'http://vbnet.mvps.org/index.html?code/internet/urldownloadtofilenocache.htm
Call DeleteUrlCacheEntry(sSourceUrl)
'Download the file. BINDF_GETNEWESTVERSION forces
'the API to download from the specified source.
'Passing 0& as dwReserved causes the locally-cached
'copy to be downloaded, if available. If the API
'returns ERROR_SUCCESS (0), DownloadFile returns True.
DownloadFileAPI = URLDownloadToFile(0, sSourceUrl, sLocalFile, BINDF_GETNEWESTVERSION, 0) = ERROR_SUCCESS
End Function
and in the code;
Dim retbol As Boolean
Dim URL As String = "mySite/myFiletodownload"
fsavename = "mysavefile" 'path\filename to save downloaded file to.
Try
'This should return true or false so might not trigger an exception
retbol = DownloadFileAPI(URL, fsavename)
'etc

Related

download html web page or scrape text from it

I am struggling to download full html code from below page. I was using URLDownloadToFileA and MSXML2.XMLHTTP60 methods and none of them downloads full code. Part of the webpage is missing - table on the bottom with "DEBTI...." in not included in the code. My aim is to get these "DEBTI..." strings and I want to avoid selenium if possible. None of below codes work for me, but when I just ctrl+s (save) page from the browser everything is correctly mentioned in the code. Any suggestions? Thanks!
Sub Get_Data()
Dim xmlhttp As New MSXML2.XMLHTTP60, myurl As String
myurl = "https://ec.europa.eu/taxation_customs/dds2/ebti/ebti_consultation.jsp?Lang=en&Lang=en&refcountry=&reference=&valstartdate1=&valstartdate=&valstartdateto1=&valstartdateto=&valenddate1=&valenddate=&valenddateto1=&valenddateto=&suppldate1=&suppldate=&nomenc=2309&nomencto=&keywordsearch1=&keywordsearch=&specialkeyword=&keywordmatchrule=OR&excludekeywordsearch1=&excludekeywordsearch=&excludespecialkeyword=&descript=&orderby=0&Expand=true&offset=1&viewVal=Thumbnail&isVisitedRef=false&allRecords=0&showProgressBar=true" 'replace with your URL
xmlhttp.Open "GET", myurl, False
xmlhttp.Send
Open "C:\Desktop\test.txt" For Output As #1
Print #1, (xmlhttp.responseText)
Close #1
End Sub
Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _
Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _
ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Function DownloadFile(URL As String, LocalFilename As String) As Boolean
Dim lngRetVal As Long
lngRetVal = URLDownloadToFile(0, URL, LocalFilename, 0, 0)
If lngRetVal = 0 Then DownloadFile = True
End Function
Sub test()
DownloadFile "https://ec.europa.eu/taxation_customs/dds2/ebti/ebti_consultation.jsp?Lang=en&Lang=en&refcountry=&reference=&valstartdate1=&valstartdate=&valstartdateto1=&valstartdateto=&valenddate1=&valenddate=&valenddateto1=&valenddateto=&suppldate1=&suppldate=&nomenc=8418&nomencto=&keywordsearch1=&keywordsearch=&specialkeyword=&keywordmatchrule=OR&excludekeywordsearch1=&excludekeywordsearch=&excludespecialkeyword=&descript=&orderby=0&Expand=true&offset=1&viewVal=List&isVisitedRef=false&allRecords=0&showProgressBar=true", "C:\Desktop\abc.html"
End Sub
web:
https://ec.europa.eu/taxation_customs/dds2/ebti/ebti_consultation.jsp?Lang=en&Lang=en&refcountry=&reference=&valstartdate1=&valstartdate=&valstartdateto1=&valstartdateto=&valenddate1=&valenddate=&valenddateto1=&valenddateto=&suppldate1=&suppldate=&nomenc=8418&nomencto=&keywordsearch1=&keywordsearch=&specialkeyword=&keywordmatchrule=OR&excludekeywordsearch1=&excludekeywordsearch=&excludespecialkeyword=&descript=&orderby=0&Expand=true&offset=1&viewVal=List&isVisitedRef=false&allRecords=0&showProgressBar=true

VBA display a google static map in picture with long URL

I'm able to display a google static map in Excel.
Sheets("Sheet1").Range("a1").Parent.Pictures.Insert theURL
This works fine but once my URL is longer than 1650 characters I get an error message.
It's the same when I use a shape to display the map.
Sheets("Sheet1").Shapes("gMap").Fill.UserPicture theURL
Is there another way to display a google static map in Excel?
My URL I want to display could be <= 5000 characters. It's a map with a polyline.
There are URL examples:
URL with 1649 characters
https://maps.googleapis.com/maps/api/staticmap?size=600x600&path=enc%3Amym~h?g~uz`??e?a?q?a?k?c?u?e?s?i?}?m?{`?c?s?a?i?a?i?a?i?a?i?a?g?a?o?a?g?c?q?a?i?g?c`?a?i?m?w`?a?q?q?s`?c?i?s?u`?e?q?m?y`?e?q?o?}`?q?w`?a?g?o?w`?c?g?e?q?a?g?k?o`?o?y`?m?w`?q?w`?a?g?q?u`?a?g?i?y`?m?s`?a?g?k?y`?a?g?i?w`?a?g?e?{`??q?c?y`?g?w`?a?e?e?u?g?g`?m?}`?a?g?m?{`?o?y`?k?a`?i?a`?i?c`?o?s`?u?q`?i?y?o?}`?c?y?c?k`?a?o?k?{`?c?o?o?w`?a?g?m?w`?m?y`?a?g?m?g`?i?y?q?{`?c?o?e?u`?o?m`?a?g?e?c`?d?u?f?c?z?`?b`?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u?e?a?g`?y?e?c?e`?y?e?c?g`?u?i?e?c`?{?e?c?a`?y?g?e?a`?e`?{?}?{?h?a`?v?}?~?a?d?m?f`?g?n`?i?~`?e?z`?o?t`?c?f?m?|`?a?f?i?|`?k?v`?g?|`??v?a?~?c?z?`?ba??|?c?d?}?r?}?f`?q?r?e?l?m?l?a`?z?i?d?}?n?y?h?g?j?e?l?e?v?g?x`??|`?d?|`?`?l`?e?v`?d?z`?`?n?j?x`??f?h?z`??f?j?|`?b?t?f?v`?h?v`??f?p?|`?d?p?h?t`??v`?g?|`?c?p??~`?b?l?f?``?n?``?`?d?n?x?h?n?p?d`?r?l`?j?v?r?l`?t?p`?h?r?b?d?f?r?f?x?b?l?`?l?b?l?f?d`?`?f?b?h`?`?z??h?c?l`??f?c?l`?j?p`?n?r`?b?f?t?r`?d?n?f?v`?m?z?{?~?s?|?a`?|?a`?v?c?`?k?j?m?n?a`?z?c?b?a`?x?c`?|?c?b?a`?|?q?n?a`?z?e?b?y?x?{?~?`?d`?`?z?}?f`?i?d`??f??l`??r`?v?l`?t?p`?`?f?x?n`?t?~?x?d`?v?b`?j?t?`?b?j?p?h?j?b?b?z?``?v?``?h?j`??p`??f?j?z?|?b?v?a?h?b?v?r?z?m?``?w?b?c?~?{?f?e?b`?}?``?q?h?a?d`?w?v?d?
Both URLs work when you copy them to your browser.
Here is an example using #Omegastripes idea of downloading to a folder first. My function in the comments, which converted to tinyURL also worked but can't be posted. Downloading to a folder is more robust however.
Note:
If on 32-bit remove the word PtrSafe
Code:
Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _
Alias "URLDownloadToFileA" (ByVal pCaller As Long, _
ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Private Sub DownloadPic()
Dim url As String
Dim fileLocation As String
url = "https://maps.googleapis.com/maps/api/staticmap?size=600x600&path="
url = url & "enc%3Amym~h?g~uz??e?a?q?a?k?c?u?e?s?i?}?m?{?c?s?a?i?a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??f?h?z`??f?j?|`?b?t?f?v`?h?v`??f?p?|`?d?p?h?t`??v`?g?|`?c?p??~`?b?l?f??n??`?d?n?x?h?n?p?d`?r?l`?j?v?r?l`?t?p`?h?r?b?d?f?r?f?x?b?l?`?l?b?l?f?d`?`?f?b?h`?`?z??h?c?l`??f?c?l`?j?p`?n?r`?b?f?t?r`?d?n?f?v`?m?z?{?~?s?|?a`?|?a`?v?c?`?k?j?m?n?a`?z?c?b?a`?x?c`?|?c?b?a`?|?q?n?a`?z?e?b?y?x?{?~?`?d`?`?z?}?f`?i?d`??f??l`??r`?v?l`?t?p`?`?f?x?n`?t?~?x?d`?v?b`?j?t?`?b?j?p?h?j?b?b?z??v??h?j`??p`??f?j?z?|?b?v?a?h?b?v?r?z?m??w?b?c?~?{?f?e?b?}?``?q?h?a?d?w?v?d?"
fileLocation = "C:\Users\User\Desktop\TestFolder\Test.png"
If URLDownloadToFile(0, url, fileLocation, 0, 0) = 0 Then
Debug.Print "downloaded"
ThisWorkbook.Worksheets("Sheet1").Range("A1").Parent.Pictures.Insert fileLocation
Kill fileLocation
Else
Debug.Print "failed"
End If
End Sub
Result:

Need to edit title bar of putty through vba code

I am using the below vba code to open a putty screen on a button click.
TaskID = Shell("C:\putty.exe 173.194.127.210", vbMaximizedFocus)
When it opens a new screen, the title bar will contain the string "173.194.127.210 - PUTTY".
I want to change "173.194.127.210 - PUTTY" to "173.194.127.210 - HELLO" through vba code when the above code opens a new screen. Can anyone share the code for doing this?
Please note that I am not using super putty.
I am able to do the same manually with following steps:
Right click on title bar of putty screen opened.
Click on change settings
Click on Behavior under the option Window
Change window title as 173.194.127.210 - HELLO
Unfortunately, there is no way to change this value via the command line. The only place that this value can be set is in a session. Look at the PuTTY Configuration page, and click on the Session branch to see this. There is always a session called "Default Settings" which can't be deleted, and simply shows the application's internal defaults. You can't change these. However, you can create a new session programatically, save the window title in that, and then use the "-load" option of the PuTTY command line to load that session when starting the application.
This information for sessions is stored in the registry for each user, under the HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions key. Each key under here becomes a session with the name of the key. For the purposes of creating a session name which is unlikely to clash with a user's session, the code below uses a name which is the application EXE name, prefixed by two underscores.
The registry value you need to write for the window title is "WinTitle". However, you must also provide the "HostName", "Protocol" and "Port" values for PuTTY to open correctly. All values except "Port" are string (REG_SZ), whilst "Port" is an integer (REG_DWORD).
Option Explicit
Private Const HKEY_CURRENT_USER As Long = &H80000001
Private Const ERROR_SUCCESS As Long = 0&
Private Const REG_SZ As Long = 1
Private Const REG_DWORD As Long = 4
Private Enum REGSAM
KEY_ALL_ACCESS = &HF003F
KEY_CREATE_LINK = &H20
KEY_CREATE_SUB_KEY = &H4
KEY_ENUMERATE_SUB_KEYS = &H8
KEY_EXECUTE = &H20019
KEY_NOTIFY = &H10
KEY_QUERY_VALUE = &H1
KEY_READ = &H20019
KEY_SET_VALUE = &H2
KEY_WOW64_32KEY = &H200
KEY_WOW64_64KEY = &H100
KEY_WRITE = &H20006
End Enum
Private Declare Function RegCloseKey Lib "Advapi32.dll" ( _
ByVal hKey As Long _
) As Long
Private Declare Function RegCreateKeyEx Lib "Advapi32.dll" Alias "RegCreateKeyExW" ( _
ByVal hKey As Long, _
ByVal lpSubKey As Long, _
ByVal Reserved As Long, _
ByVal lpClass As Long, _
ByVal dwOptions As Long, _
ByVal samDesired As REGSAM, _
ByVal lpSecurityAttributes As Long, _
ByRef phkResult As Long, _
ByRef lpdwDisposition As Long _
) As Long
Private Declare Function RegSetValueEx Lib "Advapi32.dll" Alias "RegSetValueExW" ( _
ByVal hKey As Long, _
ByVal lpValueName As Long, _
ByVal Reserved As Long, _
ByVal dwType As Long, _
ByVal lpData As Long, _
ByVal cbData As Long _
) As Long
Private Enum ConnectionType
Raw
Telnet
Rlogin
SSH
End Enum
Private Function OpenPutty(ByRef the_sHost As String, ByRef the_sTitle As String, ByVal enmConnectionType As ConnectionType, Optional ByVal the_nPort = -1) As Long
Dim sUniqueSession As String
Dim sKeyUniqueSession As String
Dim sConnectionType As String
Dim nPort As Long
Dim hKeyUniqueSession As Long
sUniqueSession = "__" & App.EXEName
sKeyUniqueSession = "Software\SimonTatham\PuTTY\Sessions\" & sUniqueSession
' Provide the connection type / protocol string, and a default port value.
Select Case enmConnectionType
Case Raw
sConnectionType = "raw"
nPort = -1
Case Telnet
sConnectionType = "telnet"
nPort = 23
Case Rlogin
sConnectionType = "rlogin"
nPort = 513
Case SSH
sConnectionType = "ssh"
nPort = 22
End Select
' -1 indicates use the default port value.
If the_nPort <> -1 Then
nPort = the_nPort
End If
If RegCreateKeyEx(HKEY_CURRENT_USER, StrPtr(sKeyUniqueSession), 0&, 0&, 0&, KEY_SET_VALUE, 0&, hKeyUniqueSession, 0&) = ERROR_SUCCESS Then
RegSetValueEx hKeyUniqueSession, StrPtr("HostName"), 0&, REG_SZ, StrPtr(the_sHost), LenB(the_sHost)
RegSetValueEx hKeyUniqueSession, StrPtr("WinTitle"), 0&, REG_SZ, StrPtr(the_sTitle), LenB(the_sTitle)
RegSetValueEx hKeyUniqueSession, StrPtr("Protocol"), 0&, REG_SZ, StrPtr(sConnectionType), LenB(sConnectionType)
RegSetValueEx hKeyUniqueSession, StrPtr("PortNumber"), 0&, REG_DWORD, VarPtr(nPort), LenB(nPort)
RegCloseKey hKeyUniqueSession
End If
OpenPutty = Shell(App.Path & "\putty.exe -load """ & sUniqueSession & """", vbMaximizedFocus)
End Function
Private Sub Command1_Click()
OpenPutty "192.168.1.5", "My custom title", Telnet
End Sub
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Public Declare Function SetWindowText Lib "user32" Alias "SetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String) As Long
Sub Main()
On Error Resume Next
hwindows = FindWindow(vbNullString, "Microsoft Works Calendar")
Ret = SetWindowText(hwindows, "Calandar")
End Sub

VB.NET string path be cut off automatically

I ended up a simple program sending and receiving a RS-232 message. My parameters (baudrate, COM port) are stored in an INI file (the file will be created automatically if not existing). The progam runs without error but I don't know why it cuts off the path that point to INI file when the path length exceed a limit (there are Unicode Japanese characters in the path string)
My path string in New function (construction) is like this: "D:\通信プログラム20120709\新しいフォルダー\新しいフォルダー\新しいフォルダー\新しいフォルダー\Debug\Config.ini"
and in an event function, it will become: D:\通信プログラム20120709\新しいフォルダー\新しいフォルダー\新しいフォ・
After consulting some source on Internet, they show me that a .NET String would have a very huge capacity so I guess my problem not concerned to VB.NET String.
Any help would be appreciated.
From Comments
I found that the path is changed after the first line of code below
RS232TransPort = IniRoutine.GetString(IniSectionName, ConfigName.COMPort, "COM3")
RS232Baudrate = IniRoutine.GetInteger(IniSectionName, ConfigName.Baudrate, 9600)
This is the function to get a string:
Public Function GetString(ByVal Section As String, ByVal Key As String, ByVal [Default] As String) As String
Dim intCharCount As Integer
Dim objResult As New System.Text.StringBuilder(256)
intCharCount = GetPrivateProfileString(Section, Key, [Default], objResult, objResult.Capacity, strFilename)
GetString = String.Empty
If intCharCount > 0 Then GetString = Left(objResult.ToString, intCharCount)
End Function
where strFilename is a local variable of this class.
And this is the API declaire:
Private Declare Ansi Function GetPrivateProfileString _
Lib "kernel32.dll" Alias "GetPrivateProfileStringA" _
(ByVal lpApplicationName As String, _
ByVal lpKeyName As String, ByVal lpDefault As String, _
ByVal lpReturnedString As System.Text.StringBuilder, _
ByVal nSize As Integer, ByVal lpFileName As String) _
As Integer
You are using GetPrivateProfileStringA instead of GetPrivateProfileStringW.
Since you are using Unicode, you need to use GetPrivateProfileStringW instead.

save images from url

Is it possible to save images using Visual Basic 2008 from URL to my PC?
For example : From www.domain.com/image.jpg to C:\folder\image.jpg
P.S: I need simpliest example of the code, then I will edit is as I need.
Thanks.
Update : I want to know when the code have finished downloading of the image.
This is the simplest way I know.
Dim Client as new WebClient
Client.DownloadFile(Source, Destination)
Client.Dispose
This is superior to using the My.Computer.Network.DownloadFile method per Microsoft's documentation
"The DownloadFile method does not send optional HTTP headers. Some servers may return 500 (Internal Server Error) if the optional user agent header is missing. To send optional headers, you must construct a request using the WebClient class."
There's a simpler way:
My.Computer.Network.DownloadFile(Source, Desination)
Here what i came up with.
Public Function getImgFrmUrl(ByVal url As String, ByVal Optional ImageName As String = "", ByVal Optional DstntnPath As String = "c:\") As String
Dim imgPath = DstntnPath & "\"
Dim name = IIf(ImageName.Length = 0, Guid.NewGuid.ToString, ImageName)
Dim fileExt = Path.GetExtension(url)
Using webClient As WebClient = New WebClient
Const _Tls12 As SslProtocols = CType(&HC00, SslProtocols)
Const Tls12 As SecurityProtocolType = CType(_Tls12, SecurityProtocolType)
ServicePointManager.SecurityProtocol = Tls12
Dim data As Byte() = webClient.DownloadData(url)
If File.Exists(imgPath + name & fileExt) Then File.Delete(imgPath + name & fileExt)
Using mem = New MemoryStream(data)
Using yourImage = Image.FromStream(mem)
If fileExt.ToLower Is ".png" Then
yourImage.Save(imgPath + name & fileExt, ImageFormat.Png)
Else
yourImage.Save(imgPath + name & fileExt, ImageFormat.Jpeg)
End If
End Using
End Using
End Using
Return imgPath & name & fileExt
End Function
create a module and use this function
Public Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Public Function DownloadFile(sURLFile As String, sLocalFilename As String) As Boolean
Dim lRetVal As Long
lRetVal = URLDownloadToFile(0, sURLFile, sLocalFilename, 0, 0)
If lRetVal = 0 Then DownloadFile = True
End Function