Is SQL Server available - sql-server

I'm using VB.NET to create a simple application which will test if a variety of SQL Server are available online.
I have the code below, but the timeout is not working and it simply waits forever rather than throwing a timeout error. I have put breakpoints in and, as this is in an loop of IP's, it never progresses if the IP being checked is unavailable.
Dim data As New SqlClient.SqlConnection("Data Source=DatabaseIP;Initial Catalog=POS;Integrated Security=False;User ID=sa;Password=;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False".Replace("DatabaseIP", IP))
Try
data.Open()
Catch ex As Exception
Dim stophere As String = ""
TextBox1.Text += IP + vbNewLine
End Try

Connect Timeout=15 is not correct, try it with Connection Timeout=15

To connect with Database, following code is enough,
Dim data As New SqlClient.SqlConnection("Data Source=DatabaseIP;Initial Catalog=POS;Integrated Security=False;User ID=sa;Password=;")

Related

Try Catch not catching Database connection error

I'm using the following code to open a database connection. If the connection fails for any reason, I get the typical VB error message with all of the details. and my program stops. It does not give me my graceful message and ending.
My try/catch does not work regardless of the connection error (whether it is password related, network related, or sql server related).
I need my program to continue on even if I can't connect to the database.
Public Class SQL_Connection
Public conn As New SqlConnection
Public cmd As New SqlCommand
Public Sub New()
conn.ConnectionString = my_connection_string
Try
conn.Open()
Catch ex As Exception
MessageBox.Show("Unable to open database. " + ex.ToString)
End Try
cmd = conn.CreateCommand()
End If
End Sub
End Class
Have a look at this article.
If the program is not run in debug mode, the try catch would do it's thing right away with out stopping the execution.

Error in File Temp__.rpt

I made reports using database name Test. SQL Server as backend.
Used DSN. Even configured in ODBC DataSource.
Now I changed my report to mainDb
Some reports worked fine. Others throw error when database name changed.
Error message shown below.
Any solution for this?
I searched on internet, found similar errors based on invalid login or some implementation error. I don't know what exactly my error means.
My small code is posted here.
Private Sub DisplayReport()
Try
Dim report As New Summary
Dim pubdbname as String = "mainDb" '-------This name is correct.'
With report
.DataSourceConnections.Item(0).SetConnection("bonny", Pubdbname, True)
.SetParameterValue("#CompYear", PubYear1)
.SetParameterValue("#CompNo", mComp1)
.SetParameterValue("#accode", PubAcCode)
.SetParameterValue("#Trtype", PubTrTp)
.SetParameterValue("#SBkCd", PubSBkCd)
.SummaryInfo.ReportTitle = "Summary Report" & "_" & Format(CDate(FromDate.Text), "ddMMyyyy") & "-" & Format(CDate(ToDate.Text), "ddMMyyyy")
CReports.CRViewer.ReportSource = report
CReports.Show()
End With
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Thank You.

prompt for users to browse database connection if current database connection fails

I am building a data-entry program in vb.net that 5 people will share using, and I have problems setting the right database connection. It would do basic things like: pulling up the stock units, save job, load jobs operations.
The database I'm using is Access database (.mdb). This database will be located in a local server drive (mine is in Z drive) and the connection string looks like this
Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Z:\Jimmy's Files\Quality Enclosures.mdb"
This works fine on my computer, but the problem is it does not work on my coworkers computer.
d (\dc-qenclosures) (Z:) is the loacation to my local server drive, but on my coworker's computer, it is set up as
d (\dc-qenclosures) (Q:).
So, whenever I open the program on my co-worker's computer, it gives me an error saying that the database Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Z:\Jimmy's Files\Quality Enclosures.mdb" does not exist (which makes sense because it is not under Z: on his computer)
I know how to use the OpenFileDialog to browse for mbd files.. but how do I set this as the new database connection?
I want to create a properties menu to set the database location.
This is the code I have so far to browse for the database file
Private Sub RadButton6_Click(sender As Object, e As EventArgs) Handles RadButton6.Click
Dim myStream As Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "mdb files (*.mdb)|*.mdb|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
myConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & openFileDialog1.FileName
con.ConnectionString = myConString
con.Open()
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
I'd second #OneFineDay's suggestion of trying the UNC path first, but to answer your main question of browsing for and saving a database path, you may want to look at storing elements of your connection string in My.Settings, so you could make the path a user-level setting. There's an MSDN article with examples here:
Using My.Settings in Visual Basic 2005
In short, you'd have the code sample you shared save the value to My.Settings.DataPath (or whatever you decide to call the setting). Then when you're connecting to the database and need the connection string, you'd make it read from My.Settings.DataPath.
Of course, that'd store your path to the database in a plain-text app.config file by default, so you'll want to be conscious of that and take appropriate steps if there are any security concerns around your app or database.

