Check for valid connection between frontend and backend Access database - vba

I have an Access database application that I've split into a Frontend and Backend. The backend sits on a shared network drive that all users can access. My issue is that when a user launches the frontend of this app, and they don't have a connection to the backend because the shared drive may not have been mounted locally, the initial form to be displayed when the app is launched, doesn't open and leaves the user questioning what's going on. I already have code to check if the backend is connected although for some reason, when it isn't connected the intro screen form never is displayed and the access app just sits there
Private Sub Form_Open(Cancel As Integer)
Dim strBackEndPath, LResult As String
Dim i, j, lenPath As Integer
'initialize variable status to 0
Me.BEDB_Status = 0
'define what to check in backend database
strBackEndPath = CurrentDb.TableDefs("VersionInfo-Available").Connect
' Now remove the datebase & password prefix
j = InStrRev(strBackEndPath, "=") + 1
strBackEndPath = Mid(strBackEndPath, j)
'Checking access to Backend database files...
Me.MessageText = "Checking access to Backend database files..."
On Error Resume Next
LResult = Dir(strBackEndPath)
'Set status to Length of LResult
Me.BEDB_Status = Len(LResult)
'Check length of BEDB_Status, if greater than 0, backend is connected. If 0, backend is not connected.
If Me.BEDB_Status > 0 Then
'length is greater than 0 so continue opening the app
DoCmd.OpenForm "IntroScreen"
Else
'length is 0 so backend is not connected. Alert user and quit the app
Me.MessageText = "The database isn't currently accessible. Program will now exit. Please ask the support team for assistance"
DoCmd.Quit acQuitSaveNone
End If
End Sub

It may be simpler and much faster to attempt opening one of the linked tables and ignore the error:
Public Function IsLinkedTable(ByVal TableName As String) As Boolean
Dim LinkOk As Boolean
On Error Resume Next
LinkOk = (DCount("*", TableName) >= 0)
IsLinkedTable = LinkOk
End Function
And do use the OnLoad event of the form as this allows the form to open.

Implemented Gustav's suggestion to use the On Load event rather than the On Open event along with his IsLinkedTable function and it's working great.
Thanks Gustav.

Related

win32com and SAP-GUI

My SAP-GUI has Scripting installed and Scripting is enabled.
Like in this screenshot:
In this Introduction to SAP GUI Scripting in "Step 2: Setup your SAP System" you need to call RZ11.
I don't have permissions to call RZ11.
Is there a way to detect this (sapgui/user_scripting on or off) via a script?
At the moment I use below code, but the list of connections is always empty:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
sapgui = win32com.client.GetObject("SAPGUI")
system = query.get('system')
client = query.get('mandant')
session = False
application = sapgui.GetScriptingEngine
seen = []
for i_conn in range(0, application.Connections.Count):
seen.append('i_conn=%s session_count=%s' % (i_conn, application.Connections.Item(i_conn).Sessions.Count))
for i_sess in range(0, application.Connections.Item(i_conn).Sessions.Count):
session_info = application.Connections.Item(i_conn).Sessions.Item(i_sess).Info
system_of_session = session_info.SystemName
client_of_session = session_info.Client
if system_of_session == system and client_of_session == client:
connection = application.Connections.Item(i_conn).Children(i_sess)
session = connection.Children(i_sess)
break
seen.append('system=%s client=%s' % (system_of_session, client_of_session))
if session:
break
else:
info_popup('You are not logged into system %s in Client %s! Seen:\n%s' % (
system, client, '\n'.join(seen)))
return
When you don't have sufficient priviledges in sap, the fact that you can't connect is a pretty good indication that the user does not have scripting enable (assuming the user has a active sap session running), other wise you could just test with 'session.findById("wnd[0]/usr/tblSAPLCMDITCTRL_3500").getAbsoluteRow(3).selected = true' and check for errors.
Also, I suggest you factor in "SAPGUISERVER' in your sapgui = win32com.client.GetObject("SAPGUI") connection if "SAPGUI" fails.
As I know sapgui/user_scripting is a system-level = application level setting but not a user-level. So, if you have no permissions to run RZ11 tcode then you have no opportunity or permissions to read applicaton server settings and, of course, no permissions to change it. You have to contact your basis administrator to verify this application settings with him.
You see, SAP limited scripting abilities due to possible vulnerability, that's why scripting support should be turned on both on client side and on application server side.
If you have access to interrogate the registery you could write a cutom function to check SAPGUI is installed and flagged e.g:
Public Sub CheckKey()
Const cRegKey As String = "HKEY_CURRENT_USER\Software\SAP\SAPGUI Front\SAP Frontend Server\Security\UserScripting"
If CheckSAPGUI(cRegKey) Then
MsgBox "User has SAPGUI installed and initialized", vbOKOnly Or vbInformation, Application.Name
Else
MsgBox "User does not have SAPGUI installed", vbOKOnly Or vbCritical, Application.Name
End If
End Sub
Public Function CheckSAPGUI(RegKey As String) As Boolean
Dim rtn As Variant
On Error Resume Next
rtn = vbNullString
With CreateObject("wscript.shell")
rtn = .RegRead(RegKey)
End With
If Len(rtn) = 0 Then
CheckSAPGUI = False
ElseIf Val(rtn) <> 1 Then
CheckSAPGUI = False
Else
CheckSAPGUI = True
End If
On Error GoTo 0
End Function
You should be able to modify the MsgBox comments to better suit how you want to interact with your end user

