Click here to Skip to main content
15,880,427 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
On my photo upload page when I test it and try to upload a photo I keep getting the following error message: Not allowed to change the ConnectionString property. The connection's current state is open.

I have scanned and read line by line and I still cannot find where I have left a db connection open and not closed it, or is there another issue causing this? I am newbie to noivce so be gentle.

What I have tried:

VB.NET
Imports System
Imports System.Collections.Generic
Imports System.Drawing
Imports System.IO
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D


Partial Class members_uploadphoto
    Inherits System.Web.UI.Page
    Dim cf As New comonfunctions


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        '   Response.Write(Now.Year.ToString & Now.Month.ToString & Now.Day.ToString & Now.Hour.ToString & Now.Minute.ToString & Now.Millisecond)
        Dim myreader As System.Data.OleDb.OleDbDataReader
        Dim cn As New System.Data.OleDb.OleDbConnection
        Dim cmd As New System.Data.OleDb.OleDbCommand
        Dim strsql As String = ""
        Dim mcount As Integer = 0

        strsql = "select count(*) from photo where pid='" & Session("pid") & "'"
        cn.ConnectionString = cf.friendshipdb
        cn.Open()

        cmd.Connection = cn
        cmd.CommandText = strsql
        myreader = cmd.ExecuteReader


        If myreader.HasRows = True Then
            While myreader.Read
                mcount = myreader.GetValue(0)
            End While
        End If

        If mcount >= 200 Then
            upimage.Text = "You Can only Upload 200 Photos"
            upimage.Enabled = False
        End If

        cn.Close()

    End Sub

    Protected Sub upimage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles upimage.Click
        Dim msg As String = ""
        Dim filecopy As String = ""
        Dim x As Integer = 0
        Dim y As Integer = 0

        If Not FileUpload1.PostedFile Is Nothing And FileUpload1.PostedFile.ContentLength > 0 Then

            'Dim fn As String = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName)
            Dim ext As String = ""
            ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName)

            Dim SaveLocation As String = Server.MapPath("..\App_Themes") & "\"
            Try

                If (FileUpload1.PostedFile.ContentType = "image/gif" Or FileUpload1.PostedFile.ContentType = "image/pjpeg" Or FileUpload1.PostedFile.ContentType = "image/jpeg" Or FileUpload1.PostedFile.ContentType = "image/png" Or FileUpload1.PostedFile.ContentType = "image/bmp" Or FileUpload1.PostedFile.ContentType = "image/bitmap" Or FileUpload1.PostedFile.ContentType = "image/jpg" Or FileUpload1.PostedFile.ContentType = "image/tiff") Then

                    msg = addentry(ext)
                    SaveLocation = SaveLocation & msg & "11" & ext
                    filecopy = Server.MapPath("..\App_Themes") & "\" & msg & ext

                    FileUpload1.PostedFile.SaveAs(SaveLocation)

                    '  watermark(SaveLocation, "aminnn")
                    '  Response.Write("The file has been uploaded.")


                    Dim objImage As System.Drawing.Image = System.Drawing.Image.FromFile(SaveLocation)
                    'From File
                    Dim height As Integer = objImage.Height
                    'Actual image width
                    Dim width As Integer = objImage.Width
                    'Actual image height
                    Dim bitmapimage As New System.Drawing.Bitmap(objImage, width, height)
                    ' create bitmap with same size of Actual image
                    Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bitmapimage)
                    'Creates a System.Drawing.Color structure from the four ARGB component
                    '(alpha, red, green, and blue) values. Although this method allows a 32-bit value
                    ' to be passed for each component, the value of each component is limited to 8 bits.
                    'create Brush
                    Dim brush As New SolidBrush(Color.FromArgb(113, 255, 255, 255))

                    x = 10
                    y = objImage.Height / 2
                    'Adding watermark text on image
                    'g.DrawRectangle(Pens.Blue, x, y)
                    'g.Clear(Color.Green)

                    g.TextRenderingHint = Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit
                    g.DrawString(cf.websitename, New Font("Arial", 18, System.Drawing.FontStyle.Bold), brush, x, y)

                    g.DrawString(cf.websitename, New Font("Arial", 18, System.Drawing.FontStyle.Bold), brush, 100, y + 80)

                    'save image with Watermark image/picture
                    'bitmapimage.Save("watermark-image.jpg"); //if u want to save image

                    Response.ContentType = "image/jpeg"
                    bitmapimage.Save(filecopy)
                    bitmapimage.Dispose()
                    objImage.Dispose()

                    File.Delete(SaveLocation)
                    Label1.Text = "Photo Uploaded"
                Else
                    'Response.Write("file is not an image")
                    Response.Write("<br>file is " & FileUpload1.PostedFile.ContentType)
                End If
            Catch Exc As Exception
                Response.Write("Error: " & Exc.Message)
            End Try
        Else
            Response.Write("Please select a file to upload.")
        End If


    End Sub

    Function addentry(ByVal ext1 As String) As String
        Dim uid As String = ""

        Dim strfield As String = ""
        Dim strvalues As String = ""
        Dim strsql As String = ""
        Dim passw As String = ""

        Dim cnstring As String
        Dim cn As New System.Data.OleDb.OleDbConnection
        Dim cmd As New System.Data.OleDb.OleDbCommand
        Dim cmd2 As New System.Data.OleDb.OleDbCommand

        Dim photoid As String = ""
        Dim photoname As String = ""

        Dim myreader As System.Data.OleDb.OleDbDataReader

        cn.ConnectionString = cf.friendshipdb
        cn.Open()

        strsql = "select passw from photo where pid='" & Session("pid") & "' and (passw<>'' and passw is not null)"
        cmd2.Connection = cn
        cmd2.CommandText = strsql
        myreader = cmd2.ExecuteReader

        While myreader.Read
            passw = myreader.GetValue(0).ToString
        End While


        cnstring = ConfigurationManager.ConnectionStrings("accessconstr").ConnectionString
        cn.ConnectionString = cnstring
        cn.Close()

        cn.Open()

        uid = Now.Year.ToString & Now.Month.ToString & Now.Day.ToString & Now.Hour.ToString & Now.Minute.ToString & Now.Millisecond



        strfield = " insert into photo(photoid,photoname,pid,passw)"
        strvalues = " values(@photoid,@photoname,@pid,@passw)"

        strsql = strfield & strvalues

        cmd.Parameters.AddWithValue("@photoid", uid)
        cmd.Parameters.AddWithValue("@photoname", uid & ext1)
        cmd.Parameters.AddWithValue("@pid", Session("pid"))
        cmd.Parameters.AddWithValue("@passw", passw)

        cmd.Connection = cn
        cmd.CommandText = strsql
        cmd.ExecuteNonQuery()

        addentry = uid
        cn.Close()

    End Function


