Vb.Net Detect if application server is down - vb.net

I have developed a .Net application that I want to share to users through shared file in the LAN that is managed through a Domain server. When the server is up and running its fine but when the server is shut down an error comes. I have access to sql server database in that server. When server is shut down it gives a fatal error and application stops. How to detect the error of server being down?
I am connecting to the server through the following code:
Dim sql As String
Dim daCourseMaster As SqlDataAdapter
Try
sqlConn = New SqlConnection(connString)
sqlConn.Open()
sql = " ... "
daCourseMaster = New SqlDataAdapter(sql, sqlConn)
daCourseMaster.Fill(dsDataset, "table")
dvRegister = New DataView
dvRegister = dsDataset.Tables("courseRegisters").DefaultView
dgvCourseRegister.DataSource = dvRegister
Catch ex As Exception
MsgBox(Err.Description)
End Try
Now there might be different reasons why user can not login to the server: either the server name is wrong or user name or password is wrong or thebserver might be shut down! How to differentiate between these reasons to let the user know what might be the reason to failed login?

Use this code before the code that do the sharing (if the code in a Sub):
If Not My.Computer.Network.Ping(" You Server Name or Server IP") Then Exit Sub
or (if the code in a Function):
If Not My.Computer.Network.Ping(" You Server Name or Server IP") Then Exit Function

Lets say, you need to query your database. When you open connection and then when you execute your query, use Try-Catch Block and intercept SqlException. It has different codes, so you can test it for connectivity -related codes
Try
Using conn as new SqlConnection(...)
conn.Open()
....
End Using
Catch (connEx as SqlException)
' sql - related error handling
Catch (ex as Exception)
' here handle all other exception
End Try
this way, you can let user know that connection has lost and "try again later" or something like this

Related

Login failed for user 'user' VB.NET app and SQL connection

please see SQL Management Screen Shot Here
I am getting:
system.data.sqlclient.sqlexception: ' login failed for user 'public_user'.'
when I run my application on VB.NET. Please see the link to check settings on my SQL management studio. This application was running flawlessly previously, however I swapped my HDD to SSD and reinstalled SQL and Visual Studio. Since then I am failing to login as public_user.
I ran a query on SQL as public_user and I am not getting any error message. When I run the application, it does connect to SQL on the app, but it fails to load table1 on datagridview.
I've put tableadapter at the beginning on the mainform, at the end, under sqlconnection1.open, basically any possible places, however I am still getting the same error.
The source code is below, please help me to find the solution:
VB.NET
Microsoft SQL Server 2008 R2
Windows 10 OS
Timer1.Enabled = True
Dim sqlconnection1 As New SqlConnection("server = xxx-xxx-xxx;user id=public_user; password=xxxxxx; Trusted_Connection=True; connection timeout=5")
Dim cmdsql As New SqlCommand
cmdsql.CommandText = "SELECT * FROM [LM2].[dbo].[Table_1]"
cmdsql.CommandType = CommandType.Text
cmdsql.Connection = sqlconnection1
Me.Table_1TableAdapter.Fill(Me.LM2DataSet2.Table_1)
Try
sqlconnection1.Open()
If ConnectionState.Open Then
MsgBox("Connected To SQL")
Else
MsgBox("Failed To Connect SQL")
End If
Catch ex As DataException
MessageBox.Show(ex.Message)
End Try
i've found the solution. When i copied SLN from the old HDD and transferred to SSD, for some reason it automatically deleted the ID and password on ConnectionString settings. I've entered those details on main settings and it is working fine. I had in total 5 SQL Databases which was connecting to my App, and all of them were using same login details for public_user. when i enter credentials it worked for all SQL databases.

How can I allow multiple users to access/edit a microsoft access database?

