Cannot connect project to a SQL Server database - sql-server

I have a problem while trying to copy my project folder to another hard drive. My project in Visual Studio is defined in h:\ and while run exe file project no any problem but while copy folder project to another hard drive I have a problem to connect the application to SQL Server.
See these screenshots:
http://upload.tehran98.com/img1/f9kio8ssjofg1lhkjdg.jpg
http://upload.tehran98.com/img1/k6ajdb22xhdjrgcn419.jpg
For example in login form and in login button my code is:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As New SqlConnection("Server=.\SQLExpress;AttachDbFilename=" + Environment.CurrentDirectory + "\Database\Automation.mdf;Database=Automation;Trusted_Connection=Yes;")
s2 = "Select count( * ) from Login where UserName = '" & TextBox1.Text & "' and Password = '" & TextBox2.Text & "'"
Dim com As New SqlCommand(s2, conn)
Dim res As Object
conn.Open()
res = com.ExecuteScalar()
conn.Close()
If res = 1 Then
MsgBox("Welcome Dear " + TextBox1.Text, MsgBoxStyle.OkOnly, "Login Successful")
us = TextBox1.Text
If us = "admin" Then
Main.Label4.Text = "ADMINISTRATOR"
Else
Main.Label4.Text = "USER"
us = TextBox1.Text
Main.Button3.Enabled = False
Main.Button5.Enabled = False
Main.Button9.Enabled = False
End If
Main.Show()
Me.Hide()
Else
MsgBox("Invalid User OR Password", MsgBoxStyle.Critical, "Attention Please")
TextBox1.Text = ""
TextBox2.Text = ""
Exit Sub
End If
End Sub

You need to specify where the database is, you can't use Environment.CurrentDirectory. CurrentDirectory uses the path of the current working directory. So either move the database to the same hard drive or change the path to your database.
http://msdn.microsoft.com/en-us/library/system.environment.currentdirectory.aspx

Related

Error : vb.net sqlite create database with password

