Error "ExecuteReader: connection property has not been initialized." - asp.net

Here's my code. I can't seem to figure out what's causing this error. The error itself pointed to the Do While myReader.read line of code, but I'm not sure that's what's causing the problem.
Here is a more detailed error message:
executereader: connection property has not been initialized. at system.data.oledb.oledbcommand.validateconnection(string method) at system.data.oledb.oledbcommand.validateconnectionandtransaction(string method)
Code:
Imports System.Data.OleDb
Imports System.Data
Partial Class Customer_6_OrderHistory
Inherits System.Web.UI.Page
Private myDB As OleDbConnection
Private sqlCmd As OleDbCommand
Private myReader As OleDbDataReader
Private myConnection As String = ConfigurationManager.ConnectionStrings("ConnString10").ToString
Private myDataFile As String = ConfigurationSettings.AppSettings("DBFile")
Private LegoNameList As New ArrayList
Private ShipmentDateList As New ArrayList
Private CostList As New ArrayList
Private NumberPurchasedList As New ArrayList
Private RecipientList As New ArrayList
Private TotalCostList As New ArrayList
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
myDB = New OleDbConnection(myConnection)
sqlCmd = New OleDbCommand("exec qry_OrderHistory")
sqlCmd.Parameters.AddWithValue("#CustomerName", Session("myCart").GetCustomerName())
Try
myDB.Open()
myReader = sqlCmd.ExecuteReader
Do While myReader.Read
LegoNameList.Add(myReader("Lego Name"))
ShipmentDateList.Add(myReader("Date"))
CostList.Add(myReader("Cost"))
NumberPurchasedList.Add(myReader("Number Purchased"))
RecipientList.Add(myReader("Recipient"))
TotalCostList.Add(myReader("Total Cost"))
Loop
myReader.Close()
Catch ex As Exception
MsgBox(ex.ToString)
Finally
myDB.Close()
End Try
Dim myDataTable As New DataTable
myDataTable.Columns.Add("Lego Name")
myDataTable.Columns.Add("Date")
myDataTable.Columns.Add("Cost")
myDataTable.Columns.Add("Number Purchased")
myDataTable.Columns.Add("Recipient")
myDataTable.Columns.Add("Total Cost")
For i = 0 To LegoNameList.Count - 1
Dim myRow As DataRow = myDataTable.NewRow
myRow.Item("Lego Name") = LegoNameList.Item(i)
myRow.Item("Date") = FormatDateTime(ShipmentDateList.Item(i), DateFormat.ShortDate)
myRow.Item("Cost") = FormatCurrency(CostList.Item(i), 2, TriState.True, TriState.False, TriState.True)
myRow.Item("Number Purchased") = NumberPurchasedList.Item(i)
myRow.Item("Recipient") = RecipientList.Item(i)
myRow.Item("Total Cost") = FormatCurrency(TotalCostList.Item(i), 2, TriState.True, TriState.False, TriState.True)
myDataTable.Rows.Add(myRow)
Next
gvwOrderHistory.DataSource = myDataTable
gvwOrderHistory.DataBind()
End Sub
End Class

You have created your connection, and then you create your command, but you never assign the connection to your command, which is why you're getting the error. You can either assign the connection to your OleDbCommand, like this:
sqlCmd.Connection = myDB
Or you can specify in the OleDbCommand constructor, like this:
sqlCmd = New OleDbCommand("exec qry_OrderHistory", myDB)
Then you can open the connection and execute the command.

You have to initialize your Connective instance myConnection before use it

Related

SQL Server connection remains open, even after closing