how to identify application instance name along with its user in vb.net 3.5?

I am using the below code to identify instance of the application also if we need to check that which user is using this application what will be the code for it?
Function PrevInstance() As Boolean
If Ubound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
Return True
Else
Return False
End If
End Function
My requirement is if same user tries to open the application then it should display pop up message like "application already opened".
Please advice...
abhay
Thanks a lot guys.... solution on my problem as follows:
> Function PrevInstance() As Boolean
> If UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName))
> > 0 Then
> Dim CurUser As Boolean = GetProcessOwner(Diagnostics.Process.GetCurrentProcess.ProcessName)
> Return CurUser
> Else
> Return False
> End If
> End Function
Function GetProcessOwner(ByVal ProcessName As String) As Boolean
Dim boolVal As Boolean
Dim CurUserName As String
Dim CountInstance As Integer
CountInstance = 0
CurUserName = System.Environment.UserName
Dim selectQuery As SelectQuery = New SelectQuery("Select * from Win32_Process Where Name = '" + ProcessName + ".exe' ")
Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(selectQuery)
Dim y As System.Management.ManagementObjectCollection
y = searcher.Get
For Each proc As ManagementObject In y
Dim s(1) As String
proc.InvokeMethod("GetOwner", CType(s, Object()))
Dim n As String = proc("Name").ToString()
If n = ProcessName & ".exe" Then
If s(0) = CurUserName Then
CountInstance = CountInstance + 1
If CountInstance > 1 Then
boolVal = True
End If
End If
End If
Next
Return boolVal
End Function
I have called PrevInstance() in my Form_Load() and its working perfectly.
PrevInstance Property
Returns a value indicating whether a previous instance of an application is already running.
Syntax
object.PrevInstance
The object placeholder represents an object expression that evaluates to an object in the Applies To list.
Remarks
You can use this property in a Load event procedure to specify whether a user is already running an instance of an application. Depending on the application, you might want only one instance running in the Microsoft Windows operating environment at a time.
Note Since a computer running Windows NT can support multiple desktops, if you use a component designed to work with distributed COM, it can result in the following scenario:
A client program in a user desktop requests one of the objects the component provides. Because the component is physically located on the same machine, the component is started in the user desktop.
Subsequently, a client program on another computer uses distributed COM to request one of the objects the component provides. A second instance of the component is started, in a system desktop.
There are now two instances of the component running on the same NT computer, in different desktops.
This scenario is not a problem unless the author of the component has placed a test for App.PrevInstance in the startup code for the component to prevent multiple copies of the component from running on the same computer. In this case, the remote component creation will fail.
Send feedback to MSDN.Look here for MSDN Online resources.
Session
The above tells you if it's already running. This tells you what session. An interactive user is always session1 on Vista and later. 0 for XP and earlier.
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
For Each objItem in colItems
msgbox objitem.name & " PID=" & objItem.ProcessID & " SessionID=" & objitem.sessionid
Next
PS
The rules for single instance programs is just before you exit you switch windows to the previous instance.
PPS
Due to problems introduced by 32 bit computing previnstance (Win32's one rather than VB's) becomes less meaningful. The common way to do this now is to open and lock a file on startup (Windows also has memory constructs you can use such as mailslots, pipes, etc). If a program can't lock then another is already running.

Bloomberg API: How to check wether connection works?