Now I know right off the bat that Microsoft access isn't the ideal client for multiple users accessing it but it's the only one I've got right now. I have built a small program as a sort of inventory management system. There are currently three users that will be using it regularly and at the same time. One issue I am running into with this is that sometimes the database will not be accessible and will give an error stating that the file is already in use by "so and so" user. The other issue is that I'm getting a similar error every now and then where it states "The database has been placed in a state by user on machine that prevents it from being opened or locked". I am connecting to the database through an ACE OLEDB connection using the line below
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"
I have also changed some of the settings in the actual access database such as:
Enable all macros
Add the folder the database is in to the trusted locations list
Confirm that the database is set to open in shared mode by default
I don't know if there is something small I've missed or a setting I need to change but as of yet, the problem is still persisting.
Below is an example of how I am using the database. I am using string based SQL commands but am not too familiar with DataSet/DataTable/etc. items, so I may be doing something incorrectly.
'close connection from any previous session
con.Close()
'clear dataset so as not to append data
ds.Clear()
'Select SQL query that selects ALL records from a table
Dim str As String = "SELECT * FROM " & "[" & table & "]" & ""
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"
'use try catch statement to open the connection
Try
con.Open()
Catch ex As Exception
MsgBox(Convert.ToString(ex))
End Try
'use try catch statement to add a table (dt) to the dataset (ds) in order to store values
Try
ds.Tables.Add(dt)
Catch ex As Exception
End Try
'create new dataadapter object using the sql string from above and the connection created above
da = New OleDbDataAdapter(str, con)
'create new command builder in order to excecute the SELECT SQL statement using the dataadapter created (da)
'specify prefix and suffix for cb
Dim cb = New OleDbCommandBuilder(da) With {
.QuotePrefix = "[",
.QuoteSuffix = "]"
}
'use try catch statement to fill the datatable (dt) using the dataadapter (da)
Try
da.Fill(dt)
Catch ex As Exception
MsgBox(Convert.ToString(ex))
End Try
'set the datasource of the datagridview to the datatable
dgv.DataSource = dt.DefaultView
'close the connection to the database
con.Close()
Go to your Back-End Access DB file. File > Options > Client Settings. For your Use Case No Locks should be fine, but Edited record setting will work as well if you need it
but its [sic] the only one I've got right now
Actually, it's not.
Have a look at SQL Server Compact. It's free, it's small and it handles multiple users with aplomb.
You can add all the references you need using NuGet.

Errors With SQLite and VB.net when reading database

I seem to be receiving random error messages when trying to read queries from a SQLite DB stored on a network drive. On my development machine, I rarely ever get an error, but users are reporting random errors such as:
Unable to open database. File is encrypted or is not a database
Database disk image is malformed
Or it just doesn't return any data.
My code looks like such:
Private Sub LoadStoreCalls()
Dim tmpID As String
Dim QryString As String
Dim SQLconnect As New SQLite.SQLiteConnection()
SQLconnect.ConnectionString = "Data Source=" & SpiceWorksPath & ";New=False;Compress=True;Read Only=True;"
Try
'Open a connection to the database
SQLconnect.Open()
'Get StoreCode
tmpID = Mid(StoreCode, 2) & "-" & StoreName
QryString = "SELECT id, summary, status, c_location, c_store_device FROM tickets WHERE status = 'open' AND c_location = '" & tmpID & "'"
Dim ExQry As New SQLiteCommand(QryString, SQLconnect)
ExQry.CommandType = CommandType.Text
Dim da As New SQLiteDataAdapter(ExQry)
dasSpice.Clear()
da.Fill(dasSpice, "Calls")
SQLconnect.Close()
Catch ex As Exception
If SQLconnect.State = ConnectionState.Open Then SQLconnect.Close()
MsgBox(ex.Message)
End Try
End Sub
The problem is that my application relies on this data being returned to populate additional entries of a datagridview control, and because I cannot replicate this error on my development machine using debug, I cannot find where the fault is occurring.
If the user gets one of these errors, they usually keep trying to run the query and eventually it will work. Or they just exit my application and go back in and then it seems to work for a while. The errors are random and not always from running the same query.
I'm assuming it's due to an issue talking to an SQLite DB on a shared drive, but I can't find any information regarding setting timeouts. I also can't work out how to 'catch' the error because I can't replicate it myself. I have tried adding logging details to the Catch event handler, but it simply just returns me the error message (above) in the logs.
Any help would be greatly appreciated.
Thanks
After many hours of troubleshooting and researching I found that SQLite does not play well with remote connections. Not only was it causing errors in my application, it was also throwing errors in the parent application.
My alternative was to write an application to query the database that ran locally on the SQLite machine. This fixed all of my issues.
For anyone interested...