I have a website that is designed to multi-tiered. My code works, but I have noticed that the larger my app becomes, the more SQL database connections start to stack up and remain open. This eventually causes this error:
System.InvalidOperationException: 'Timeout expired. The timeout
period elapsed prior to obtaining a connection from the pool. This
may have occurred because all pooled connections were in use and max
pool size was reached.'
My code is split into 3 layers. They are:
Application layer. Every time it wants to CRUD, is calls the Business Layer.
Business Layer - does business logic. When it wants to interface with the MS SQL db, it connects via ConnectionAdapter layer.
The ConnectionAdapter inherits from a SqlConnectionAdapter class and does the actual db interactions.
The following is pseudo code for each:
Application
My application may call the business layer multiple times. Particularly when doing AJAX requests. An example would be like:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim dp As New DataProxy
Dim listOfObs As New List(Of MyObject)
dim someId as integer = 1
Try
If Not Page.IsPostBack Then
listOfObs = dp.ExampleReadFuncion(someId)
End If
Catch ex As Exception
Throw
Finally
dp.dispose()
dp = Nothing
SetMenue()
End Try
End Sub
DatatProxy (business layer)
Public Class DataProxy
Dim scConAdapter As New ConnectionAdapter
Public Sub New()
Try
scConAdapter.Connect()
Catch ex As Exception
Throw
End Try
End Sub
Public Sub dispose()
scConAdapter.Dispose()
End Sub
Private Shared Sub Main()
End Sub
Public Function ExampleReadFuncion(ByVal someId As Integer) As List(Of MyObject)
Dim successFactor As LogStatusEnum = LogStatusEnum.INFO
Dim newEx As Exception = Nothing
Dim conn As New ConnectionAdapter
Dim myObj As ActivityMarker
Dim listOfObs As New List(Of MyObject)
Dim dr As SqlDataReader = Nothing
Try
successFactor = LogStatusEnum.INFO
conn.Connect()
dr = conn.ExampleReadFuncion(someId)
Using dr
If (dr.HasRows = True) Then
While dr.Read
myObj = New myObj
myObj.Marker_Id = dr.Item("id")
myObj.Acitvity_Id = dr.Item("someValue")
listOfObs.Add(myObj)
End While
End If
End Using
Return listOfObs
Catch ex As Exception
successFactor = LogStatusEnum.ERRORS
Throw
Finally
dr.Close()
dr = Nothing
conn.Dispose()
conn = Nothing
End Try
End Function
End class
ConnectionAdapter
Public Class ConnectionAdapter
Inherits SqlConnectionAdapter
Public Sub New()
End Sub
Public Function ExampleReadFuncion(ByVal someId As Integer) As SqlDataReader
Try
Dim dr As SqlDataReader = Nothing
Dim selectString As New StringBuilder
Dim cmd As SqlCommand = Nothing
Try
cmd = CreateCommand()
selectString.Append("SELECT * " & vbCrLf)
selectString.Append("FROM " & vbCrLf)
selectString.Append("dbo.mytable " & vbCrLf)
selectString.Append("WHERE " & vbCrLf)
selectString.Append("id = #SOME_ID " & vbCrLf)
With cmd
.CommandType = CommandType.Text
.CommandText = selectString.ToString
.Parameters.Add("#SOME_ID", SqlDbType.Int).Value = someId
dr = .ExecuteReader
End With
Catch ex As Exception
Throw
Finally
cmd.Dispose()
End Try
Return dr
Catch ex As Exception
Throw ex
End Try
End Function
end class
SqlConnectionAdapter
Public MustInherit Class SqlConnectionAdapter
Protected CurrentTransaction As SqlTransaction
Public Property db As SqlConnection
Public Property Password As String
Public Property TNSName As String
Public Property User As String
Public Property DBName As String
Public Property PortNumber As Integer
Public Overridable Sub Dispose()
Try
If Not CurrentTransaction Is Nothing Then
CurrentTransaction.Commit()
End If
Catch ex As Exception
Throw
Finally
If Not db Is Nothing Then
db.Close()
db.Dispose()
db = Nothing
End If
End Try
End Sub
Public Overridable Sub Connect()
Try
Dim appSettings = ConfigurationManager.AppSettings
If (appSettings("releaseVersion") = "DEBUG") Then
Connect(appSettings("db_sqlHost"), appSettings("db_sqlDb"))
Else
Connect(appSettings("db_sqlHost"), appSettings("db_sqlPort"), appSettings("db_sqlDb"), appSettings("db_sqlUser"), appSettings("db_sqlPassword"))
End If
Catch ex As Exception
Throw
End Try
End Sub
Public Sub Connect(ByVal GetServername As String, ByVal GetDatabaseName As String)
Try
TNSName = GetServername
DBName = GetDatabaseName
db = New SqlConnection
db = SqlConnectionUtilities.GetConnection(GetServername, GetDatabaseName)
Catch ex As Exception
Throw
End Try
End Sub
Public Sub Connect(ByVal GetServerName As String, ByVal GetPort As Long, ByVal GetDatabase As String, ByVal GetUsername As String, ByVal Getpassword As String)
Try
User = GetUsername
Password = Getpassword
PortNumber = GetPort
DBName = GetDatabase
TNSName = GetServerName
db = New SqlConnection
db = SqlConnectionUtilities.GetConnection(GetServerName, GetPort, GetDatabase, GetUsername, Getpassword)
Catch ex As Exception
Throw
End Try
End Sub
Protected Function CreateCommand() As SqlCommand
Dim ret As SqlCommand = Nothing
Try
ret = db.CreateCommand
If Not CurrentTransaction Is Nothing Then
ret.Transaction = CurrentTransaction
End If
Catch ex As Exception
Throw
Finally
End Try
Return ret
End Function
Public Sub BeginTransaction()
If CurrentTransaction Is Nothing Then
CurrentTransaction = db.BeginTransaction
End If
End Sub
Public Sub CommitTransaction()
If Not CurrentTransaction Is Nothing Then
CurrentTransaction.Commit()
CurrentTransaction.Dispose()
CurrentTransaction = Nothing
End If
End Sub
Public Sub RollbackTransaction()
If Not CurrentTransaction Is Nothing Then
CurrentTransaction.Rollback()
CurrentTransaction.Dispose()
CurrentTransaction = Nothing
End If
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class
Utilities class
Public Class SqlConnectionUtilities
Public Shared Property connectionString As String
Public Shared Function GetConnection(ByVal ServerName As String, ByVal Port As String, ByVal Database As String, ByVal username As String, ByVal password As String) As SqlConnection
Dim connString As New StringBuilder
Dim con As SqlConnection
Try
connString.Append("Server=tcp:" & ServerName & "," & Port & ";")
connString.Append("Initial Catalog = " & Database & "; Persist Security Info=False;")
connString.Append("User ID = " & username & ";")
connString.Append("Password = " & password & ";")
connString.Append("MultipleActiveResultSets = False;")
connString.Append("Encrypt = True;TrustServerCertificate=False;Connection Timeout=30;")
connectionString = connString.ToString
con = New SqlConnection(connString.ToString)
con.Open()
Return con
Catch ex As Exception
Throw
End Try
End Function
Public Shared Function GetConnection(ByVal Servername As String, ByVal DatabaseName As String) As SqlConnection
Dim ConnectString As String
Dim con As SqlConnection
Try
ConnectString = "Data Source=" & Servername & ";Initial Catalog=" & DatabaseName & ";Integrated Security=True"
connectionString = ConnectString
con = New SqlConnection(ConnectString)
con.Open()
Return con
Catch ex As Exception
Throw
End Try
End Function
End class
I can tell that connections are remaining open by running this SQL statement:
SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName
FROM
sys.sysprocesses
WHERE
dbid > 0
GROUP BY
dbid, loginame
I set up break points when my DataProxy class is called. I run the SQL code and can see a new connection is opened. Then, I run the code again when I dispose of the DataProxy class and I can see the connection remains. This will build up until it hits 101 connections, then it causes the above error. How am I not handling the connections correctly?
System.InvalidOperationException: 'Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.'
How am I not handling the connections correctly?
You are "leaking" connections. IE you have some code path that opens a SqlConnection, and doesn't Close/Dispose it. The SqlConnection remains open and is sitting on the managed heap. Eventually it will be GC'd and its Finalizer will close the connection. But if you leak 100 connections before that happens, you get this error.
So you need to ensure that your SqlConnections are always closed using a USING block, or are managed by some other object that's closed with a USING block.
Note that if you are returning a SqlDataReader from a function, there's a special CommandBehavior that will close the SqlConnection when the SqlDataReader is closed.
No, even this code not work and it wait a few minutes to remove sql connection from sql server.
using (var conn = new SqlConnection(connStr))
{
conn.Open();
conn.Close();
}
GC.Collect();
GC.WaitForPendingFinalizers();

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code error?