End Class
Posted
Updated 2-Aug-17 17:04pm
v2

1 solution

Add your code which is talking to database in try...catch block and close the connection in finally block as well. This ensures if there is an exception in your code before connection close method is called, the finally should tale care of closing your connection. The best practice is to use a using block for your connection. Google to find how to manage connection vb.net. Another improvement in your code is to use parameterized query so that your code is not vulnerable to sql injection. Google for it I am sure you will find lot of information.
 
Share this answer
 
Comments
Edward Mergel 3-Aug-17 1:59am    
Okay, the connection string issue has been resolved, but not when I try to upload I am getting no results and the image I am trying to upload is not uploading and also not writing to the MS DB. I have not done the using yet I am still reading on the, so could that be the problem? Here the the code as it looks now:

Imports System
Imports System.Collections.Generic
Imports System.Drawing
Imports System.IO
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D


Partial Class members_uploadphoto
Inherits System.Web.UI.Page
Dim cf As New comonfunctions


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Response.Write(Now.Year.ToString & Now.Month.ToString & Now.Day.ToString & Now.Hour.ToString & Now.Minute.ToString & Now.Millisecond)
Dim myreader As System.Data.OleDb.OleDbDataReader
Dim cn As New System.Data.OleDb.OleDbConnection
Dim cmd As New System.Data.OleDb.OleDbCommand
Dim strsql As String = ""
Dim mcount As Integer = 0

strsql = "select count(*) from photo where pid='" & Session("pid") & "'"
cn.ConnectionString = cf.friendshipdb
cn.Open()

cmd.Connection = cn
cmd.CommandText = strsql
myreader = cmd.ExecuteReader


If myreader.HasRows = True Then
While myreader.Read
mcount = myreader.GetValue(0)
End While
End If

If mcount >= 200 Then
upimage.Text = "You Can only Upload 200 Photos"
upimage.Enabled = False
End If

cn.Close()

End Sub

Protected Sub upimage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles upimage.Click
Dim msg As String = ""
Dim filecopy As String = ""
Dim x As Integer = 0
Dim y As Integer = 0
Dim cn As New System.Data.OleDb.OleDbConnection
Dim cmd As New System.Data.OleDb.OleDbCommand

cn.ConnectionString = cf.friendshipdb
cn.Open()

cmd.Connection = cn


If Not FileUpload1.PostedFile Is Nothing And FileUpload1.PostedFile.ContentLength > 0 Then

'Dim fn As String = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim ext As String = ""
ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName)

Dim SaveLocation As String = Server.MapPath("..\App_Themes") & "\"


Try
Catch Exc As Exception
If (FileUpload1.PostedFile.ContentType = "image/gif" Or FileUpload1.PostedFile.ContentType = "image/pjpeg" Or FileUpload1.PostedFile.ContentType = "image/jpeg" Or FileUpload1.PostedFile.ContentType = "image/png" Or FileUpload1.PostedFile.ContentType = "image/bmp" Or FileUpload1.PostedFile.ContentType = "image/bitmap" Or FileUpload1.PostedFile.ContentType = "image/jpg" Or FileUpload1.PostedFile.ContentType = "image/tiff") Then