How do I resolve "ODBC-connection fail"

My Program is "Searching Employee" Use VB web application in Visual Studio 2008
and I use Database in Microsoft Access
I program it in my computer it work 100%. But When I move the project to other computer for upload to server, it have error
ODBC--connection to 'SQL ServerWDT02418\SQLEXPRESS' failed.
WDT02418 is my Computer's name. But I run the project in other computer.
I use the Database connection like this
Function CountEmpData(ByVal EN As String, ByVal Area As String, ByVal Product_type As String) As Integer
Dim CounterEmpData As Integer
Try
Dim ole As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\PROJECT_WD\e-OJT_Project6\Database\Employee.mdb")
ole.Open()
Dim sqlCommand As String = "SELECT COUNT(*) AS 'Counter' FROM Employee WHERE (Emp_ID LIKE '%" + EN + "%') AND (Area LIKE '%" + Area + "%') AND (Product_Type LIKE '%" + Product_type + "%')"
Dim myCommand As New OleDbCommand(sqlCommand, ole)
Dim myReader As OleDbDataReader = myCommand.ExecuteReader()
While myReader.Read()
CounterEmpData = myReader.GetInt32(0)
End While
myReader.Close()
ole.Close()
Catch ex As Exception
End Try
Return CounterEmpData
End Function
It alert error at line
Dim myReader As OleDbDataReader = myCommand.ExecuteReader()
Someone please help me!!
There's nothing computer-specific in the code above, apart from the location of the Access file, but the absence of that wouldn't produce the error above. So I think the problem must lie in your .mdb database, and I suspect the issue is that it contains tables that are linked to a SQL Server which only code running on your machine can get to.
I would troubleshoot this by using the Microsoft Access UI to open the access database on one of the other computers, opening the Employee table and seeing if you still get an error. If you do, you'll know that it's the Access database that's at fault rather than your code. I would guess at this point that remote connections are not set up on SQL Server Express (see here to find out how to enable remote connections), or some firewall rule on your machine is preventing other machines from connecting to the instance of SQL Server Express, so I'd open Windows Firewall and allow inbound traffic on the port that SQL Server Express is listening on, or (better) move the SQL Server from your local machine to a dedicated development server.

Unable to execute SQL command in windows service

