Any possible chance for a memory leak? - asp.net

i get this error System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException was thrown.` Why?? Kindly help me. I get this error (only when i host the website online, not in local machine).
Dim db As SqlDatabase = Connection.connection
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
'Dim lblNodeID As Label = CType(Master.FindControl("lblParentId"), Label)
Using conn As DbConnection = db.CreateConnection()
Dim cmdInsertGroup As SqlCommand = db.GetSqlStringCommand("Insert Into CategoryGroups Values ('" & BLL.getNewGroupIDfromCategoryGroups & "','" & lblParentId.Text.Trim & "','" & txtGroupName.Text.Trim & "')")
Try
If fuGroupAttributes.HasFile Then
fuGroupAttributes.SaveAs(IO.Path.Combine(Server.MapPath("~/Admin/SpecificationExcels"), lblParentId.Text.Trim & IO.Path.GetExtension(fuGroupAttributes.FileName)))
Dim path As String = Server.MapPath("~/Admin/SpecificationExcels/" & lblParentId.Text.Trim & IO.Path.GetExtension(fuGroupAttributes.FileName))
Dim strmail As String = String.Empty
Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & path & ";Extended Properties=Excel 12.0;"
Dim objConn As New OleDbConnection(connectionString)
objConn.Open()
Dim strConString As String = "SELECT * FROM [Sheet1$]"
'where date = CDate('" + DateTime.Today.ToShortDateString() + "')";
Dim objCmdSelect As New OleDbCommand(strConString, objConn)
' Create new OleDbDataAdapter that is used to build a DataSet
' based on the preceding SQL SELECT statement.
Dim objAdapter1 As New OleDbDataAdapter()
' Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect
' Create new DataSet to hold information from the worksheet.
Dim ds As New DataSet()
' Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(ds, "ExcelData")
'My Exp
Dim _newAttributeID As Integer = BLL.getNewAttributeIDfromGroupAttributes
Dim _newGroupID As Integer
conn.Open()
Dim trans As DbTransaction = conn.BeginTransaction()
If cbInsertInExistingGroup.Checked Then
If gvExistingGroups.SelectedValue IsNot Nothing Then
_newGroupID = gvExistingGroups.SelectedRow.Cells(1).Text
Else
pnlMessage.Visible = True
pnlMessage.BackColor = Drawing.Color.Red
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Select a Group"
Exit Sub
End If
Else
_newGroupID = BLL.getNewGroupIDfromCategoryGroups
db.ExecuteNonQuery(cmdInsertGroup, trans)
End If
For i = 0 To ds.Tables(0).Rows.Count - 1
ds.Tables(0).Rows(i).Item(0) = _newAttributeID
ds.Tables(0).Rows(i).Item(1) = _newGroupID
_newAttributeID = _newAttributeID + 1
Next
' Clean up objects.
objConn.Close()
'Dim db As SqlDatabase = Connection.connection
Dim sqlBulk As New SqlBulkCopy(conn, SqlBulkCopyOptions.Default, trans)
sqlBulk.DestinationTableName = "GroupAttributes"
sqlBulk.WriteToServer(ds.Tables(0))
trans.Commit() ' commit the transaction
pnlMessage.Visible = True
pnlMessage.BackColor = Drawing.Color.Green
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Successfully Uploaded"
'Response.Redirect("~/Admin/AddSpecifications.aspx?id=" & Request.QueryString(0))
Else
pnlMessage.Visible = True
pnlMessage.BackColor = Drawing.Color.Red
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Select an Excel File"
'Response.Write("")
End If
Catch ex As Exception
trans.Rollback() ' rollback the transaction
pnlMessage.BackColor = Drawing.Color.Red
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Some Error Occured"
End Try
End Using
End Sub

Your code is a bit complicated to follow, but in this block you Exit Sub without closing the connection objConn
If cbInsertInExistingGroup.Checked Then
If gvExistingGroups.SelectedValue IsNot Nothing Then
_newGroupID = gvExistingGroups.SelectedRow.Cells(1).Text
Else
pnlMessage.Visible = True
pnlMessage.BackColor = Drawing.Color.Red
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Select a Group"
Exit Sub
End If
You should really try to refactor this huge block of code in more small units. In this way you could use the Using statement to dispose correctly of the Disposable objects like OleDbConnection, OleDbAdapter, OleDbCommand....

Related

Server cannot append header after HTTP headers have been sent. vb.net

I'm working on something where I should export an information to a csv file, but when I try to download it in the line Response.AddHeader(" content-disposition "attachment; filename = GridViewExport.csv")
I get the error:
Server can not append header after HTTP headers have been sent.
My gridview is inside og a update panel
Public Sub archivoGenerado()
For Each RW As GridViewRow In Dgdatoo.Rows
If CType(RW.Cells(10).FindControl("CheckBox2"), CheckBox).Checked = True Then
'If CType(RW.Cells(10).FindControl("Radio"), RadioButton).Checked = True Then
Dim estatus As [String] = CType(RW.Cells(8).FindControl("LabEs"), Label).Text
Dim Centro As [String] = DirectCast(RW.Cells(1).FindControl("LabeCe"), Label).Text
Dim almacen As [String] = DirectCast(RW.Cells(3).FindControl("LabeAl"), Label).Text
Dim Dupla As [String] = DirectCast(RW.Cells(6).FindControl("LabeDu"), Label).Text
Dim constr As New Data.SqlClient.SqlConnection
constr.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
Using cmd As New SqlCommand("Select Vw_RptInventarioSAP.IdMaterial as 'Barcode / Item-ID',Vw_RptInventarioSAP.MaterialNombre as'Description',S_AsignacionDuplas.Cantidad as 'Quantity',Vw_RptInventarioSAP.IdLote as 'Lote',S_AsignacionDuplas.IdCentro as 'Centro',S_AsignacionDuplas.IdAlamacen as 'Almacen',S_AsignacionDuplas.IdDupla as 'Dupla' from Vw_RptInventarioSAP inner join S_AsignacionDuplas on Vw_RptInventarioSAP.IdMaterial = S_AsignacionDuplas.IdMaterial where S_AsignacionDuplas.IdDupla = '" & Dupla & "' and IdCentro ='" & Centro & "' and IdAlmacen= '" & almacen & "'")
Using sda As New SqlDataAdapter()
cmd.Connection = constr
sda.SelectCommand = cmd
Dim da As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
'Build the CSV file data as a Comma separated string.
Dim csv As New StringBuilder()
For i As Integer = 0 To dt.Columns.Count - 1
csv.Append(dt.Columns(i).ColumnName + ",")
Next
csv.Append(Environment.NewLine)
For j As Integer = 0 To dt.Rows.Count - 1
For k As Integer = 0 To dt.Columns.Count - 1
csv.Append(dt.Rows(j)(k).ToString() + ",")
Next
csv.Append(Environment.NewLine)
Next
For Each RW2 As GridViewRow In Dgdatoo.Rows
Response.Clear()
Response.ClearContent()
Response.ContentType = "text/csv"
Response.AddHeader("content-disposition","attachment;filename=GridViewExport.csv")
Response.Write(csv.ToString())
Response.Flush()
Next
'Next
End Using
End Using
End Using
Else
With lbError0
.Visible = True
.Text = "Selecionar inventario a descargar"
End With
End If
Next
End Sub

database cannot update textbox value in vb.net

I am doing a update profile in a web application using vb.net. At first I read the database and put the data into the textbox, then i change the data inside the textbox and click the 'update' button. The problem is when i click the button, it won't update the latest value that i typed into the textbox. It will still update the value where i read from database.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim item1 As String = CType(Session.Item("UserAccount"), String)
txtUsername.Enabled = False
conn.Open()
sql1 = "Select * From [Users] WHERE username='" & item1 & "'"
cmd = New SqlCommand(sql1, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows Then
txtUsername.Text = dr.Item("username")
password = dr.Item("password")
txtFirstName.Text = dr.Item("firstname")
txtLastName.Text = dr.Item("lastname")
txtDob.Text = dr.Item("dob")
txtEmail.Text = dr.Item("email")
txtNumber.Text = dr.Item("phone")
txtAddress.Text = dr.Item("address")
End If
dr.Close()
conn.Close()
End Sub
'above this image is how i read from the database.
Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim errFirstName As Boolean = True
Dim errLastName As Boolean = True
Dim errCPassword As Boolean = True
Dim errNPassword As Boolean = True
Dim errDob As Boolean = True
Dim errEmail As Boolean = True
Dim errNumber As Boolean = True
Dim errAddress As Boolean = True
Dim newFName, newLName, newPassword, newAddress, newNumber, newEmail, newDob As String
If txtFirstName.Text = "" Then
txtFirstName.BackColor = Drawing.Color.LightPink
lblFirstName.Text = "cannot be empty"
ElseIf Not Regex.Match(txtFirstName.Text, "^[a-zA-Z_ ]*$", RegexOptions.IgnoreCase).Success Then
.
.
.
This is the 'Update' button click.
Here is where i do all the validation for the value in textbox
If errNPassword = False And errCPassword = False And errFirstName = False And errLastName = False And errDob = False And errEmail = False And errNumber = False And errAddress = False Then
conn.Open()
sql2 = "Update [Users] Set password='" & newPassword & "', firstname='" & newFName & "', lastname='" & newLName & "', dob='" & newDob & "', address='" & newAddress & "', email='" & newEmail & "', phone='" & newNumber & "' WHERE username='" & txtUsername.Text & "'"
cmd = New SqlCommand(sql2, conn)
cmd.ExecuteNonQuery()
conn.Close()
Response.Redirect(String.Format("~/index.aspx?"))
Else
Dim message As String = "Please correct the error above"
Dim sb As New System.Text.StringBuilder()
sb.Append("<script type = 'text/javascript'>")
sb.Append("window.onload=function(){")
sb.Append("alert('")
sb.Append(message)
sb.Append("')};")
sb.Append("</script>")
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", sb.ToString())
Exit Sub 'break
End If
This is how i update the value of textbox to my database where the username is match.
Your page is posting back and running the same code, you have to add If Not IsPostBack to Page_Load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack
Dim item1 As String = CType(Session.Item("UserAccount"), String)
txtUsername.Enabled = False
conn.Open()
sql1 = "Select * From [Users] WHERE username='" & item1 & "'"
cmd = New SqlCommand(sql1, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows Then
txtUsername.Text = dr.Item("username")
password = dr.Item("password")
txtFirstName.Text = dr.Item("firstname")
txtLastName.Text = dr.Item("lastname")
txtDob.Text = dr.Item("dob")
txtEmail.Text = dr.Item("email")
txtNumber.Text = dr.Item("phone")
txtAddress.Text = dr.Item("address")
End If
dr.Close()
conn.Close()
End If
End Sub

unhandles exception error when login page idle

I have developed a site in vb.net (with some help from my brother in law) and it's almost ready to roll out except I am getting an unhandled exception error on the login
screen when the page is idle for a few minutes. I am reasonably new to vb.net and not a programmer :( Any help would be really appreciated. Sorry if anything in my post is not to the site standard as this is my first post. :)
I'm not sure why this is happening. The code that is executed on login_buttonClick is:
Protected Sub LoginWizard_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles LoginWizard.FinishButtonClick
Dim oUsername As String = txtUsername.Text
Dim oPassword As String = txtPassword.Text
Dim oPath As String = Server.MapPath("App_Data/IOFR.mdb")
Dim oValid As Boolean = False
Dim oReader As System.Data.OleDb.OleDbDataReader = Nothing
Dim oConnection As System.Data.OleDb.OleDbConnection = Nothing
Dim oName As String = ""
Dim oOrg As String = ""
Dim oUserId As Integer = 0
Dim oActiveAcc As String = ""
Dim oSessionExpire As Integer = 0
Try
oConnection = New System.Data.OleDb.OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Jet OLEDB:Database Password=EdmundColin13", oPath))
oConnection.Open()
Dim ipAddress As String = Request.ServerVariables("REMOTE_ADDR")
Dim cmd As New SqlCommand
Dim oParams As New List(Of System.Data.OleDb.OleDbParameter)
oParams.Add(New System.Data.OleDb.OleDbParameter("#pmUsername", oUsername))
oParams.Add(New System.Data.OleDb.OleDbParameter("#pmPassowrd", oPassword))
Dim oCommand As New System.Data.OleDb.OleDbCommand("SELECT ID, [Name], Organisation, ActiveAccount, [Password] FROM Users WHERE [Username] = #pmUsername AND [Password] = #pmPassword", oConnection)
oCommand.Parameters.AddRange(oParams.ToArray)
oReader = oCommand.ExecuteReader()
If oReader.Read() Then
oValid = True
oName = oReader.GetString(oReader.GetOrdinal("Name"))
oActiveAcc = oReader.GetString(oReader.GetOrdinal("ActiveAccount"))
oOrg = oReader.GetString(oReader.GetOrdinal("Organisation"))
oPassword = oReader.GetString(oReader.GetOrdinal("Password"))
oUserId = oReader.GetInt32(oReader.GetOrdinal("ID"))
oSessionExpire = oReader.GetInt32(oReader.GetOrdinal("SessionExpire"))
End If
Catch ex As Exception
Finally
If Not oReader Is Nothing Then
If Not oReader.IsClosed Then
oReader.Close()
End If
oReader = Nothing
End If
End Try
If oValid And Not String.Equals(txtPassword.Text, oPassword) Then
oValid = False
End If
If oValid Then
If oActiveAcc = "No" Then
Response.Redirect("~/DisabledAccount.aspx")
Return
End If
Session("username") = txtUsername.Text
Session("name") = oName
Session("org") = oOrg
'Generate session id and store it in session
Dim uniquesessionid As String = Guid.NewGuid().ToString()
Session("uid") = uniquesessionid
Dim oCommandSession As New System.Data.OleDb.OleDbCommand("UPDATE Users SET SessionId = #pmid, SessionExpire = '" & DateTime.Now.AddHours(2).ToString() & "' WHERE [ID] = #pmUserid", oConnection)
oCommandSession.Parameters.Add(New System.Data.OleDb.OleDbParameter("#pmid", uniquesessionid))
oCommandSession.Parameters.Add(New System.Data.OleDb.OleDbParameter("#pmUserid", oUserId))
oCommandSession.ExecuteNonQuery()
Response.Redirect("~/Home.aspx?login=true")
Else
txtUsername.BorderColor = Drawing.Color.Red
txtUsername.BackColor = Drawing.Color.Red
txtPassword.BorderColor = Drawing.Color.Red
FailedLogin.Visible = True
End If
If Not oConnection Is Nothing Then
If oConnection.State = Data.ConnectionState.Open Then
oConnection.Close()
End If
End If
End Sub
Thanks All. This seams to have resolved the issue.
EnableViewStateMAC="False"

changing the way of coding so that MS Excel is not to be needed to installed on server in asp.net

I have started to deveop a website using asp.net.
I need to fetch some data from excel to display it to the client.
I am hosting my site on somee.com so that I can freely host it.
But on the server of somee.com Excel is not installed.
I have written some code for my website to display the data from from excel.
Dim xlApp As New Microsoft.Office.Interop.Excel.Application()
Dim xlWorkbook As Microsoft.Office.Interop.Excel.Workbook = xlApp.Workbooks.Open(FileUploadPath & sender.text)
Dim xlWorksheet As Microsoft.Office.Interop.Excel._Worksheet = xlWorkbook.Sheets(SheetName)
Dim xlRange As Microsoft.Office.Interop.Excel.Range = xlWorksheet.UsedRange
Dim rowCount As Integer = xlRange.Rows.Count
Dim colCount As Integer = xlRange.Columns.Count
Dim tbl As New DataTable()
For i As Integer = 1 To rowCount
tbl.Rows.Add()
Next
For i As Integer = 1 To colCount
tbl.Columns.Add()
Next
If rowCount > 1 Or colCount > 1 Then
For i As Integer = 1 To rowCount
For j As Integer = 1 To colCount
tbl.Rows(i - 1)(j - 1) = xlRange.Value2(i, j)
Next j
Next i
End If
gvReadFiles.AutoGenerateColumns = True
gvReadFiles.DataSource = tbl
gvReadFiles.DataBind()
xlApp.ActiveWorkbook.Close(False, Session(FileUploadPath & sender.text))
xlApp.Quit()
xlWorkbook = Nothing
xlApp = Nothing
Now I need to have some changes in code so it is not excel dependent.
Can you help me?
I solved it using google for more than 2 hours.
Here is the code
Dim objConn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Try
Dim connString As String = ""
If Extension = "xls" Or Extension = ".xls" Then
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FileUploadPath & sender.text & ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 8.0;HDR=No;IMEX=1" + Convert.ToChar(34).ToString() + ""
ElseIf Extension = "xlsx" Or Extension = ".xlsx" Then
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & FileUploadPath & sender.text & ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 12.0;HDR=No;IMEX=1" + Convert.ToChar(34).ToString() + ""
End If
objConn = New OleDbConnection(connString)
objConn.Open()
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim firstSheetName As String = "Sheet1"
If Not dt Is Nothing Then
Dim excelSheets As [String]() = New [String](dt.Rows.Count - 1) {}
' Add the sheet name to the string array.
For Each row As DataRow In dt.Rows
firstSheetName = row("TABLE_NAME").ToString().Substring(0, row("TABLE_NAME").ToString.Length - 1)
Exit For
Next
End If
Return firstSheetName
Catch ex As Exception
Return "Sheet1"
Finally
If objConn IsNot Nothing Then
objConn.Close()
objConn.Dispose()
End If
If dt IsNot Nothing Then
dt.Dispose()
End If
End Try

Adding a new record to an Access database via vb.net

Do i need to have a new ID generate within vb if I have it set to AutoID in the table itself?
I currently have
Protected Sub deleteButton_Click(sender As Object, e As System.EventArgs) Handles deleteButton.Click
Dim deleteSQL As String
deleteSQL = "DELETE FROM Authors WHERE au_id=#au_id"
Dim myConnection As New SqlConnection(connectionString)
Dim myCommand As New SqlCommand(deleteSQL, myConnection)
myCommand.Parameters.AddWithValue("#au_id", authorDropDownList.SelectedItem.Value)
Dim successBoolean As Boolean = True
Dim index As Integer = authorDropDownList.SelectedIndex
Try
myConnection.Open()
successBoolean = myCommand.ExecuteNonQuery
'authorLabel.Text = "Record Deleted"
'authorLabel.Visible = True
Catch ex As Exception
successBoolean = False
authorLabel.Text = "Error deleting author. " & ex.Message
authorLabel.Visible = True
Finally
myConnection.Close()
End Try
If successBoolean Then
FillAutherList(index)
authorDropDownList_SelectedIndexChanged(sender, e)
authorLabel.Text = "Record Deleted"
authorLabel.Visible = True
End If
End Sub
Dim insertSQL As New StringBuilder
Dim currentDate As String
currentDate = DateTime.Now.ToString
insertSQL.Append("INSERT INTO Story_Table (Author,Content,Submission_Date)") 'Inserts new story
insertSQL.Append(" VALUES (#Author,#Content,#Submission_Date)") 'Sets the story values
Dim myConnection As New SqlConnection(connectionString)
Dim myCommand As New SqlCommand(insertSQL.ToString, myConnection)
With myCommand.Parameters 'Do this next
.AddWithValue("#Author", authorTextBox.Text)
.AddWithValue("#Content", storyTextBox.Text)
.AddWithValue("#Submission_Date", currentDate)
End With
Dim successBoolean As Boolean = True
Try
myConnection.Open()
successBoolean = myCommand.ExecuteNonQuery
resultLabel.Text = "Thanks for the Story! Look for it on the homepage."
resultLabel.Visible = True
Catch ex As Exception
successBoolean = False
resultLabel.Text = "Error inserting story. " & ex.Message
resultLabel.Visible = True
storyLabel.Text = storyTextBox.Text
storyLabel.Visible = True
Finally
myConnection.Close()
End Try`

Resources