When trying to insert the following information into my database I get "An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code error?" error.
My code is as follows:
Imports System.Data.SqlClient
Partial Class SecurePages_AddBackup
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim customer As Integer
Dim backupDate As String
Dim Server As Integer
Dim Status As String
Dim Product As Integer
Dim Details As String
customer = ddlCustomer.SelectedValue
backupDate = clDate.SelectedDate
Server = DDLserver.SelectedValue
Status = DDLStatus.Text
Product = DDLproduct.SelectedValue
Details = txtDetails.Text
Dim cmdstring As String = "INSERT INTO Backup(CustomerID, Date, ServerID, Status, ProductID, Details) Values (#Customer, #BackupDate, #Server, #Status, #Product, #Details)"
conn = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Backups.mdf;Integrated Security=True")
cmd = New SqlCommand(cmdstring, conn)
cmd.Parameters.AddWithValue("#Customer", customer)
cmd.Parameters.AddWithValue("#BackupDate", backupDate)
cmd.Parameters.AddWithValue("#Server", Server)
cmd.Parameters.AddWithValue("#Status", Status)
cmd.Parameters.AddWithValue("#Product", Product)
cmd.Parameters.AddWithValue("#Details", Details)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
lblStatus.Text = "Backup added to the database!"
End Sub
End Class
I'm not sure where I am going wrong.
Backup is a reserved keyword in SQL Server.
Try INSERT INTO [Backup]