i face problem when i try create sqlite database with password.
When I create database without password it is work very good but if i try to set password it give me error message "Could not load file or assembly 'System.Data.SQLite.SEE.License, Version=1.0.117.0, Culture=neutral, PublicKeyToken=433d9874d0bb98c5' or one of its dependencies. The system cannot find the file specified.".
My Code :
My Code Is :
Imports System.Data.SQLite
Imports System.IO
Public Class Form1
Dim DB_Path As String = Application.StartupPath & "\DB\database.sqlite"
Private Async Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
If File.Exists(DB_Path) = False Then
' create db folder if not exist
If Not (System.IO.Directory.Exists(Application.StartupPath & "\DB\")) Then
System.IO.Directory.CreateDirectory(Application.StartupPath & "\DB\")
End If
' Create a new SQLite connection
Using conn As New SQLiteConnection("Data Source=" & Application.StartupPath & "\DB\database.sqlite" & ";Version=3;")
'set db password
conn.SetPassword("ashraf123") ' the error here
'change db conn string
conn.ConnectionString = "Data Source=" & DB_Path & ";Password=ashraf123;Version=3;"
'open conn
Await conn.OpenAsync
' do somthing
End Using
Else
Using conn As New SQLiteConnection("Data Source=" & DB_Path & ";Password=ashraf123;Version=3;")
Await conn.OpenAsync
' do somthing
End Using
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
End Class
I tried that change platform from any cpu to x86.
I tried that change platform from any cpu to x64.
I tried that Copy system.data.sqlite.dll and all other .dll files to startup app folder.
I tried uninstall all packages and reinstalled them again.
i tried creat new project and do all mentioned steps.
install this package SQLitePCLRaw.bundle_e_sqlcipher
and use the password in connection string like this :
Data Source=" & DB_Path & ";Password=ashraf123

Retrieve Messages from SQL Stored Procedure in VB.Net

I am working on created a login form for an application I am working on. I have my application set up to properly connect to the database and run stored procedures and queries on the database as well.
However I am unsure how to send messages from the database to my VB.Net Application. Right now I have essentially two methods that execute code for my database:
Public Function ExecuteCMD(ByRef CMD As SqlCommand) As DataTable
Dim DS As New DataSet()
Try
OpenDBConnection()
CMD.Connection = DB_CONNECTION
If CMD.CommandText.Contains(" ") Then
CMD.CommandType = CommandType.Text
Else
CMD.CommandType = CommandType.StoredProcedure
End If
Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300
adapter.Fill(DS)
Catch ex As Exception
Throw New Exception("Database Error: " & ex.Message)
Finally
CloseDBConnection()
End Try
Return DS.Tables(0)
End Function
Public Function ExecuteCMDWithReturnValue(ByRef CMD As SqlCommand) As Boolean
Try
OpenDBConnection()
CMD.Connection = DB_CONNECTION
CMD.Parameters.Add("#ret", SqlDbType.Int).Direction = ParameterDirection.ReturnValue
CMD.CommandType = CommandType.StoredProcedure
CMD.ExecuteNonQuery()
Dim result As Object = CMD.Parameters("#ret").Value
Return If(Convert.ToInt32(result) = 1, False, True)
Catch ex As Exception
Throw New Exception("Database Error: " & ex.Message)
Return False
Finally
CloseDBConnection()
End Try
End Function
These functions honestly work fine, but they are horrible for error processing.
For example I'd like to be able to set up my Store Procedure for logging in to the application to return a "Username not found" or "Password incorrect" message so that I can display to my user exactly what the problem is, as opposed to just returning a generic "Login information incorrect" message from only returning true or false on the logging in going through or not.
I unfortunately do not know exactly how to do this on either end. I don't know what to set up on the SQL Server side to have it spit out messages in procedures, and I don't know hot to receive those messages in VB.Net.
You can verify your user right in VB. I don't think it is a good idea to tell the user If the password or user name is wrong (or if both are wrong). If this data is password protected then it should be protected from malicious logins. It would help a hacker to know what was wrong.
Private Function VerifyPassword(pword As String, uname As String) As Boolean
Using cn As New SqlConnection(My.Settings.UsersConnectionString)
Dim cmd As New SqlCommand("Select Count(*) From Users Where UserName = #UserName And UserPassword = #Password;", cn)
cmd.Parameters.Add("#UserName", SqlDbType.VarChar, 100).Value = uname
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 100).Value = pword
Try
cn.Open()
Dim i As Integer = CInt(cmd.ExecuteScalar())
If i > 0 Then Return True
Return False
Catch ex As Exception
Throw
Finally
cn.Close()
cmd.Dispose()
End Try
End Using
End Function
Of course the password is stored hashed with a salt.

Upload Image using VB.Net and SQL Server

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim command As New SqlCommand("insert into rent(Image,Status)values(#Image,#Status)", connection)
Dim ms As New MemoryStream
PictureBox1.Image.Save("ms", PictureBox1.Image.RawFormat)
command.Parameters.Add("#Image", SqlDbType.VarChar).Value = ms.ToArray
command.Parameters.Add("#Status", SqlDbType.VarChar).Value = TextBox5.Text
connection.Open()
If command.ExecuteNonQuery = 1 Then
MessageBox.Show("Successfully uploaded")
Else
MessageBox.Show("Not uploaded")
End If
connection.Close()
End Sub
I'm trying to upload an image into my SQL Server using Visual Studio; everything is working except when I click the upload button, I keep getting the following error:
I tried every possible solution and no luck, I tried enabling the tcp and changing the ip even in SQL Server.
The error you get means that you can't connect to SQL Server.
Make sure your connection string is correct, and you don't have a firewall blocking the connection between the computer that runs the code and the computer that hosts SQL Server.
However, once you sort the connection error, you still have a few problems with your code.
change PictureBox1.Image.Save("ms", PictureBox1.Image.RawFormat)
to PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
to save the image into the memory stream.
Change command.Parameters.Add("#Image", SqlDbType.VarChar).Value = ms.ToArray
to command.Parameters.Add("#Image", SqlDbType.VarBinary).Value = ms.ToArray
because memoryStream.ToArray returns a byte array, not a string.
make sure the Image column in your table is, in fact, VarBinary.
SqlCommand, SqlConnection and MemoryStream all implements the IDisposable interface, therefor you should use all of them as local variable inside the using statement. Your code suggest you are using a class level SqlConnecion instance. That should be changed.
All communication with the database should be inside a try...catch block, since too many things you can't control can go wrong (network disconnected, for instance).
Your code should look more like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim RowsEffected as int = 0
Using Dim connection As NewSqlConnection(ConnectionString
Using Dim command As New SqlCommand("insert into rent(Image,Status)values(#Image,#Status)", connection)
Using Dim ms As New MemoryStream
PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
command.Parameters.Add("#Image", SqlDbType.VarBinary).Value = ms.ToArray
command.Parameters.Add("#Status", SqlDbType.VarChar).Value = TextBox5.Text
Try
connection.Open()
RowsEffected = command.ExecuteNonQuery()
End Try
Catch Exception ex
MessageBox.Show("Failed to upload image:"& VbCrLf & ex.Message)
End Catch
End Using
End Using
End Using
If RowsEffected = 1 Then
MessageBox.Show("Successfully uploaded")
Else
MessageBox.Show("Not uploaded")
End If
End Sub

VB.net SQL Backup with user choosing path

I am trying to figure out how to program a SQL Server backup through a button click on my application, allowing the user to choose the path in which it's saved.
So far I have the following but I am stuck on how to proceed.
Private Sub Backup_Click(sender As Object, e As EventArgs) Handles Backup.Click
Dim sqlconnectionstring As String = "Data Source=ressqlxd023.silver.com\int;Initial Catalog=hw3qwq_c51twed;Integrated Security=True"
Dim conn As New sqlconnection(sqlconnectionstring)
conn.open()
Dim cmd As New sqlcommand
cmd.connection = conn
cmd.ExecuteNonQuery()
conn.close()

Keep console window open after completion

I'm running a bat file and having the output displayed in the console window. Right now, I am having the bat file intentionally fail (bat file contains "STARET www.webaddress.com"). The error catching and everything works, but the console window closes immediately. I would like to keep it open, but so far my searching how to do so hasn't come up with any solutions.
The code I currently have:
Me.processStartInfo = New ProcessStartInfo("C:\Admin\PsTools\psexec.exe", "\\PCName -u domain\" & user & " -p " & pass & " pathtobatfile")
Me.processStartInfo.RedirectStandardError = True
Me.processStartInfo.RedirectStandardOutput = True
Me.processStartInfo.WindowStyle = ProcessWindowStyle.Hidden
Me.processStartInfo.UseShellExecute = False
Dim process As System.Diagnostics.Process = Nothing
'Start the process, which runs the bat file on the remote server
process = System.Diagnostics.Process.Start(Me.processStartInfo)
AddHandler process.OutputDataReceived, AddressOf OutputHandler
process.BeginOutputReadLine()
process.WaitForExit()
Dim errorresponse As DialogResult
If process.HasExited And process.ExitCode <> 0 Then
errorresponse = MessageBox.Show("There was an error. Exit code: " & process.ExitCode & _
". Do you wish to view the log?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error)
ElseIf process.HasExited And process.ExitCode = 0 Then
MessageBox.Show("The update completed successfully.", "Success", MessageBoxButtons.OK)
End If
If errorresponse = DialogResult.Yes Then
'To fill in later
End If
And the event handler sub:
Private Shared Sub OutputHandler(ByVal sendingProcess As Object, ByVal output As DataReceivedEventArgs)
Console.WriteLine(output.Data)
End Sub
I've also tried just doing synchronous output (using StreamReader and Console.Writeline with a Readline()), but that didn't work either.
Try to add at the end
set err=%ERRORLEVEL%
pause
exit %err%
Try adding pause at the end of the BAT file. Alternatively, if you're lauching the bat file via a cmd process, you can add the /k argument.
cmd /k pathToBatFile

Resources