Refresh a OleDbConnection to an Access DB - best practice

For reasons that is too long to explain in my .Net Win-Form Application I use a single global OleDbConnection to connect an Access DB. When I need, I open and close the connection, but generally the connection remains opened.
The problem is that sometimes the reading of the data not returns the updated datas:
Using cm As New OleDb.OleDbCommand(sQuery, cn)
Using rd As OleDb.OleDbDataReader = cm.ExecuteReader()
If rd.HasRows Then
If rd.Read() Then
Me.txtBrand.Text = rd.Item("MA_BRAND")
End If
End If
rd.Close()
End Using
End Using
While if I use a new connection I get the right data:
Using cn As New OleDb.OleDbConnection(sConnectionString)
cn.Open()
Using cm As New OleDb.OleDbCommand(sQuery, cn)
Using rd As OleDb.OleDbDataReader = cm.ExecuteReader()
If rd.HasRows Then
If rd.Read() Then
Me.txtBrand.Text = rd.Item("MA_BRAND")
End If
End If
rd.Close()
End Using
End Using
cn.Close()
End Using
I have to use the global connection then my solution is this
cn.Close()
cn.Open()
Using cm As New OleDb.OleDbCommand(sQuery, cn)
But I ask: there is a better solution to refresh the OledbConnection?
Thank you!
Pileggi
The Jet Access engine caches stuff - that's probably the problem.
Here's a good link:
How to Synchronize Writes and Reads with MS Access
No, do not leave the connection open. The connection pool provides for fast reconnects.
The problem you are facing with reading and writing the data is due to how Jet is implemented:
Microsoft Jet has a read-cache that is updated every PageTimeout milliseconds (default is 5000ms = 5 seconds). It also has a lazy-write mechanism that operates on a separate thread to main processing and thus writes changes to disk asynchronously.
Also, the rd.HasRows() isn't necessary, the If rd.Read() Then will return false if there aren't any rows.
To continue, the rd.Close() isn't necessary either since you are using the Using...End Using declaration. The End Using will close and dispose of it for you.

SQL Server pooling Issue

I have written a web application in which I have not allowed connection pooling for this application. I have written sample code as shown below which gets record from my table 20 times and fill in Data set I have close connection at every time.
But if I look in SQL Server Activity monitor it shows me one connection open in sleeping mode.
anyone tell me why this happens?
does this sleeping connection increase if users increase?
If SQL Server pools my connection then why its pooling if I have not allowed pooling for this application? How can I avoid this?
Code to fetch data
Try
Dim i As Integer
For i = 0 To 20
Dim _db As New commonlib.Common.DBManager(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString.ToString())
GridView1.DataSource = _db.ExecuteDataSet(CommandType.Text, "SELECT * FROM BT_AppSetting")
GridView1.DataBind()
Next
Catch ex As Exception
Response.Write(ex.Message.ToString())
ex = Nothing
End Try
DBManager constructor
'CONSTRUCTOR WHICH ACCEPTS THE CONNECTION STRING AS ARGUMENT
Public Sub New(ByVal psConnectionString As String)
'SET NOT ERROR
_bIsError = False
_sErrorMessage = Nothing
_cn = New SqlConnection
_sConnectionString = psConnectionString
_cn.ConnectionString = _sConnectionString
Try
_cn.Open()
Catch ex As Exception
_bIsError = True
_sErrorMessage = ex.ToString
ex = Nothing
End Try
End Sub
ExecuteDataSet Function body
Public Function ExecuteDataSet(ByVal CmdType As CommandType, ByVal CmdText As String, ByVal ParamArray Params As SqlParameter()) As DataSet
Try
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet
PrepareCommand(cmd, CmdType, CmdText, Params)
da.Fill(ds)
cmd.Parameters.Clear()
If _cn.State = ConnectionState.Open Then
_cn.Close()
End If
Return ds
Catch ex As Exception
_sErrorMessage = ex.ToString
_bIsError = True
ex = Nothing
Return Nothing
End Try
Please help me.... Waiting for kind reply
1)I THINK sql server does not close the connection right away. That why you see it.
2) Since you are closing the connection you should see only one. Unless your users are running the code at the same time. e.g if it was in a web page and there are 2 users, you will/shoudl see 2 connections.
Also if dont close your connections (just to try) your number of connection will (should :) ) go up.
It is your .net application that pools the connection and not sql server.

Resources