display table in gridview for website in vb.net

I am new to vb.net and I want to display an Access table in gridview using vb.net in an ASP.NET secnario.
Public Class Form1
Public Sub New()
InitializeComponent()
BindGrid()
End Sub
Private Sub BindGrid()
Dim constring As String = "Data Source=.\SQL2005;Initial Catalog=Northwind;User id = sa;password=pass#123"
Using con As New SqlConnection(constring)
Using cmd As New SqlCommand("SELECT * FROM Customers", con)
cmd.CommandType = CommandType.Text
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
End Using
End Using
End Using
End Using
End Sub
End Class
Can someone please help me?
To use a ACCESS database you must change your connection string.
Dim constring As String = "Data Source=.\SQL2005;Initial Catalog=Northwind;User id = sa;password=pass#123"
To
http://www.connectionstrings.com/access/
Also
Using ds As New DataSet()
sda.Fill(ds)
GridView1.DataSource = ds.Table(0)
GridView1.DataBind()
End Using

Value of type ... cannot be converted to

I keep receiving the following error whenever I try to run my code. Are there any suggestions on what may be causing me to not be able to convert? It seems as though both types are the same, so I'm a little confused on this one.
Value of type 'System.Collections.Generic.List(Of CVE)' cannot be converted to 'System.Collections.Generic.List(Of CVE)'
Error is occurring here:
Dim cveList As List(Of CVE)
cveList = CVERepository.GetInstance.ReadAllCVEs
Here's the CVERepository class:
Public Class CVERepository
Private Sub New()
End Sub
Public Shared ReadOnly Property GetInstance As CVERepository
Get
Static Instance As CVERepository = New CVERepository
Return Instance
End Get
End Property
Public Function ReadAllCVEs() As List(Of CVE)
Dim objAdapter As OleDb.OleDbDataAdapter
Dim dtCVE As New DataTable()
Dim strSQL As String
Dim strConn As String
Dim dvCVE As DataView
strConn = ConnectStringBuild()
strSQL = "Select * From CVE"
objAdapter = New OleDb.OleDbDataAdapter(strSQL, strConn)
objAdapter.Fill(dtCVE)
dvCVE = dtCVE.DefaultView
Dim cveList As New List(Of CVE)
'Put it into an object list to make it more managable.
For index = 0 To dvCVE.Count - 1
Dim cve As New CVE
cve.ID = dvCVE(index)("CVEID")
cve.PublishedDate = dvCVE(index)("PublishedDate")
cve.Availability = dvCVE(index)("Availability")
cve.CVSSScore = dvCVE(index)("CVSSScore")
cve.Confidentiality = dvCVE(index)("Confidentiality")
cve.Integrity = dvCVE(index)("Integrity")
cve.Summary = dvCVE(index)("Summary")
cveList.Add(cve)
Next
Return cveList
End Function
Public Shared Function ConnectStringBuild() As String
'Grabbing connection string from web.config
Return System.Configuration.ConfigurationManager.ConnectionStrings("CVEConnectionString").ConnectionString
End Function
End Class
Any suggestion on the error?
just a little change
Dim cveList As List(Of CVE)
cveList.AddRange(CVERepository.GetInstance.ReadAllCVEs)