msg = addentry(ext)
SaveLocation = SaveLocation & msg & "11" & ext
filecopy = Server.MapPath("..\App_Themes") & "\" & msg & ext

FileUpload1.PostedFile.SaveAs(SaveLocation)

' watermark(SaveLocation, "aminnn")
' Response.Write("The file has been uploaded.")


Dim objImage As System.Drawing.Image = System.Drawing.Image.FromFile(SaveLocation)
'From File
Dim height As Integer = objImage.Height
'Actual image width
Dim width As Integer = objImage.Width
'Actual image height
Dim bitmapimage As New System.Drawing.Bitmap(objImage, width, height)
' create bitmap with same size of Actual image
Edward Mergel 3-Aug-17 2:01am    
Here is the rest of the page sorry:

' create bitmap with same size of Actual image
Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bitmapimage)
'Creates a System.Drawing.Color structure from the four ARGB component
'(alpha, red, green, and blue) values. Although this method allows a 32-bit value
' to be passed for each component, the value of each component is limited to 8 bits.
'create Brush
Dim brush As New SolidBrush(Color.FromArgb(113, 255, 255, 255))

x = 10
y = objImage.Height / 2
'Adding watermark text on image
'g.DrawRectangle(Pens.Blue, x, y)
'g.Clear(Color.Green)

g.TextRenderingHint = Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit
g.DrawString(cf.websitename, New Font("Arial", 18, System.Drawing.FontStyle.Bold), brush, x, y)

g.DrawString(cf.websitename, New Font("Arial", 18, System.Drawing.FontStyle.Bold), brush, 100, y + 80)

'save image with Watermark image/picture
'bitmapimage.Save("watermark-image.jpg"); //if u want to save image

Response.ContentType = "image/jpeg"
bitmapimage.Save(filecopy)
bitmapimage.Dispose()
objImage.Dispose()

File.Delete(SaveLocation)
Label1.Text = "Photo Uploaded"
Else
'Response.Write("file is not an image")
Response.Write("file is " & FileUpload1.PostedFile.ContentType)
End If



Response.Write("Error: " & Exc.Message)
Finally
End Try

Else
Response.Write("Please select a file to upload.")
End If
cn.Close()
End Sub

Function addentry(ByVal ext1 As String) As String
Dim uid As String = ""

Dim strfield As String = ""
Dim strvalues As String = ""
Dim strsql As String = ""
Dim passw As String = ""

Dim cnstring As String
Dim cn As New System.Data.OleDb.OleDbConnection
Dim cmd As New System.Data.OleDb.OleDbCommand
Dim cmd2 As New System.Data.OleDb.OleDbCommand

Dim photoid As String = ""
Dim photoname As String = ""

Dim myreader As System.Data.OleDb.OleDbDataReader

cn.ConnectionString = cf.friendshipdb
cn.Open()

strsql = "select passw from photo where pid='" & Session("pid") & "' and (passw<>'' and passw is not null)"
cmd2.Connection = cn
cmd2.CommandText = strsql
myreader = cmd2.ExecuteReader

While myreader.Read
passw = myreader.GetValue(0).ToString
End While


cnstring = ConfigurationManager.ConnectionStrings("accessconstr").ConnectionString
cn.ConnectionString = cnstring


uid = Now.Year.ToString & Now.Month.ToString & Now.Day.ToString & Now.Hour.ToString & Now.Minute.ToString & Now.Millisecond



strfield = " insert into photo(photoid,photoname,pid,passw)"
strvalues = " values(@photoid,@photoname,@pid,@passw)"

strsql = strfield & strvalues

cmd.Parameters.AddWithValue("@photoid", uid)
cmd.Parameters.AddWithValue("@photoname", uid & ext1)
cmd.Parameters.AddWithValue("@pid", Session("pid"))
cmd.Parameters.AddWithValue("@passw", passw)

cmd.Connection = cn
cmd.CommandText = strsql
cmd.ExecuteNonQuery()

addentry = uid
cn.Close()

End Function


End Class
Atlapure Ambrish 3-Aug-17 6:07am    
I do not see your code like the one below. The con.Dispose will close the connection and release associated resources.

Dim con As New SqlClientConnection( . . .)

Try
' DB Operations (create, read, update, delete) here
con.open()

Catch SqlClientException (ex)

' Deal with exception
Finally
' Code here will always run, whether or not the try code succeeded
' or if you wound up in a catch block. You can safely call .close()
' or (as shown below) .dispose() because if the connection is already
' closed/disposed, the call doesn't do anything.


' Dispose is what you want - it will not only close the
' connection, but it will release the .NET reference to
' the remote resource, freeing up that resource (the database
' in this case) to serve other clients.

con.Dispose()

End Try

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900