I wrote below function to go through a proxy server.
' Thisworkbook::set_proxy
Public Sub set_proxy(ByRef client As MSXML2.ServerXMLHTTP60)
' use_proxy, proxy_server, proxy_user and proxy_password are global valiable.
If Not use_proxy Then Exit Sub
With client
.setProxy 2, proxy_server
.setProxyCredentials proxy_user, proxy_password
End With
End Sub
And, I added Call Thisworkbook.set_proxy(client) just before every client.send in WebDriver.cls.
But, Chrome display authentication dialog for proxy, so can not connect to internet.
Please show me that how to go through a proxy server with SeleniumVBA.
Related
Hi there I have piece of legacy (VS2010) Windows Service code that I have imported into VS2017 and is causing me severe frustration. This code has worked well for about the last 6 years, however when I carry out the install and attempt to start the service the SCM comes back with a timeout error. The OnStart code is as follows:
Protected Overrides Sub OnStart(ByVal args() As String)
'Instaniate the timer for the service
_serviceTimer = New Threading.Timer(New Threading.TimerCallback(AddressOf Tick), Nothing, 60000, 60000)
End Sub
The call back is:
Private Sub Tick(ByVal state As Object)
'Switch off the timer event whilst the code executes
_serviceTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite)
If Not _started Then
Startup()
_started = True
End If
Call ServerProcess()
'Re-enable the timer now that application code has completed
_serviceTimer.Change(_longInterval, _longInterval)
End Sub
I originally had the Startup process in the OnStart method, however removed it as an attempt at resolving this issue, however it has not made any difference. Method Startup is as follows:
Public Sub Startup()
Try
'Source these settings from the local config file
_appDataFolder = Utilities.GetSetting("AppDataRoot")
_configPathMapped = _appDataFolder & Utilities.GetSetting("ConfigPathMapped")
_logPath = _appDataFolder & "\" & utl.GetSetting("LogPath")
'Instaniate the timer for the service - Commented out after moving startup code from OnStart method
' _serviceTimer = New Threading.Timer(New Threading.TimerCallback(AddressOf Tick), Nothing, Timeout.Infinite, Timeout.Infinite)
'Initialise logging architecture
_logger = New aslLog.Logger(_configPathMapped & "nlog.config", _logPath, My.Application.Info.ProductName, My.Application.Info.Version.ToString)
_logger.SendLog("Started PSALERTS Schedule Server Service", NLog.LogLevel.Info, _serviceTimer, _checkInterval, Nothing)
'Determine if the cloned config files exists in the mapped config file folder
'We clone these files to a writable destination to allow us to overcome write restrictions ot the C: drive on the SPEN PTI Desktop model
If Not System.IO.File.Exists(_configPathMapped & "psaservermachine.config") Then
'Clone the app.config file in the config folder as psaservermachine.config
Utilities.CloneFile(_programFileLocation & "PSALERTSScheduleServer.exe.config", _configPathMapped & "psaservermachine.config")
End If
If Not System.IO.File.Exists(_configPathMapped & "nlog.config") Then
'Clone the nlog.config file
Utilities.CloneFile(_programFileLocation & "PSALERTSScheduleServer.exe.config", _configPathMapped & "nlog.config")
End If
'Determine the Oracle TNS Environment
'Check for the existence of the environment variable 'TNS_ADMIN'
If Environment.GetEnvironmentVariable("TNS_ADMIN") IsNot Nothing Then
'If TNS_ADMIN exists then we can continue with the application session
Else
Dim oraTnsPath As String = ""
'If it doesn't exist then we need to determine the Oracle information from the PATH environment variable
oraTnsPath = GetOraTnsPath()
If oraTnsPath <> "" Then
'Then create the TNS_ADMIN environment variable
Environment.SetEnvironmentVariable("TNS_ADMIN", oraTnsPath)
Else
'If no oracle client information exists then raise an error to this effect and exit the app
'informing the user that they need to install the Oracle client in order to use PSALERTS
Beep()
Throw New PSALERTSOracleConfigException(
"PSALERTS Oracle Configuration Error. PSALERTS Did not find a valid Oracle Client." & vbCrLf & vbCrLf &
"Please install a valid Oracle Client and try again." & vbCrLf & vbCrLf &
"If a valid Oracle Client is installed then ensure that the PATH environment variable contains an entry for the Oracle Client." & vbCrLf & vbCrLf &
"For example - TNS_ADMIN=C:\oracle\12.1.0\Client_lite\NETWORK\ADMIN"
)
End If
End If
'Register the application
If Not Registered() Then
'Register the application
Register()
End If
If Registered() Then
'Clean/close any stray Excel processes from previous debug session
If _debugModeOn Then
CleanUpRedundantProcesses("EXCEL", "PSALERTS")
End If
'instantiate fresh excel session
_myXLApp = New Excel.Application
'Get the timer interval settings
_longInterval = CType(utl.GetSettingServerMachine(_configPath, "appSettings", "LongIntervalMillis"), Integer)
_initInterval = CType(utl.GetSettingServerMachine(_configPath, "appSettings", "InitialIntervalMillis"), Integer)
_refreshInterval = CType(utl.GetSettingServerMachine(_configPath, "appSettings", "InitialIntervalMillis"), Integer)
'Re-start the timer with periodic signalling as per the specified check interval
_serviceTimer.Change(_initInterval, _initInterval)
Else
_started = False
End If
Catch ex As Exception
_logger.SendLog("PSALERTS Schedule Server startup failure.", NLog.LogLevel.Error, ex)
Finally
End Try
End Sub
I use a similar technique for a number of similar services and they are running fine. Would appreciate some insight from any Windows Service gurus out there. Oh, I use WiX to carry out the install, again this is a well worn template for a number of similar such applications.
Kind Regards
Paul J.
Core: The very most typical errors:
Config problems: connection strings, faulty paths, etc...
Boot startup problem (good list - from FAQ)
Wrong password / login account when running as a real user with password.
Files missing or runtimes missing.
Permission problems (ACL / NT Privilege missing).
Maybe check this answer before the below.
UPDATE: Maybe have a look at this previous answer. Service startup timing issue. Also check my ad-hoc answer there in the same page.
Debugger: Other than that - nothing like stepping through the code with a debugger. I haven't done that in a long time. Deploy debug binaries and try? Windows 10 now hides messages from services - not sure how that affects debuggers: No more switching to Session 0.
I am not a service guru, but a deployment specialist. I'll just provide some links and see if that helps. Maybe I have not fully understood the whole problem. I tend to focus on the deployment side and not so much development side.
Ideas List / Debugging Check List: These are "ideas lists" for what could be wrong for applications in general - not just services (two first lists are similar - created some time apart):
Crash on launch
Desktop application won't launch
General purpose WiX / MSI links
Yes, these lists are very generic - too large to digest. Just skim the first two I think.
Debugging Tools: Also a reminder of the most useful service debugging tools: Event Viewer, Task Manager, Services.msc, Process Explorer (system internals), The NET command and SC.exe.
Good Service FAQ: https://www.coretechnologies.com/WindowsServices/FAQ.html
Your startup method should fire up a background worker and quickly return to the SCM that it has started. There is a system wide default setting of 30 seconds but honestly a proper service should respond in a few seconds.
Looking though your code, your connection to the database is probably the long pole causing the problem.
I am developing a piece of scientific software in VB.net that I intend to distribute. Part of the application will involve communication with a server (and other clients). For all intents and purposes the communication will be like a chat application.
I have developed the software using sockets, and it works fine when testing at home on my local network. Below is basically how I send messages:
Dim serverIPString as String = "192.168.1.5"
Dim serverPort as long = 65500
dim messageString as String = "Hello"
Dim Client As New System.Net.Sockets.TcpClient(serverIPString, serverPort)
Dim Writer As System.IO.StreamWriter(Client.GetStream())
Writer.Write(messageString)
Writer.Flush()
Writer.Close()
And this is how I listen:
Public Class TCPIPListener
Dim initalised As Boolean = False
Dim port As Long
Dim IP As System.Net.IPAddress
Dim ourListener As TcpListener
Dim ourClient As TcpClient
Dim ourMessage As String
'''''''''''
'' ctors ''
'''''''''''
Public Sub New()
initalised = False
End Sub
'Takes IP and port and starts listeing
Public Sub New(inIP As String, inPort As Long, inExchange As messageExchange)
'Try to set the IP
Try
IP = System.Net.IPAddress.Parse(inIP)
Catch ex As Exception
Exit Sub
End Try
'Set the port
port = inPort
initalised = startListener()
End Sub
'''''''''''''''
'' Listening ''
'''''''''''''''
Private Sub Listening()
ourListener.Start()
End Sub
'starts listener
Public Function startListener() As Boolean
ourListener = New TcpListener(IP, port)
ourClient = New TcpClient()
Dim ListenerThread As New Thread(New ThreadStart(AddressOf Listening))
ListenerThread.Start()
initalised = True
Return True
End Function
'Called from a timer on the form
Public Function tick() As Boolean
If Not initalised Then
Return False
End If
If ourListener.Pending = True Then
ourMessage = ""
ourClient = ourListener.AcceptTcpClient()
Dim Reader As New System.IO.StreamReader(ourClient.GetStream())
While Reader.Peek > -1
ourMessage = ourMessage + Convert.ToChar(Reader.Read()).ToString
End While
messagebox(ourMessage)
End If
Return True
End Function
End Class
Using this approach, every client will be listening for messages sent from the server, and any messages sent will go to the server and be directed to the relevant client - it's a little inefficient but necessary for the way my software works.
The problem is that I am having real trouble getting this to work across the internet. If I send a message to a local IP address it works fine, even from the debugger. If I use a external IP address I get the following:
No connection could be made because the target machine actively refused it XXX.XXX.XXX.XXX:65500"
I have turned on port forwarding with my router and set up the correct port (65500 here) to forward to my PC running the lister (192.168.1.5) for both TCP and UDP. This website it tells me this port is open, and those either side are not.
If I right click on the exe and run as administrator, my antivirus pops up and says it is doing something suspicious when I start the listener (which I guess if anything is encouraging). If I then add my application to the list of exceptions and run it again, then check to see if the port is listening (using this) I find my application listening on the correct port (if I stop the application it is gone). However the client application still gives the same error above. If I use a random IP address rather than the one of the listener I get a different error:
{"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond XXX.XXX.XXX.XXX:65500"}
I suspect I am not taking the correct approach to this. I am fine with most aspects of VB, but have not really tackled this sort of problem before. When it comes to distributing software I really don't want my customers to have to mess around with deep settings to get this application to work. Any help will be immensely useful to me!
Another problem I guess I will face in the future is if multiple clients have the same external IP but different internal IPs (I intend to distribute to universities). Under these circumstances I guess port forwarding will not work.
Thanks very much in advance (and apologies for the long post)!
If you set your server to listen for connections on 192.168.1.5 then it will only allow connections from that specific IP address. The address you give a TcpListener is the IP address which you will accept connections from.
Since the 192.168.1.5 address is internal no one outside your network will be able to connect to your server. Make your server listen to 0.0.0.0 (or the equivalent IPAddress.Any) instead to make it allow connections from anyone.
I'm running a routine in Outlook that will check the "Sent" folder and will look thru public folders to see if emails in "Sent" folder need to be moved to public folder. That's working well.
The problem is that I want this routine to be executed only if Outlook is connected to exchange via the company LAN on Wifi. Reason being that when employees are at home using Outlook, they sometimes don't want that routine to be executed.
So the question being how to detect that Outlook is connected thru company LAN or WIFI?
I've found a way to detect if I'm connected to my company network by using this sub and associated function. For that I try to access a file on the company server. This is not that elegant but it got me that far
Sub TestNetwork()
Dim connected As Boolean
connected = CheckForNetwork()
If connected = False Then
MsgBox ("not connected")
Else
MsgBox ("connected")
End If
End Sub
Function CheckForNetwork() As Boolean
On Error GoTo end
If Len(Dir("\\company_name\company_name\company_name-000\Employee\ _
Employee Name\*.*")) > 0 Then
CheckForNetwork = True
End If
Exit Function
end:
End Function
This will tell me if I'm connected to our company server or not but it won't tell me if it's connected via my home network, a public WiFi spot in an airport or anywhere else.
I need to find out if Outlook is connected via company network or any other connection.
I'll greatly appreciate any help on that matter
Thanks to the suggestion of Sorceri, I found an easy way to retrieve the actual IP adress of a computer. With that I'll be able to detect if the IP adress belongs to my company LAN of if the computer is connected to the Internet via another connection. Inspiration comes frome here: http://www.myengineeringworld.net/2014/12/get-public-ip-local-ip-mac-address-vba.html?m=1 and the final code is as follows
With the following code I first detect if Outlook is online or offline and the I retrieve the IP adress with the GetMyPublicIP function
Sub enligne_horsligne()
'olCachedConnectedDrizzle 600 The account is using cached Exchange code such that headers are downloaded first, followed by the
'bodies and attachments of full items.
'olCachedConnectedFull 700 The account is using cached Exchange mode on a Local Area Network or a fast connection with the Exchange server.
'The user can also select this state manually, disabling auto-detect logic and always downloading full items
'regardless of connection speed.
'olCachedConnectedHeaders 500 The account is using cached Exchange mode on a dial-up or slow connection with the Exchange server, such
'that only headers are downloaded. Full item bodies and attachments remain on the server.
'The user can also select this state manually regardless of connection speed.
'olCachedDisconnected 400 The account is using cached Exchange mode with a disconnected connection to the Exchange server.
'olCachedOffline 200 The account is using cached Exchange mode and the user has selected Work Offline from the File menu.
'olDisconnected 300 The account has a disconnected connection to the Exchange server.
'olNoExchange 0 The account does not use an Exchange server.
'olOffline 100 The account is not connected to an Exchange server and is in the classic offline mode.
'This also occurs when the user selects Work Offline from the File menu.
'olOnline 800 The account is connected to an Exchange server and is in the classic online mode.
Dim myNamespace As Outlook.NameSpace
Dim adresse_IP As String
Dim mpfInbox As Outlook.folder
Set myNamespace = Application.GetNamespace("MAPI")
If (myNamespace.ExchangeConnectionMode = 700 Or myNamespace.ExchangeConnectionMode = 600 Or myNamespace.ExchangeConnectionMode = 700) Then
MsgBox ("Outlook is online")
MsgBox (Environ("userdomain") & "\" & Environ("username"))
Else
MsgBox ("Outlook is offline")
MsgBox (Environ("userdomain") & "\" & Environ("username"))
End If
adresse_IP = GetMyPublicIP()
MsgBox ("The IP adrress is " & adresse_IP)
End Sub
The function GetMyPublicIP is
Function GetMyPublicIP() As String
'source: http://www.myengineeringworld.net/2014/12/get-public-ip-local-ip-mac-address-vba.html?m=1
Dim HttpRequest As Object
On Error Resume Next
'Create the XMLHttpRequest object.
Set HttpRequest = CreateObject("MSXML2.XMLHTTP")
'Check if the object was created.
If Err.Number <> 0 Then
'Return error message.
GetMyPublicIP = "Could not create the XMLHttpRequest object!"
'Release the object and exit.
Set HttpRequest = Nothing
Exit Function
End If
On Error GoTo 0
'Create the request - no special parameters required.
HttpRequest.Open "GET", "http://myip.dnsomatic.com", False
'Send the request to the site.
HttpRequest.Send
'Return the result of the request (the IP string).
GetMyPublicIP = HttpRequest.ResponseText
End Function
My company posts invoices to both Ariba and Oracle Supplier Networks via HTTP POST. We've had an issue where we haven't been able to determine whether it's settings or code.
Below is the code:
Public Function SendMime(pFiles As List(Of String)) As String
'just use the text send option in HTTP connection
If pFiles.Count = 1 And pFiles.Item(0).EndsWith(".xml") Then
Return Send(My.Computer.FileSystem.ReadAllText(pFiles(0)))
End If
Dim Request As Net.HttpWebRequest
Request = DirectCast(Net.WebRequest.Create(GetFirstURL()), Net.HttpWebRequest)
Request.ContentType = "multipart/related;boundary=" & OuterBoundary & ";type=""text/xml"";start=""<" & _CID & ".1>"""
Request.Method = "Post"
Request.KeepAlive = True
WriteRequest(Request, pFiles)
Dim Response As Net.WebResponse
Try
Response = Request.GetResponse()
Dim ResponseStream As Stream = Response.GetResponseStream()
Dim ResponseReader As New StreamReader(ResponseStream)
Return ResponseReader.ReadToEnd()
Catch ex As System.Exception
Return "error: " & ex.Message
End Try
End Function
Private Sub WriteRequest(pRequest As Net.WebRequest, pFiles As List(Of String))
Dim PartCount As Integer = 1
_RequestStream = pRequest.GetRequestStream()
_tempStream = New FileStream("C:\lastMIMEsent.txt", FileMode.Create)
For Each File As String In pFiles
WriteBoundary(OuterBoundary)
If File.ToLower.EndsWith(".xml") Then
GetXMLPart(File, PartCount)
ElseIf File.ToLower.EndsWith(".pdf") Then
GetPDFPart(File, PartCount)
End If
PartCount += 1
Next
WriteTrailer(OuterBoundary)
_RequestStream.Close()
_tempStream.Flush()
_tempStream.Close()
End Sub
The send function is similar to the SendMime function, but with no attachments (cxml only). This code is shared between a Windows Service and a basic GUI test program.
edit: The error I get is: "Unable to connect to host."
Where things get weird:
On the server running the service: Oracle works, Ariba does not, when the service calls the SendMime function.
On the server running the service: Both work, when the GUI utility calls the SendMime function.
On my work station: both work, regardless of whether it is the service or GUI calling the SendMime function
My first thought was Proxy, but both machines are behind the same proxy.
My second thought was Firewall issues, but we disabled the firewall with no success.
We can connect to the address via web browser as well.
We tried with different Active Directory accounts, with no change as well.
Both the service and the GUI utility are running .Net 4.5 (needed for some asynchronous parts of the service). They were not at one point, but upgrading the Utility made no difference.
The only difference i can find, is that my machine runs Windows 7 and the server runs Windows Server R2, but I can find no documentation stating that there should be a difference.
I've been trying to figure this out for a couple weeks, experimenting with different adjustments, and at this point, both I and the server team are out of ideas. Any advice, whether its red flags in my code or just known windows server issues, would be greatly appreciated.
I'm working at a server chat application and I need to get the ip of the computer that's running the server app.
Because you didn't specify if you want an IPv4 or an IPv6 address:
Imports System.Net.NetworkInformation
Module Module1
Sub Main()
Dim networkInterfaces As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
For Each networkInterface As NetworkInterface In networkInterfaces
For Each unicastAddress As UnicastIPAddressInformation In networkInterface.GetIPProperties().UnicastAddresses
Console.WriteLine(unicastAddress.Address)
Next
Next
Console.ReadLine()
End Sub
End Module
As you iterate through the available network interfaces on the computer, there should be something you would know that would identify the one that you want.
Open cmd and type ipconfig. Now look for IPv4