Upload Image in ASP.NET VB

Is there any way an image can be uploaded with ASP.NET with VB?
I need an "upload" button on the ASP.NET side.
I already have an image field in the table in SQL server 2008.
Is there any way I can do this?
Add a fileupload control with:
<asp:FileUpload runat="server" id="FileUpload1" />
Add an upload button, and place this in the button click event handler:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim bldgIDNum As Int32 = FormView_Building.SelectedValue
If FileUpload1.PostedFile IsNot Nothing AndAlso FileUpload1.PostedFile.FileName <> "" Then
Dim imageSize As Byte() = New Byte(FileUpload1.PostedFile.ContentLength - 1) {}
Dim uploadedImage__1 As HttpPostedFile = FileUpload1.PostedFile
uploadedImage__1.InputStream.Read(imageSize, 0, CInt(FileUpload1.PostedFile.ContentLength))
' Create SQL Connection
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "INSERT INTO Table (PrimaryKey,ImageData) VALUES (#PrimaryKey,#ImageData)"
cmd.CommandType = CommandType.Text
cmd.Connection = con
Dim PrimaryKey As New SqlParameter("#PrimaryKey", SqlDbType.Int, 32)
PrimaryKey.Value = (however you want to get it)
Dim UploadedImage__2 As New SqlParameter("#ImageData", SqlDbType.Image, imageSize.Length)
UploadedImage__2.Value = imageSize
cmd.Parameters.Add(UploadedImage__2)
con.Open()
Dim result As Integer = cmd.ExecuteNonQuery()
con.Close()
If result > 0 Then
lblMessage.Text = "File Uploaded"
End If
End If
ListView_BldgImages.DataBind()
End Sub
The database column ImageData should be varbinary(max)
Create a handler called Handler_Image.ashx with the following content:
Imports System
Imports System.Web
Imports System.Configuration
Imports System.Data.SqlClient
Public Class Handler_Image : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "Select ImageData from Table where PrimaryKey =#PrimaryKey"
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
Dim ID As New SqlParameter("#PrimaryKey", System.Data.SqlDbType.Int)
ID.Value = context.Request.QueryString("PrimaryKey")
cmd.Parameters.Add(ID)
con.Open()
Dim dReader As SqlDataReader = cmd.ExecuteReader()
dReader.Read()
context.Response.BinaryWrite(DirectCast(dReader("ImageData"), Byte()))
dReader.Close()
con.Close()
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Display the image with an image control with the following property:
ImageUrl='<%# "Handler_Image.ashx?PrimaryKey=" & Eval("PrimaryKey")%>'
Replace the connectionstring, the table name, and the primary key to suit your application

Resources