I am having a problem with my try catch block runs in the error:
database is not available
My problem is the try catch runs and catches the error, but it will not redirect to my error page. The code continues to execute the other subs. I have tried adding: exit, return, response.end. None of them worked. Thank you for your help.
Imports System.Data
Imports EUC
Imports System.Threading
Imports System.Data.SqlClient
Partial Class mpMain
Inherits System.Web.UI.MasterPage
Dim strSQL As String
Dim objData As clsDataAccess = New clsDataAccess()
Dim ds As New D
ataSet
Dim t1 As DataTable
Dim intSecurityLevel As String = 0
Dim strUser As String = UCase(Right(HttpContext.Current.User.Identity.Name.ToString(), 4))
Protected Sub ExpandNode(ByVal NodeName As String, ByVal PageName As String)
'More Code
End Sub
Protected Sub ExpandNode2(ByVal NodeNameMain As String, ByVal NodeName As String, ByVal PageName As String)
'More Code
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (IsPostBack) Then
Try
strSQL = "Select SecurityLevel from tblSecurity where SFID = #SFID order by SecurityLevel"
Dim MyParameters1 As SqlParameter() = { _
New SqlParameter("#SFID", SqlDbType.VarChar) _
}
MyParameters1(0).Value = UCase(Right(HttpContext.Current.User.Identity.Name.ToString(), 4))
ds = objData.SQLExecuteDataset(strSQL, CommandType.Text, MyParameters1)
t1 = ds.Tables(0)
Catch ex As Exception
Dim sendError As New clsExceptionMessage
sendError.sendMessage(ex.Message, Request.Path, strSQL)
Response.Redirect("ErrorMessage.aspx", False)
End Try
End If
End Sub
Protected Sub TreeView1_TreeNodeDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles TreeView1.TreeNodeDataBound
'More Code
End Sub
Protected Sub TreeView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.DataBound
'More Code
End Sub
End Class
Firstly I would catch SQLException, you rarely want to catch a general exception.
In the catch block, set a boolean parameter such as
hasError = True
and once outside the try..catch block check for this to be true and redirect from there.
Related
Trying to call a function in code behind but not working - one suggestion was to use the OnAuthenticate instead of the OnClick however this requires a rewrite of the entire authentication process.
<asp:Login ID="Login1" runat="server" OnClick="MyButton" DestinationPageUrl="~/Receipt.aspx"
UserNameLabelText="User Name (From: mysite.com):"
PasswordRecoveryText="Forgot User Name or Password?"
PasswordRecoveryUrl="~/GetPassword.aspx">
</asp:Login>
vb code:
Protected Sub MyButton(ByVal sender As Object, ByVal e As System.EventArgs)
Dim username As String = Login1.UserName
Dim currentDateTime As DateTime = DateTime.Now.AddHours(3)
Dim filepath As String = Server.MapPath("~") + "\debug.txt"
Using writer As StreamWriter = File.AppendText(filepath)
writer.WriteLine(username)
writer.WriteLine(currentDateTime)
writer.WriteLine("")
End Using
End Sub
Revised Code:
Imports System.IO
Imports System.Data
Partial Class Login
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xUserName As String = User.Identity.Name()
'UpdateLastLoginDate(xUserName)
End Sub
Protected Sub MyButton(ByVal sender As Object, ByVal e As System.EventArgs)
Dim username As String = Login1.UserName
Dim pw As String = Login1.Password
Dim currentDateTime As DateTime = DateTime.Now.AddHours(3)
Dim filepath As String = Server.MapPath("~") + "\debug.txt"
Using writer As StreamWriter = File.AppendText(filepath)
writer.WriteLine(username)
writer.WriteLine(pw)
writer.WriteLine(currentDateTime)
writer.WriteLine("REMOTE_ADDR: " + Request.Servervariables("REMOTE_ADDR"))
writer.WriteLine("USER_AGENT: " + Request.Servervariables("HTTP_USER_AGENT"))
writer.WriteLine("LOCAL_ADDR: " + Request.Servervariables("LOCAL_ADDR"))
writer.WriteLine("LOGON_USER: " + Request.Servervariables("LOGON_USER"))
'writer.WriteLine(Request.Servervariables("ALL_HTTP"))
writer.WriteLine("")
End Using
End Sub
Protected Sub Page_PreInit(sender As Object, e As EventArgs)
WireLoginControlButtonClickEvent(Login1)
End Sub
Private Sub WireLoginControlButtonClickEvent(parent As Control)
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is Button Then
AddHandler DirectCast(ctrl, Button).Click, Function() (MyFunction())
ElseIf ctrl.HasControls() Then
WireLoginControlButtonClickEvent(ctrl)
End If
Next
End Sub
Private Function MyFunction() As String
Response.Write("Function Called")
Return Nothing
End Function
End Class
Give this a try:
Protected Sub Page_PreInit(sender As Object, e As EventArgs)
WireLoginControlButtonClickEvent(Login1)
End Sub
Private Sub WireLoginControlButtonClickEvent(parent As Control)
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is Button Then
AddHandler DirectCast(ctrl, Button).Click, AddressOf MyFunction
ElseIf ctrl.HasControls() Then
WireLoginControlButtonClickEvent(ctrl)
End If
Next
End Sub
Private Sub MyFunction(sender As Object, e As EventArgs)
Response.Write("Function Called")
End Sub
Partial Class admin_upload
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim UpPath As String
Dim UpName As String
UpPath = "/images"
UpName = Dir(UpPath, vbDirectory)
If (UpName = "") Then
MkDir("/images")
End If
End Sub
Protected Sub uplodto_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uplodto.Click
FileName.InnerHtml = FileFiled.PostedFile.FileName
FileContent.InnerHtml = FileFiled.PostedFile.ContentType
FileSize.InnerHtml = FileFiled.PostedFile.ContentLength
UploadDetails.Visible = True
Dim myfilename As String
myfilename = FileFiled.PostedFile.FileName
Dim c As String = System.IO.Path.GetFileName(myfilename)
Try
FileFiled.PostedFile.SaveAs("images\" + c)
Span1.InnerHtml = "File uploaded successfuly"
Catch ex As Exception
Span1.InnerHtml = "faild"
UploadDetails.Visible = False
End Try
End Sub
End Class
i want to make the direction of files on the web site folders & server
If Not System.IO.Directory.Exists(Server.MapPath("~/images/")) Then
System.IO.Directory.CreateDirectory(Server.MapPath("~/images/"))
End If
I am completely new to ASP.NET and VB as well as C#. I am trying to add customers to a contact list out of a DB. Then the list can be referenced to call them up.
But when I try to run it I get System.NullReferenceException: Object reference not set to an instance of an object. In line 19.
Here is my code:
Page 1 is default page...it connects to the database and grabs the contact information and allows me to select the current contact and add them to a listbox on a separate page:
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Private SelectedCustomer As Customer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
If Not IsPostBack Then
ddlCustomers.DataBind()
End If
SelectedCustomer = Me.GetSelectedCustomer
Me.DisplayCustomer()
End Sub
Private Function GetSelectedCustomer() As Customer
Dim dvTable As dataview = CType(AccessDataSource1.Select( _
DataSourceSelectArguments.Empty), dataview)
dvTable.RowFilter = "CustomerID = " & ddlCustomers.SelectedValue
Dim drvRow As DataRowView = dvTable(0)
Dim customer As New Customer
customer.CustomerID = CInt(drvRow("CustomerID"))
customer.Name = drvRow("Name").ToString
customer.Address = drvRow("Address").ToString
customer.City = drvRow("City").ToString
customer.State = drvRow("State").ToString
customer.ZipCode = drvRow("ZipCode").ToString
customer.Phone = drvRow("Phone").ToString
customer.Email = drvRow("Email").ToString
Return customer
End Function
Private Sub DisplayCustomer()
lblAddress.Text = SelectedCustomer.Address
lblCityStateZip.Text = SelectedCustomer.City & ", " _
& SelectedCustomer.State & " " _
& SelectedCustomer.ZipCode
lblPhone.Text = SelectedCustomer.Phone
lblEmail.Text = SelectedCustomer.Email
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
If Page.IsValid Then
Dim customerItem As New Customer
customerItem.Name = SelectedCustomer.ToString
Me.AddToCustomer(customerItem)
Response.Redirect("CustomerList.aspx")
End If
End Sub
Private Sub AddToCustomer(ByVal customerItem As Customer)
Dim customer As SortedList = Me.GetCustomer
Dim customerID As String = SelectedCustomer.CustomerID
If customer.ContainsKey(customerID) Then
customerItem = CType(customer(customerID), Customer)
Else
customer.Add(customerID, customerItem)
End If
End Sub
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Customer"), SortedList)
End Function
End Class
The next bit of code allows me to add the contact to a list box:
Partial Class Default2
Inherits System.Web.UI.Page
Private Customer As SortedList
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Customer = Me.GetCustomer
If Not IsPostBack Then Me.DisplayCustomer()
End Sub
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function
Private Sub DisplayCustomer()
lstCustomer.Items.Clear()
Dim customerItem As Customer
For Each customerEntry As DictionaryEntry In Customer
customerItem = CType(customerEntry.Value, Customer)
lstCustomer.Items.Add(customerItem.Name)
Next
End Sub
Protected Sub lstCustomer_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstCustomer.SelectedIndexChanged
End Sub
End Class
The error occurs on line 19 (For Each customerEntry As DictionaryEntry In Customer) in the second set of code from the default2 class. Any ideas? I am completely new to ASP.NET just trying to learn. I more at home on PHP, Java, and Actionscript unfortunately.
I think the problem is in this function
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function
You initialise Customer here but then pull out of Session("Cart")
I think what you meant to do is
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Customer"), SortedList)
End Function
Now customer should always be initialised whereas before it might not have been which would cause the NullReferenceException that you are getting.
For some reason my code is not adding customer to the session. I am new to ASP.NET does anyone have any input as to why this is happening and maybe able to give some code example. Thanks!
Below it the code.
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Private SelectedCustomer As Customer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
If Not IsPostBack Then
ddlCustomers.DataBind()
End If
SelectedCustomer = Me.GetSelectedCustomer
Me.DisplayCustomer()
End Sub
Private Function GetSelectedCustomer() As Customer
Dim dvTable As dataview = CType(AccessDataSource1.Select( _
DataSourceSelectArguments.Empty), dataview)
dvTable.RowFilter = "CustomerID = " & ddlCustomers.SelectedValue
Dim drvRow As DataRowView = dvTable(0)
Dim customer As New Customer
customer.CustomerID = CInt(drvRow("CustomerID"))
customer.Name = drvRow("Name").ToString
customer.Address = drvRow("Address").ToString
customer.City = drvRow("City").ToString
customer.State = drvRow("State").ToString
customer.ZipCode = drvRow("ZipCode").ToString
customer.Phone = drvRow("Phone").ToString
customer.Email = drvRow("Email").ToString
Return customer
End Function
Private Sub DisplayCustomer()
lblAddress.Text = SelectedCustomer.Address
lblCityStateZip.Text = SelectedCustomer.City & ", " _
& SelectedCustomer.State & " " _
& SelectedCustomer.ZipCode
lblPhone.Text = SelectedCustomer.Phone
lblEmail.Text = SelectedCustomer.Email
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
If Page.IsValid Then
Dim customerItem As New Customer
customerItem.Name = SelectedCustomer.ToString
Me.AddToCustomer(customerItem)
Response.Redirect("CustomerList.aspx")
End If
End Sub
Private Sub AddToCustomer(ByVal customerItem As Customer)
Dim customer As SortedList = Me.GetCustomer
Dim customerID As String = SelectedCustomer.CustomerID
If customer.ContainsKey(customerID) Then
customerItem = CType(customer(customerID), Customer)
Else
customer.Add(customerID, customerItem)
End If
End Sub
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Customer"), SortedList)
End Function
End Class
Second page of code below:
Partial Class Default2
Inherits System.Web.UI.Page
Private Customer As SortedList
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Customer = Me.GetCustomer
If Not IsPostBack Then Me.DisplayCustomer()
End Sub
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Customer"), SortedList)
End Function
Private Sub DisplayCustomer()
lstCustomer.Items.Clear()
Dim customerItem As Customer
For Each customerEntry As DictionaryEntry In Customer
customerItem = CType(customerEntry.Value, Customer)
lstCustomer.Items.Add(customerItem.Name)
Next
End Sub
Protected Sub lstCustomer_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstCustomer.SelectedIndexChanged
End Sub
Protected Sub Clearbtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Clearbtn.Click
If Customer.Count > 0 Then
Customer.Clear()
lstCustomer.Items.Clear()
Else
clrErr.Text = "ERROR: NO CUSTOMERS STORED"
End If
End Sub
End Class
I think I've actually answered this in another of your questions
You need to add a line to actually store the updated customer object back into Session for example
Private Sub AddToCustomer(ByVal customerItem As Customer)
Dim customer As SortedList = Me.GetCustomer
Dim customerID As String = SelectedCustomer.CustomerID
If customer.ContainsKey(customerID) Then
customerItem = CType(customer(customerID), Customer)
Else
customer.Add(customerID, customerItem)
End If
Session("Customer") = customer
End Sub
Although I'd recommend you put this in another function so that your design doesn't depend on Session if you want to change it later on. So more like
Private Sub AddToCustomer(ByVal customerItem As Customer)
Dim customer As SortedList = Me.GetCustomer
Dim customerID As String = SelectedCustomer.CustomerID
If customer.ContainsKey(customerID) Then
customerItem = CType(customer(customerID), Customer)
Else
customer.Add(customerID, customerItem)
End If
StoreCustomer(customer)
End Sub
Private Sub StoreCustomer(ByVal customer As SortedList)
Session("Customer") = customer
End Sub
At the moment all local changes to customer are lost just after the call toto AddToCustomer as you then do a redirect after.
Me.AddToCustomer(customerItem)
Response.Redirect("CustomerList.aspx")
Imports System.Net.Mail
Partial Class ContactUs
Inherits System.Web.UI.Page
Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton1.Click
Dim username = User.Identity.Name.ToString
Response.Redirect("~/ViewCart_aspx/ViewCart.aspx?userID=" & username)
End Sub
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
If txtComments.Text.Length > 200 Then
args.IsValid = False
Else
args.IsValid = True
End If
End Sub
Protected Sub WizardStep3_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles WizardStep3.Load
lblName.text = txtName.Text
lblEmail.Text = txtEmail.Text
lblComments.Text = txtComments.Text
lblRating.Text = txtRatings.Text
End Sub
Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick
SendMail(txtEmail.Text, txtComments.Text)
'MsgBox("Feedback Sent")
Response.Redirect("homepage_aspx/homepage.aspx")
End Sub
Private Sub SendMail(ByVal from As String, ByVal body As String)
Dim mMailSettings As System.Net.Configuration.MailSettingsSectionGroup
Dim mPort As Integer = mMailSettings.Smtp.Network.Port
Dim mHost As String = mMailSettings.Smtp.Network.Host
Dim mPassword As String = mMailSettings.Smtp.Network.Password
Dim mUsername As String = mMailSettings.Smtp.Network.UserName
'Dim mailServerName As String = "smtp.tricedeals.com"
'Dim message As MailMessage = New MailMessage(from, "admin#tricedeals.com", "feedback", body)
'Dim mailClient As SmtpClient = New SmtpClient
'mailClient.Host = mailServerName
'mailClient.Send(message)
'message.Dispose()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Cache.SetCacheability(HttpCacheability.NoCache)
End Sub
End Class
what is wrong with my smtp settings??i cant send emails.please help me.
you can't send email because the send command is commented out. since you don't give more details or better explanation or exception message that's the only thing I can assume.