I'm working on creating a windows service that will send emails to a customer when they are within a month of having their submission expire. I'm using vb.net in Visual Studios 2008
Because it's a windows service it's very difficult to debug. Trying to narrow down my error I created a "sendDebugEmail" method that sends me an email if it gets to a certain line. The emails never make it past "dr = cmd.ExecuteReader()"
I'm wondering what I am doing wrong. My SQL statement should work fine. I've tested it in my SQL server database.
I've created a dummy_database that I just made in sql server as well. I added an INSERT sql statement for the dummy table i have in there just to see if i could actually access a database. All the table takes in is the line number and time it was sent. When I run my windows service that database updates just fine.
Any help would be appreciated. Thanks
Dim conn As New SqlConnection(connString2)
sendDebugEmail("134")
SQL = "Select email FROM _Customer WHERE custID in (SELECT custID FROM _OnlineCustomer WHERE ExpirationDate <= '6-20-12' AND ExpirationDate >= '6-10-12')"
Dim cmd As New SqlCommand(SQL, conn)
sSubject = "hello"
sBody = "This is test data"
Dim dr As SqlDataReader
sendDebugEmail("143")
Try
dr = cmd.ExecuteReader() // This is were it stops
sendDebugEmail("147")
While dr.Read
sendDebugEmail("152")
Try
LogInfo("Service woke up")
Dim i As Integer = 0
' Prepare e-mail fields
sFrom = "test#gmail.com"
sTo = "test1#gmail.com"
sCc = "test2#gmail.com"
Dim oMailMsg As MailMessage = New MailMessage
oMailMsg.From = sFrom
oMailMsg.To = sTo
oMailMsg.Cc = sCc
' Call a stored procedure to process the current item
' The success message
oMailMsg.Subject = sSubject + "(Success)"
oMailMsg.Body = sBody + "Email has been sent successfully."
' Send the message
If Not (oMailMsg.To = String.Empty) Then
SmtpMail.Send(oMailMsg)
End If
Catch obug As Exception
LogEvent(obug.Message)
Finally
End Try
End While
Catch ex As Exception
Finally
dr.Close()
cmd.Dispose()
conn.Close()
conn.Dispose()
End Try
End Sub
/////////////////////////////////////////////////////////////////////////////////
Problem Solved: I set up my connection but I never opened it.
I needed conn.open()
The thing that helped me most was adding this code into my last catch statement:
sendDebugEmail(ex.Message & vbcrlf & ex.stackTrace)
It send me an email of the stackTrace and made it very easy to debug
Are you trapping and swallowing exceptions? If you are, stop. Let exceptions service crash the service: the exception will be logged in the Event log. The only exceptions you should trap are those you can actually recover from (though its valid to catch the exception, log it and rethrow it via throw;).
Have you instrumented your code with log4net (http://logging.apache.org/log4net/), or something similar? You should be, especially for a daemon like a Windows service — how else are you (or operations) going to diagnose problems with the service when the occur (as they will).
Edited to note:
You should be using using statements: all those ADO.Net objects are IDisposable. It makes for cleaner code.
Consider using a SqlDataAdapter to fill a DataTable or DataSet with your results set. The pattern you're using:
read a row from SQL
while read was successful
send an email
read a row from SQL
will ultimately lead to blocking in your database. Talking to a mail server has the potential for a high latency. If the mail server doesn't answer, or you have network congestion, or any of a number of other reasons, you're going to be left hanging until the mail is sent or an exception is thrown due to timeout. And your SQL Query is going to be sitting there with read locks on the table and indices from which you're reading data, blocking people attempting to do updates, inserts or deletes. Your production DBAs will be...vexed. You want to keep your locks moving and get the locks released as quick as you can.
If you are sure about your code (with no exceptions) i think you should check the authentication you are using to connect the SQL server(inside the connection string within the app.config file/inline code of the windows service).
If you are using SQL authentication for this (check the connection string for user name sa and its password) setting the account type of the windows service to LocalService will help you.
If the SQL connection is using windows authentication then setting the account type of the windows service to LocalSystem will help you.
The Account type modification can be done after installation also. For this go to Control panel->Administrative tools->Services->YourService right click and select Propertes->Logon and perform it there. If you are selecting the LocalSystem (windows authentication) you will be asked to enter the login credentials of the account in which the service is running.
In the case of windows authentication in SQL connection the credentials of the account in which the service is running will be taken for SQL connectivity also.
Hope this helps ...
One more suggestion put a sleep statement on your process when it starts so oyu have time to attach to it
Problem Solved: I set up my connection but I never opened it.
I needed conn.open()
The thing that helped me most was adding this code into my last catch statement:
sendDebugEmail(ex.Message & vbcrlf & ex.stackTrace)
It send me an email of the stackTrace and made it very easy to debug