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()
Related
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.
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
I'm trying to connect to a SQL Server database that is not local. I have the Data Source and Initial Catalog - no issues. But need to change Integrated Security to False and insert SQL Server credentials.
Does anyone have any idea how put that in the connection string?
Also, does anyone know how to handle SecureStrings?
Here is my code so far:
Dim pwd As New SecureString("Password")
Dim cred As New SqlCredential("Username", pwd)
Dim sql As New SqlConnection("Data Source=OnlineServer;Initial Catalog=DatabaseName;Integrated Security=False")
Have a look at here: SQL Connection Strings to hopefully find which one you need. This will give you the basics.
To make the SQL account credentials confidential, you should encrypt the <connection strings> section in the web.config. to do so:
aspnet_regiis -pe "connectionStrings" -app "OnlineServer" -prov "DataProtectionConfigurationProvider"
Retrieving your connection string using ConfigurationManager will automatically decrypt the string
Dim connectionString = ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
Here is a Microsoft Link that explains it further.
I worked out what I needed to do and how to handle secure strings.
Here is a code snippet for anyone who struggles in the future:
Imports System.Data.SqlClient
Imports System.Net.Mail
Imports System.Security
Public Module secure
Public Function sql()
Dim pass As String = "Password"
Dim pwd As SecureString = New SecureString()
For Each ch As Char In pass
pwd.AppendChar(ch)
Next
pwd.MakeReadOnly()
Dim cred As New SqlCredential("SQL_Login", pwd)
Dim conn As New SqlConnection("Server=Database_Name;Initial Catalog=Database_Address;Integrated Security=False", cred)
Return conn
End Function
End Module
Public Class sqlCommunications
Dim sql As New SqlConnection
Dim sqlcom As New SqlCommand
Public Sub start()
sql = secure.sql
sqlcom.Connection = sql
sql.Open()
sql.Close()
End Sub
End Class
I've got a question regarding Visual Basic's local database. So far I've managed to: 1. Create a Local Database, named it Database1 2. Create a table with values (username, password, year/section, secretquestion, secretanswer) 3. Create a dataset in form1(to get form2's entries) 4. Create a registration form in form 2( 5 labels/textboxes to get username,password,year/section,secretquestion,secretanswer)
Here's my current code for Form2:
Public Class Form2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlConnection1 As New System.Data.SqlClient.SqlConnection("Data Source=C:\Users\Bounty Hounds\AppData\Local\Temporary Projects\WindowsApplication1\Database1.sdf")
Dim cmd As New System.Data.SqlClient.SqlCommand
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "INSERT Username (user) Password (pass) Year/Section (yns) SecretQuestion (sq) SecretAnswer (sa)"
cmd.Connection = sqlConnection1
sqlConnection1.Open()
cmd.ExecuteNonQuery()
sqlConnection1.Close()
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Dim user As String
user = TextBox1.Text
End Sub
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Dim pass As String
pass = TextBox2.Text
End Sub
Private Sub TextBox3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.TextChanged
Dim yns As String
yns = TextBox3.Text
End Sub
Private Sub TextBox4_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox4.TextChanged
Dim sq As String
sq = TextBox4.Text
End Sub
Private Sub TextBox5_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox5.TextChanged
Dim sa As String
sa = TextBox5.Text
End Sub
End Class
But as soon as I click the register button it gives me an error and points at the sqlConnection1.Open() line, the error is: "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections."
In the Database Explorer I see my Database1.sdf with an X on its icon(the small yellow cylinder) and checked that its state is closed, so I tried opening it by right clicking it, then modify connection, placed the Database1.sdf path in the Database, inputted my password and pressed ok. At that point I see my Database1.sdf state go "Open" but when I ran my application the state went to "Closed" again (btw I see this state thing by right clicking my Database1.sdf in the Solution Explorer).
This text below has little to no connection with my code above and I just wanted your opinions on what is the best approach to the software I want to create so if you only want to help me on my code which I greatly appreaciate, you can stop reading the paragraphs below but if you do take time to consider reading it, It would mean alot to me. THANKS
The connection of a visual basic form and a database is the first step of what I really want to do, what my main goal is a File Storage system between two PCs which I'll increase once I figured out those 2 PCs.
To reach that goal I tried to divide each problems so I can address them accordingly and eventually finishing the entire software.
Establish a connection between 2 PCs (which I've done by setting PC2's dns server with PC1's ip address).
Connect a visual basic form (which in my case is a registration form) with a database for storing user accounts.
Make every registration create a folder for the certain users that registered. The folders created will be the storage of their files (this idea is really vague atm as I don't know how will I do this, AND VERY IMPORTANT PART IS ONLY THE REGISTERED USERS FROM THE DATABASE ONLY HAVE ACCESS TO THE FOLDERS THEY OWN(sorry i'm not shouting, just noting this as I feel this is the hardest part to do)
Implement a disk quota on the folders to limit sizes.
Create a Login system for PC2 to connect to the database of PC1 (Database should verify this and give an error if the infos are incorrect).
Create a Save/Load button for PC2 (I want PC2 to save its myDocuments Folder on PC1's Folder for Storage Files by using the My.Computer.FileSystem.CopyDirectory command. Then load will copy the PC1's Folder and load it into PC2's MyDocuments Folder.
Lastly and the biggest question is that are all these possible to do with Visual Basic? I've tried it with Windows Active Directory using roaming user profiles but I really want to develop my own software.
EDIT:
#Jimmy Smith
Thanks for replying, I've decided to create another database named CCS and my new code for form2 is:
Dim conn As New System.Data.SqlServerCe.SqlCeConnection()
Dim cmd As New System.Data.SqlClient.SqlCommand
conn.ConnectionString = _
"Persist Security Info = False; Data Source = 'C:\Users\Bounty Hounds\Documents\Visual Studio 2010\Projects\WindowsApplication2\WindowsApplication2\CCS.sdf';" & _
"Password = joshua8; File Mode = 'shared read'; "
conn.Open()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "INSERT Username (user) Password (pass) Year/Section (yns) SecretQuestion (sq) SecretAnswer (sa)"
However, It generates a new error:
There is a file sharing violation. A different process might be using the file. [ C:\Users\Bounty Hounds\Documents\Visual Studio 2010\Projects\WindowsApplication2\WindowsApplication2\CCS.sdf ]
You can't connect to SDF files direct without using the Compact Edition library. Unfortunately, it's not installed by default as Microsoft seems to be phasing it out.
Use System.Data.SqlserverCe.SqlCeConnection in place of System.Data.SqlClient.SqlConnection
http://visualstudiogallery.msdn.microsoft.com/0e313dfd-be80-4afb-b5e9-6e74d369f7a1
http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection(v=vs.100).aspx
I was going to check if my database is connecting to my project in vb.net, but it's seems like there's a problem on my code or to my SQL server. It always shows me a message "Login failed for user 'id/id2'".
Here is my code:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlconn As New SqlConnection
sqlconn.ConnectionString = "server = (local);Database=OJT;integrated security=true"
Try
sqlconn.Open()
Catch ex As Exception
MessageBox.Show(ex.Message, "Connection to Sql Server Failed!", MessageBoxButtons.OK)
End Try
Me.Text = "You are successfully connected to Sql Server"
End Sub
End Class
try this one instead :
"Data Source=(local);Initial Catalog=OJT;Persist Security Info=True;User ID=(Your User ID);Password=(Your Password)"
hopes that it solve your problem. Good Day!
try this
sqlconn.ConnectionString = "Data Source=(local);Initial Catalog=OJT;Integrated Security=True"