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

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.

Related

How do I create an Azure SQL Database copy during runtime?

I am new to VB.NET and Azure SQL services and I have spent the last 3 days searching for an answer and cannot come up with an answer I can truly understand. Here is my scenario and problem:
I have a VB.NET application where a user will log into their account and have their own set of tables under their own Azure SQL Database. I would like my program to automatically create their database for them (using their own selected name), which would be a database copy of an existing empty Database in Azure.
I can already access the data tables in my master database, but I do not know how to make a copy of it from my program during runtime. When I run my application and it debugs the following snippit of code, I get an exception error saying "You must be logged into the master database" I'm not sure how to resolve that error from popping up as I am using the master admin account in my normal SQL connection string.
Private Sub BtnActivate_Click(sender As Object, e As RoutedEventArgs)
If passwrd1.Password <> passwrd2.Password Then
MsgBox("Password doesn't match Confirm Password.", vbOKOnly)
Else
Dim commandString = "CREATE DATABASE " & dbname.Text & " AS COPY OF DBDEV;"
Using connection As New SqlConnection(My.Settings.DBDEVConnectionString)
Dim command As New SqlCommand(commandString, connection)
Try
connection.Open()
command.ExecuteNonQuery()
MsgBox("DATABASE SETUP. USE " & dbname.Text & "AS DBNAME TO CONNECT TO")
Catch ex As Exception
Throw ex
End Try
End Using
End If
End Sub
Please help, I've been moving nowhere and everything I'm searching for doesn't give me a clear answer to this simple scenario.
After many attempts, I solved the problem: in my connection string, I had the initial catalog default to my database and so I changed it to say "master" (even though I don't have a database named master) and it performed the Database copy for me. Woohoo!

connection to Pervasive database slow

This has been an on going issue at my place of work. Previously, we had a co-op programming student write us some applications using C# which ran well on his laptop, but once the applications were put to use on different computers, the connection to the pervasive database because painfully slow.
Now I am writing a simple VB.net application which need to query the Pervasive database, and I'm running into the same issue.
here's my code:
'PSQL variables
Dim myPsqlConnection As PsqlConnection = New PsqlConnection("ServerName=FILESERVER;ServerDSN=SAGE2")
Dim queryString As String
queryString = "SELECT NAME FROM CUSTOMER"
Dim MyCommand As New PsqlCommand(queryString, myPsqlConnection)
Dim MyReader As PsqlDataReader
Dim tempCustname As String
Try 'open conncetion to Pervasive DB
myPsqlConnection.Open()
Catch ex As Exception
MsgBox("COULD NOT OPEN A CONNECTION TO THE DATABASE" & vbCrLf & ex.Message)
Exit Sub
End Try
Try 'execute Pervasive query
MyReader = MyCommand.ExecuteReader
Catch ex As Exception
MsgBox("QUERY ERROR" & vbCrLf & ex.Message)
Exit Sub
End Try
If MyReader.HasRows = False Then
MsgBox("NO RESULTS FOUND")
Exit Sub
End If
While (MyReader.Read)
tempCustname = MyReader("NAME").ToString()
Customers.Items.Add(tempCustname)
End While
MyReader.Close()
myPsqlConnection.Close()
I stepped through the program and it take about 30 seconds to get past the line where it opens the connection.
As for the specs (I'll do my best):
My computer is quite powerful (16 gb or ram, 6 core AMD processor at 3.0 Ghz per core, windows 7 home 64 bit)
Pervasive.Data.SqlClient Version 3.2
Compiling with Microsoft Visual Basic 2010 Express
There are very few computers on this network (about 7), and I have no such trouble with MS Access databases. Our server is new 2 years ago, and out network has been upgraded to a GB connection. I should note I know very little about databases in general, let alone connecting with VB. I'm not really the best person to be doing this, but I'm still the most qualified person in our small company.
I've got it working now. The solution was to first install the database in the pervasive control center. First by selecting "new database" from the main window of the PCC and filling in the database name, location, username and password.
Next I changed the connection from pervasive ADO to OLEDB. My connection string now looks like this:
Dim myPsqlConnection As OleDbConnection = New OleDbConnection("Provider=PervasiveOLEDB;Data Source=DatabaseName;Location=FILESERVER")
Thanks to all everyone for your help!

Vb.Net Detect if application server is down

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

Restoring a backup using SQLCommand in VB.NET

I've got a VB.NET console application I'm creating that will make it easier for people to work with some test databases, and part of this is having a function that restores the database. I thought it was fairly straightforward, and here is the code I have so far:
Sub Restore()
con = New SqlConnection("Data Source=" & utilnamespace.sqlSvr & ";Database=Master;integrated security=SSPI;")
cmd = New SqlCommand("ALTER DATABASE [db] SET OFFLINE WITH ROLLBACK IMMEDIATE RESTORE DATABASE db FROM DISK = 'G:\db.bak' WITH REPLACE, STATS = 10", con)
cmd.Connection.Open()
cmd.ExecuteNonQuery()
Console.WriteLine(cmd.CommandText)
cmd.Connection.Close()
End Sub
The SQL works fine if I run it in SSMS, however it will time out if I try to run it from the app. The problem is that I've read over this and I'm still unsure of what to do.
Should I use BeginExecuteNonQuery and then have it listen for the statement complete message somehow?
Even if I believe that showing a waiting form and waiting for some kind of confirmation would be better for the end user... have you tried changing the timeout in the connection string to solve it in a quick way?
eg (seconds):
string connStr = "Data Source=(local);Initial Catalog=db;
Integrated Security=SSPI;Connection Timeout=30";
Also check these links:
SQL Server Management Objects (SMO)
SQL Server 2008 - Backup and Restore Databases using SMO
If the database is too big you can increase the timeout of the Command, not the connection string
cmd.Connection.Open()
cmd.CommandTimeout = 100
cmd.ExecuteNonQuery()
Console.WriteLine(cmd.CommandText)
cmd.Connection.Close()

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