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
Related
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()
I've been searching the net for a basic sample winforms app that is written in vb.net to upload a file to onedrive. Does anyone know of any?
I'm trying to get a file uploaded with a winforms app in vb.net. I'm as far as getting the auth working... but calling the next method returns a 401...
I did the following:
Shared scope As String = "wl.skydrive_update"
Shared client_id As String = "0000000040144E26"
Shared signInUrl As New Uri([String].Format("https://login.live.com/oauth20_authorize.srf?client_id={0}&redirect_uri=https://login.live.com/oauth20_desktop.srf&response_type=code&scope={1}", client_id, scope))
Private Sub cmdOneDriveAuth_Click(sender As Object, e As EventArgs) Handles cmdOneDriveAuth.Click
Try
Dim auth As New FrmAuthBrowser
auth.WebBrowser1.Navigate(signInUrl)
auth.Show()
Catch ex As Exception
End Try
End Sub
and then in the auth window:
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
Try
If WebBrowser1.Url.AbsoluteUri.Contains("code=") Then
Dim AuthCode As String = System.Web.HttpUtility.ParseQueryString(WebBrowser1.Url.Query)("code")
My.Settings.OneDrive_Enabled = True
My.Settings.OneDrive_AuthCode = AuthCode
My.Settings.Save()
Me.Dispose()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
but when I try and get the root info, I get a 401...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim client As New WebClient()
Dim result = client.OpenRead(New Uri("https://apis.live.net/v5.0/me/skydrive?access_token=" + My.Settings.OneDrive_AuthCode))
Dim sr As StreamReader = New StreamReader(result)
MsgBox(sr.ReadToEnd())
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Can anyone provide me with some guidance?
Looks like you're using the 'code' flow of OAuth, but you're missing a step. The 'code' you get back isn't the same as the access_token. You need to make another call to the login server first to exchange your code for an access_token.
POST https://login.live.com/oauth20_token.srf
Content-Type: application/x-www-form-urlencoded
client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
&code={code}&grant_type=authorization_code
You can find more details here http://onedrive.github.io/auth/msa_oauth.htm#code-flow.
OneDrive just released a new API, so I would encourage you to check it out. http://onedrive.github.io/
There's also a sample Windows/C# app that you can look at for reference on how to sign in and upload files. https://github.com/OneDrive/onedrive-explorer-win
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"
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.