I am implementing a tool which relies on Bloombergs blpapilib2, which is the Bloomberg API COM Lib 3.5.
Before giving my user access to any refresh-data functionality, I want to make sure that the connection works. My approach so far:
Check wether the library is available and linked. Basically a loop through references does the job.
Open a connection with session.Start() . I was hoping to get an error here, but it won't give me one. Thus, step 3.
Request some data and verify it (make sure its not empty)
Surporisingly, I cannot reliably reproduce getting an empty result. I expected my session relies on a user being looged into the terminal. It seems I was wrong; even if I log out, my request will be handled and return correct data.
I can imagine two scenarios:
some background caching in the bbcom-Server
an alternative authentication method is used
I have two questions:
Q1. What is the best way to make sure a user will be able to download data?
Q2. How can I verify whether a connection has been established successfully and a user is authenticated?
Thanks.
To "cut" the connection, you need to log out and log in on a different machine. If you simply log out the feed is still available using the API.
This is how I test the connection - I think it works fairly well. I have a BloombergWrapper class that handles all the low level stuff of communicating with the API and it has the following functions:
Private pSession As blpapicomLib2.Session
Private pService As blpapicomLib2.Service
Private Sub Class_Initialize()
Dim locStatusBar As Variant
Dim locBbResult As Variant
On Error GoTo error_handler
If Application.StatusBar = False Then locStatusBar = False Else locStatusBar = Application.StatusBar
Application.StatusBar = "Connecting to Bloomberg..."
Set pSession = New blpapicomLib2.session
pSession.Start
pSession.OpenService ("//blp/refdata")
Set pService = pSession.getService("//blp/refdata")
Application.StatusBar = locStatusBar
Exit Sub
error_handler:
If InStr(Err.Description, "timeout") Then
Call MsgBox("A Bloomberg timeout has occured. Make sure you are logged on your terminal.", vbCritical + vbOKOnly, "Bloomberg error...")
End If
If locStatusBar <> "" Then Application.StatusBar = locStatusBar
End Sub
Private Sub Class_Terminate()
pSession.Stop
Set pSession = Nothing
End Sub

How do I check if an ftp server is online and get the error that it generates if it is not connected?

I am new to programming in vb.net. I have come a long ways in my development and understanding of vb, but there is one hurtle I can not seem to fix. I am hosting an ftp server on my pc and I am making an app for it to connect to my server and download files. The problem with all the sample code is that everyone ASSUMES the server WILL be ONLINE. My pc may not be running 24/7 and I also may not have the ftp service running.In the first case it shouldnt even register that it is connected. In the second case, it WILL say that is connected b/c the pc is on, but it will return that the machine ou are trying to connect to is actively refusing the connection. Is there a way to TRULY check if the program is indeed connected to the server WITHOUT generating a bunch of Exceptions in the debugger? All I want is a call like:
Dim ftponline As Boolean = False 'Set default to false
ftponline = checkftp()
If ftponline Then
'continue program
Else
'try a different server
End If
So it would be a function called checkftp that returns a boolean value of true or false.
Here is my info:
Using Visual Studio 2010 Pro
Using .Net framework 4
Can anyone help?
Thanks!
I have tried the rebex ftp pack as well as the Ultimate FTP Pack.
Here is the updated code:
Public Function CheckConnection(address As String) As Boolean
Dim logonServer As New System.Net.Sockets.TcpClient()
Try
logonServer.Connect(address, 21)
Catch generatedExceptionName As Exception
MessageBox.Show("Failed to connect to: " & address)
End Try
If logonServer.Connected Then
MessageBox.Show("Connected to: " & address)
Return True
logonServer.Close()
Else
Return False
End If
End Function
Public Sub ConnectFtp()
types.Clear()
models.Clear()
ListBox1.Items.Clear()
ListBox2.Items.Clear()
TextBox2.Clear()
Dim request As New Rebex.Net.Ftp
If CheckConnection(*) Then
Dim tempString As String()
request.Connect(*)
request.Login(*, *)
request.ChangeDirectory("/atc3/HD_Models")
Dim list As Array
list = request.GetNameList()
Dim item As String = ""
For Each item In list
tempString = item.Split(New Char() {" "c})
If types.Contains(tempString(0)) = False Then
types.Add(tempString(0))
End If
If models.Contains(item) = False Then
models.Add(item)
End If
Next
request.Disconnect()
request.Dispose()
ElseIf CheckConnection(*) Then
request.Connect(*)
request.Login(*, *)
request.ChangeDirectory(*)
Dim list2 As Array
list2 = request.GetNameList()
Dim item2 As String = ""
Dim tempString2 As String()
For Each item2 In list2
MessageBox.Show(item2)
tempString2 = item2.Split(New Char() {" "c})
If types.Contains(tempString2(0)) = False Then
types.Add(tempString2(0))
End If
If models.Contains(item2) = False Then
models.Add(item2)
End If
Next
request.Disconnect()
request.Dispose()
End If
End Sub
No matter what I do, the second server will not connect. I even put a messagebox to show what items were being returned in the second server, but there are no messageboxes apearing when I run the program with my server offline. Is there anyone who can help?
If your code is designed with proper exception catching, it shouldn't be generating a "bunch" of exceptions. The first exception you catch should be your indication that the connection failed and your code should cease attempting to communicate at that point. If for some reason you really need to check the connectivity before attempting the FTP connection, you should be able to simply attempt to synchronously open a TCP socket to the FTP server's port. If that works, it's up and running.
You could simply open a socket to the server's IP address on Port 21 (assuming default FTP port).
I'm not much of a VB.Net programmer, but here's a link to sample code:
http://vb.net-informations.com/communications/vb.net_Client_Socket.htm
If you can establish the socket connection, you know that something is listening on that port (though you have not yet proven it's an FTP server, or that it will accept your login credentials...).
If you wish to simply avoid exceptions in the debugger, you could place the connection code in a method and apply the DebuggerHidden attribute to that method.

Check for active internet connection

Wrote a small app that accesses a bunch of search websites and puts the results in a word document, which gets run a few hundred times a day.
It saves individual search results in a number of local folders so the next time those words are searched, it grabs them locally instead of loading the website again.
This works fine - even though it's not quick. People are impressed because until a few weeks ago they did this manually by literally loading up six different search websites, searching, and then copying and pasting the results in a word document.
However, our Office's internet is unreliable, and has been down the last half a day. This has meant about 400 bad searches have been saved in the local folders, and inserted into the final documents.
When a person was searching they could tell if the internet was broken and they would do their searches later. Obviously, though, this app can't tell, and because I'm not using APIs or anything, and because I am limited to using the VBA environment (I'm not even allowed MZ tools), I need to find some way to check that the internet is working before continuing with the program flow, without relying on too many references, and preferably without screenscraping for the phrase "404 Page Not Found".
I'm not very familiar with VB, and VBA is ruining me in so many ways, so there's probably some easy way to do this, which is why I'm asking here.
Appreciate any help.
Obviously, your problem has many levels. You should start by defining "connected to the internet", and go on with developing fallback strategies that include not writing invalid files on failure.
As for the "am I connected" question, you can try tapping into the Win32 API:
Private Declare Function InternetGetConnectedState Lib "wininet.dll" _
(ByRef dwflags As Long, ByVal dwReserved As Long ) As Long
Public Function GetInternetConnectedState() As Boolean
GetInternetConnectedState = InternetGetConnectedState(0&,0&)
End Function
Though depending on your network setup (proxy/NAT/firewall restrictions etc.), Windows might have a different opinion about this than you.
Trying to GET the pages you are interested in, checking on the return status in the HTTP headers (gateway timeout, 404, whatever you expect to happen when it "doen't work) might also be a way to go.
You could use MSXML library & use XMLHttpRequest class to check for things
e.g.
On Error Resume Next
Dim request As MSXML2.XMLHTTP60
request.Open "http://www.google.com"
request.Send
Msgbox request.Status
The status will give you HTTP Status code of what happened to the request.
You might have to do some more checks, depending on your scenario.
Hope that helps.
Use the following code to check for internet connection
first anable XML v6.0 in your references
Function checkInternetConnection() As Integer
'code to check for internet connection
'by Daniel Isoje
On Error Resume Next
checkInternetConnection = False
Dim objSvrHTTP As ServerXMLHTTP
Dim varProjectID, varCatID, strT As String
Set objSvrHTTP = New ServerXMLHTTP
objSvrHTTP.Open "GET", "http://www.google.com"
objSvrHTTP.setRequestHeader "Accept", "application/xml"
objSvrHTTP.setRequestHeader "Content-Type", "application/xml"
objSvrHTTP.Send strT
If err = 0 Then
checkInternetConnection = True
Else
MsgBox "Internet connection not estableshed: " & err.Description & "", 64, "Additt !"
End If
End Function
Unfortunately, this is a bit of a difficult question to answer for a couple of reasons:
How do you define a non-working internet connection? Do you check for a valid IP address? Do you ping out? How do you know that you have permissions to check these things? How do you know that the computer's firewall/antivirus isn't causing wonky behavior?
Once you've established that the connection is working, what do you do if the connection drops mid-operation?
There are probably ways to do what you want to do, but a lot of "devil's in the details" type things tend to pop up. Do you have any way to check that the saved search is valid? If so, that would probably be the best way to do this.
Building on shakalpesh's answer and the comments to it, there are (at least) two ways to get the web page into Word without parsing the XML returned by the XMLHTTP60 object.
(NB the HTTP status code of 200 indicates that "the request has succeeded" - see here)
write the XMLHTTP60.ResponseText out to a text file and then call Documents.Open on that text file
If (xhr.Status = 200) Then
hOutFile = FreeFile
Open "C:\foo.html" For Output As #hOutFile
Print #hOutFile, xhr.responseText
Close #hOutFile
End If
// ...
Documents.Open "C:\foo.html"
This has the disadvantage that some linked elements may be lost and you'll get a message box when the file opens
check the URL status with the XMLHTTP60 object and then use Documents.Open to open the URL as before:
If (xhr.Status = 200) Then
Documents.Open "http://foo.bar.com/index.html"
End If
There is a slight chance that the XMLHTTP60 request could succeed and the Documents.Open one fail (or vice versa). Hopefully this should be a fairly uncommon event though
I found most answers here and elsewhere confusing or incomplete, so here is how to do it for idiots like me:
'paste this code in at the top of your module (it will not work elsewhere)
Private Declare Function InternetGetConnectedState Lib "wininet.dll" (ByRef dwflags As Long, ByVal dwReserved As Long) As Long
Private Const INTERNET_CONNECTION_MODEM As Long = &H1
Private Const INTERNET_CONNECTION_LAN As Long = &H2
Private Const INTERNET_CONNECTION_PROXY As Long = &H4
Private Const INTERNET_CONNECTION_OFFLINE As Long = &H20
'paste this code in anywhere
Function IsInternetConnected() As Boolean
Dim L As Long
Dim R As Long
R = InternetGetConnectedState(L, 0&)
If R = 0 Then
IsInternetConnected = False
Else
If R <= 4 Then IsInternetConnected = True Else IsInternetConnected = False
End If
End Function
'your main function/calling function would look something like this
Private Sub btnInternetFunction_Click()
If IsInternetConnected() = True Then
MsgBox ("You are connected to the Internet")
'code to execute Internet-required function here
Else
MsgBox ("You are not connected to the Internet or there is an issue with your Internet connection.")
End If
End Sub
This is what I use. I prefer it because it doesn't require any external references or DLLs.
Public Function IsConnected()
Dim objFS As Object
Dim objShell As Object
Dim objTempFile As Object
Dim strLine As String
Dim strFileName As String
Dim strHostAddress As String
Dim strTempFolder As String
strTempFolder = "C:\PingTemp"
strHostAddress = "8.8.8.8"
IsConnected = True ' Assume success
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("Wscript.Shell")
If Dir(strTempFolder, vbDirectory) = "" Then
MkDir strTempFolder
End If
strFileName = strTempFolder & "\" & objFS.GetTempName
If Dir(strFileName) <> "" Then
objFS.DeleteFile (strFileName)
End If
objShell.Run "cmd /c ping " & strHostAddress & " -n 1 -w 1 > " & strFileName, 0, True
Set objTempFile = objFS.OpenTextFile(strFileName, 1)
Do While objTempFile.AtEndOfStream <> True
strLine = objTempFile.Readline
If InStr(1, UCase(strLine), "REQUEST TIMED OUT.") > 0 Or InStr(1, UCase(strLine), "COULD NOT FIND HOST") > 0 Then
IsConnected = False
End If
Loop
objTempFile.Close
objFS.DeleteFile (strFileName)
objFS.DeleteFolder (strTempFolder)
' Remove this after testing. Function will return True or False
MsgBox IsConnected
End Function
I encourted this same problem and after googling a lot, I realized there was a simpler way to do it... It requires the user to enable the Microsoft Internet Explorer Controlers library, but that is all. The idea is that your code navigates to a website (in this case google), and after getting the webpage document (HTML). puts a value in the search box.
Sub Test1()
On Error GoTo no_internet 'Error handler when no internet
Dim IE As New SHDocVw.InternetExplorer
IE.Visible = False 'Not to show the browser when it runs
IE.navigate "www.google.com" 'navigates to google
Do While IE.ReadyState <> READYSTATE_COMPLETE 'loops until it is ready
Loop
'Here It gets the element "q" from the form "f" of the HTML document of the webpage, which is the search box in google.com
'If there is connection, it will run, quit and then go to the msgbox.
'If there is no connection, there will be an error and it will go to the error handler "no_internet" that is declared on top of the code
IE.document.forms("f").elements("q").Value = "test"
IE.Quit
MsgBox "Internet Connection: YES"
Exit Sub
no_internet:
IE.Quit
MsgBox "Internet Connection: NO" ' and here it will know that there is no connection.
End Sub