Hello the following code for my signup page does not work. when I execute it, it refreshes and stays in the same page. But it is supposed to redirect to a page called message.aspx. The register command works as follows the person trying to register writes in comboboxs their information and then once they finished, they click the button begin which will save all their information and then use it to personalize the message.aspx page and the person will receive an email.
here is the code:
Private Sub cmdRegister_Click(sender As Object, e As System.EventArgs) Handles cmdRegister.Click
Dim status As MembershipCreateStatus
Dim organization As New Org
Dim employee As New Employee
Dim description As New Description(25)
Dim userMembership As MembershipUser
Dim stringBuilder As New StringBuilder
Try
Membership.CreateUser( _
txtUserName.Text, _
txtPassword.Text, _
txtEmail.Text, _
"question", _
"answer", _
True, _
status)
If status.ToString = "Success" Then
organization.GSTRate = 1
organization.QSTRate = 1
organization.AccountStatus = 2
organization.Name = txtOrg.Text
organization.Active = 1
organization.OrgTypeID = cboType.SelectedValue
organization.Create()
organization = Nothing
organization = New Org(txtOrg.Text)
employee.Username = txtUserName.Text
employee.OrgID = organization.ID
employee.FirstName = txtFName.Text
employee.LastName = txtLName.Text
employee.Title = txtTitle.Text
employee.Username = txtUserName.Text
employee.IsAdmin = True
employee.IsSupervisor = True
employee.IsAccountant = False
employee.IsAdvalorem = True
employee.Email = txtEmail.Text
employee.Phone = ""
employee.Create()
Roles.AddUserToRole(employee.Username, "Admin")
userMembership = Membership.GetUser(txtUserName.Text)
stringBuilder.Append(description.EnglishDescription)
stringBuilder.Replace("(name)", employee.FirstName & " " & employee.LastName)
stringBuilder.Replace("(OrgName)", organization.Name)
stringBuilder.Replace("(username)", employee.Username)
stringBuilder.Replace("you must activate your account", "you must <a href='https://www.advataxes.ca/login.aspx?action=activate&id=" + userMembership.ProviderUserKey.ToString + "&username=" + userMembership.UserName + "'>activate your account</a>")
SendEmail(userMembership.Email, "Advataxes: Account created ", stringBuilder.ToString, Session("language"))
Session("NewUserEmail") = userMembership.Email
Response.Redirect("message.aspx?id=364")
Else
lblInvalidUserName.Visible = True
If status.ToString = "DuplicateUserName" Then lblInvalidUserName.Text = "Username already exists"
End If
Catch ex As MembershipCreateUserException
MsgBox(GetErrorMessage(ex.StatusCode))
Catch ex As HttpException
MsgBox(ex.Message)
Finally
userMembership = Nothing
organization = Nothing
employee = Nothing
description = Nothing
End Try
End Sub
Looking at your code, I suspect the code execution is not successfully reaching the Response.Redirect("message.aspx?id=364") line and due to an exception the flow jumps to catch block/
Two possibilities I can think of:
Exception is thrown inside SendEmail method if smtp is not configured
Membership.CreateUser is failing due to incorrect database connectionstring
I suggest you put a breakpoint inside the cmdRegister_Click method and step through the code.
Related
I have vb.net web application in which if users are logged in than all other pages working fine but the time I log out from account than it gets error in all pages. I know the page getting values from cookies but if cookies is empty then it's getting null & so cause the error page
Error : System.NullReferenceException: Object reference not set to an instance of an object.
VB Code for any pageload
Dim var, Type As String
var = Server.HtmlEncode(Request.Cookies("chkusername").Value)
Type = Server.HtmlEncode(Request.Cookies("User_Type").Value)
Dim LogIn, LogOut, listup As Control
Dim BtnProfile As Button = Page.Master.FindControl("myAccount")
LogIn = Master.FindControl("login")
LogOut = Master.FindControl("logout")
listup = Master.FindControl("list")
'not login
If HttpContext.Current.Request.Cookies("chkusername") Is Nothing Then
listup.Visible = True
LogIn.Visible = True
LogOut.Visible = False
BtnProfile.Visible = False
'login
Else
LogOut.Visible = True
BtnProfile.Visible = True
LogIn.Visible = False
listup.Visible = False
End If
Login Page code
Dim User, Pass As String
If selectbusinesstype.SelectedValue.ToString = "0" Then
Response.Write("<script language='javascript'>alert('Select login type first');</script>")
ElseIf selectbusinesstype.SelectedValue = "Hospitals" Then
Try
If loginId.Text <> "" And password.Text <> "" Then
Dim str As String = "select * from hospitals where username='" + loginId.Text + "' and Password='" + password.Text + "';"
Dim cmd As New MySqlCommand(str, con)
con.Open()
Dim da As New MySqlDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds)
con.Close()
User = ds.Tables(0).Rows(0)("username")
Pass = ds.Tables(0).Rows(0)("password")
If ds.Tables(0).Rows.Count > 0 Then
If User = loginId.Text.ToString And Pass = password.Text.ToString Then
Response.Cookies("User_Type").Value = "Hospitals"
Response.Cookies("chkusername").Value = loginId.Text
Response.Redirect("hospital-profile.aspx?user=" + Request.Cookies("chkusername").Value)
Else
Response.Write("<script language='javascript'>alert('User name or password is invalid');</script>")
End If
Else
Response.Write("<script language='javascript'>alert('User name or password is invalid');</script>")
End If
Else
Response.Write("<script language='javascript'>alert('Enter All the Details');</script>")
End If
Catch ex As Exception
Response.Write("<br /><br /><br /><br /><br />")
Response.Write(ex)
con.Close()
End Try
You have below lines,
Dim var, Type As String
var = Server.HtmlEncode(Request.Cookies("chkusername").Value)
Type = Server.HtmlEncode(Request.Cookies("User_Type").Value)
Convert it to,
Dim var, Type As String
If not HttpContext.Current.Request.Cookies("chkusername") Is Nothing Then
var = Server.HtmlEncode(Request.Cookies("chkusername").Value)
End If
If not HttpContext.Current.Request.Cookies("User_Type") Is Nothing Then
Type = Server.HtmlEncode(Request.Cookies("User_Type").Value)
End If
I am using the code below to send an email alert when a user log in fails.
Is there a simpler way of writing this so that the email routine doesn't have to be written out twice like this, for users that exist and users that do not exist? Essentially I am looking for a more efficient way of writing this.
Thanks for any help.
Protected Sub LoginUser_LoginError(ByVal sender As Object, ByVal e As System.EventArgs) Handles LoginUser.LoginError
LoginUser.FailureText = "Invalid Username or Password - Please Try Again"
Dim UserName As TextBox = DirectCast(LoginUser.FindControl("UserName"), TextBox)
Dim CurrentUser As MembershipUser = Membership.GetUser(LoginUser.UserName)
If (CurrentUser IsNot Nothing) Then
If (CurrentUser.IsLockedOut = True) Then
LoginUser.FailureText = "Your account has been locked - Contact the system administrator"
ElseIf (CurrentUser.IsApproved = False) Then
LoginUser.FailureText = "Your account is disabled - Contact the system administrator"
End If
Dim Email_Error As New Thread(
Sub()
Dim mailObject As New System.Net.Mail.MailMessage()
Dim emailCredentials As New System.Net.NetworkCredential("email#domain.com", "password")
mailObject.To.Add("my#email.com")
If (CurrentUser.IsLockedOut = True) Then
mailObject.Subject = "User " & CurrentUser.ToString() & " is locked out"
ElseIf (CurrentUser.IsApproved = False) Then
mailObject.Subject = "User " & CurrentUser.ToString() & " is disabled"
Else
mailObject.Subject = "User " & CurrentUser.ToString() & " login failed"
End If
mailObject.From = New System.Net.Mail.MailAddress("info#domain.com")
mailObject.IsBodyHtml = True
If (CurrentUser.IsLockedOut = True) Then
mailObject.Body = "User is locked out"
ElseIf (CurrentUser.IsApproved = False) Then
mailObject.Body = "User is disabled"
Else
mailObject.Body = "User login failed"
End If
Dim SmtpMail As New System.Net.Mail.SmtpClient("smtp.email.com")
SmtpMail.UseDefaultCredentials = False
SmtpMail.EnableSsl = False
SmtpMail.Credentials = emailCredentials
SmtpMail.Port = 587
SmtpMail.Send(mailObject)
End Sub
)
Email_Error.Start()
Else
Dim Email_NoUser_Error As New Thread(
Sub()
Dim mailObject As New System.Net.Mail.MailMessage()
Dim emailCredentials As New System.Net.NetworkCredential("email#domain.com", "password")
mailObject.To.Add("my#email.com")
mailObject.Subject = "Unknown User " & UserName.Text() & " login failed"
mailObject.From = New System.Net.Mail.MailAddress("info#domain.com")
mailObject.IsBodyHtml = True
mailObject.Body = "Unknown User login failed"
Dim SmtpMail As New System.Net.Mail.SmtpClient("smtp.email.com")
SmtpMail.UseDefaultCredentials = False
SmtpMail.EnableSsl = False
SmtpMail.Credentials = emailCredentials
SmtpMail.Port = 587
SmtpMail.Send(mailObject)
End Sub
)
Email_NoUser_Error.Start()
End If
End Sub
I'd create the mailObject only once and set all the fields that stay the same, then call functions Email_Error and Email_NoUser_Error only to set those fields which vary, then after returning to the first function send it there.
I am using VS-2008 for asp.net web application. However, I have developed my reports in VS 2005. ( I am reusing some reports that were developed in other project).
The reports work fine except the image field is not displayed. The image field is a 'VARBINARY(MAX)' field in database. Note that when I export my Crystal Report to .pdf the images shows up in the .pdf file.
(* I am able to see an image url in 'Firebug' but getting message 'Load Image failed')
I am using a 'TypedDataset' as DataSource for the Crystal Report.
I fetch the data from database and do a 'DataSet.WriteXML(filename,WriteMode.WriteSchema)'
Here is the code:-
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim rgx As Regex = New Regex("[^a-zA-Z0-9 -]")
strComp = rgx.Replace(strComp, "")
strFile = "tempXML" + strComp + ".xml"
Dim dsTemp As New DataSet
dsTemp.Clear()
dsTemp.Tables.Clear()
Dim rptengine As New CrystalDecisions.CrystalReports.Engine.ReportDocument
rptengine.Load(Session("rptname"))
sdate = CType(Session("sdate"), Date)
edate = CType(Session("edate"), Date)
rptHeading = Session("rptHead")
If IO.File.Exists(Server.MapPath("~/" + strFile)) Then
dsTemp.ReadXml(Server.MapPath("~/" + strFile), XmlReadMode.ReadSchema)
'IO.File.Delete(Server.MapPath("~/" + strFile))
Try
If Session("rptname").ToString.Substring(Session("rptname").ToString.LastIndexOf("\") + 1) _
= "Rptemp.rpt" Then
Dim dsReport As New DDL.dsEmpList
dsReport.Tables("dtEmpList").Merge(dsTemp.Tables(0))
rptengine.SetDataSource(dsReport.Tables(0))
ElseIf Session("rptname").ToString.Substring(Session("rptname").ToString.LastIndexOf("\") + 1) _
= "rptDailyAttendance.rpt" Then
Dim dsReport As New DDL.dsDailyReoprt
dsReport.Tables("dtDailyReport").Merge(dsTemp.Tables(0))
rptengine.SetDataSource(dsReport.Tables(0))
End If
Catch ex As Exception
ShowMsg1("Exception : " & ex.Message)
End Try
'**********************assigning CR-ParameterFields*****************************
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
Dim crParameterFieldDefinition As ParameterFieldDefinition
Dim crParameterValues As ParameterValues
Dim crParameterDiscreteValue As ParameterDiscreteValue
Dim parameterToDefine As Boolean = False
crParameterFieldDefinitions = rptengine.DataDefinition.ParameterFields
For Each crParameterFieldDefinition In crParameterFieldDefinitions
crParameterDiscreteValue = New ParameterDiscreteValue
crParameterValues = crParameterFieldDefinition.CurrentValues
Select Case crParameterFieldDefinition.Name
Case "sdate"
parameterToDefine = True
crParameterDiscreteValue.Value = sdate
Case "edate"
parameterToDefine = True
crParameterDiscreteValue.Value = edate
Case "heading"
parameterToDefine = True
crParameterDiscreteValue.Value = rptHeading
Case Else
parameterToDefine = False
End Select
If parameterToDefine Then
Try
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
Catch ex As Exception
objdata.writelog(ex.Message, "frmRptEngine", "frmRptEngine_Load", Server.MapPath("~/Reports"))
ShowMsg1("Error in report generation.")
Exit Sub
End Try
End If
Next
rptViewer.ReportSource = Nothing
rptViewer.ReportSource = rptengine
rptViewer.Enabled = True
rptViewer.DataBind()
Else
ShowMsg1("Invalid attempt.")
End If
End Sub
For those of us running migrated projects from .Net 4.0 or lower to 4.5+ I have made an observation. It seems if your page that contains the viewer is in a subdirectory then the image urls are being generated relative to that page and not to the root of the web application. E.g if your page is /gl/accounts.aspx then the image may be /gl/crystalimagehandler.aspx etc
A quick way to fix this is to change your handler mapping to a wildcard ending in crystalimagehandler.aspx or put the following code in Global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
var p = Request.Path.ToLower().Trim();
if (p.EndsWith("/crystalimagehandler.aspx") && p!= "/crystalimagehandler.aspx")
{
var fullPath=Request.Url.AbsoluteUri.ToLower();
var index = fullPath.IndexOf("/crystalimagehandler.aspx");
Response.Redirect(fullPath.Substring(index));
}
}
I currently have a problem attepting to update a record within my database. I have a webpage that displays in text boxes a users details, these details are taken from the session upon login. The aim is to update the details when the user overwrites the current text in the text boxes.
I have a function that runs when the user clicks the 'Save Details' button and it appears to work, as i have tested for number of rows affected and it outputs 1. However, when checking the database, the record has not been updated and I am unsure as to why.
I've have checked the SQL statement that is being processed by displaying it as a label and it looks as so:
UPDATE [users]
SET [email] = #email,
[firstname] = #firstname,
[lastname] = #lastname,
[promo] = #promo
WHERE [users].[user_id] = 16
The function and other relevant code is:
Sub Page_Load(sender As Object, e As EventArgs)
usernameLabel.text = session.contents.item("UserName")
if usernameLabel.text = "" then
logoutButton.Visible = False
loggedInAsLabel.Visible = False
else
labelGuest.Visible = False
linkLogin.Visible = False
linkRegister.Visible = False
end if
emailBox.text = session.contents.item("Email")
firstBox.text = session.contents.item("FirstName")
lastBox.text = session.contents.item("LastName")
promoBox.text = session.contents.item("Promo")
End Sub
Sub Button1_Click(sender As Object, e As EventArgs)
changeDetails(emailBox.text, firstBox.text, lastBox.text, promoBox.text)
End Sub
Function changeDetails(ByVal email As String, ByVal firstname As String, ByVal lastname As String, ByVal promo As String) As Integer
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=C:\Documents an"& _
"d Settings\Paul Jarratt\My Documents\ticketoffice\datab\ticketoffice.mdb"
Dim dbConnection As System.Data.IDbConnection = New System.Data.OleDb.OleDbConnection(connectionString)
Dim queryString As String = "UPDATE [users] SET [email]=#email, [firstname]=#firstname, [lastname]=#lastname, "& _
"[promo]=#promo WHERE ([users].[user_id] = " + session.contents.item("ID") + ")"
Dim dbCommand As System.Data.IDbCommand = New System.Data.OleDb.OleDbCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection
Dim dbParam_email As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_email.ParameterName = "#email"
dbParam_email.Value = email
dbParam_email.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_email)
Dim dbParam_firstname As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_firstname.ParameterName = "#firstname"
dbParam_firstname.Value = firstname
dbParam_firstname.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_firstname)
Dim dbParam_lastname As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_lastname.ParameterName = "#lastname"
dbParam_lastname.Value = lastname
dbParam_lastname.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_lastname)
Dim dbParam_promo As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_promo.ParameterName = "#promo"
dbParam_promo.Value = promo
dbParam_promo.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_promo)
Dim rowsAffected As Integer = 0
dbConnection.Open
Try
rowsAffected = dbCommand.ExecuteNonQuery
Finally
dbConnection.Close
End Try
labelTest.text = rowsAffected.ToString()
if rowsAffected = 1 then
labelSuccess.text = "* Your details have been updated and saved"
else
labelError.text = "* Your details could not be updated"
end if
End Function
Any help would be greatly appreciated.
Does your page have a RequiresTransaction property? If so, check that there are no exceptions thrown elsewhere during the request which might cause the transaction to roll back - leaving the data unchanged.
Are you sure that you're updating the database you think you're updating? I don't like the look of that connection string at all (and, frankly, I doubt Paul Jarratt would be too happy to see it posted here).
I have the below code in my current solution, which returns an error of 'The value '' is invalid'. The below snippet has been shortened to just show the problem area as opposed to the entire ActionResult.
Dim tComment As New hdComment
tComment.Comment = collection("wmd-input")
tComment.MadeOn = DateTime.Now
tComment.UserID = Session("LoggedInUser")
tComment.CallID = id
If Not tComment.Comment.Trim().Length = 0 Then
db.hdComments.InsertOnSubmit(tComment)
End If
db.SubmitChanges()
Return Redirect("/Calls/Details/" & id)
However, in a previous project, I have used exactly the same code, even the view is the same, but it still returns the above error.
Everything is receiving a value ok.
The only thing that's different is that it's a different project.
I'm at a bit of a loss with this one.
Anyone have any ideas?
EDIT For reference, here is the entire ActionResult.
'
' POST: /Calls/Details/5
<Authorize()> _
<AcceptVerbs(HttpVerbs.Post)> _
<ValidateInput(False)> _
Function Details(ByVal id As Integer, ByVal collection As FormCollection) As ActionResult
Dim calls As hdCall = callRepository.GetCall(id)
ViewData("MyCallID") = calls.CallID
ViewData("UserThatLogged") = calls.UserID
ViewData("TimeLogged") = calls.loggedOn.ToLongDateString & " " & calls.loggedOn.ToLongTimeString
ViewData("Title") = calls.Title
Dim dataContext As New CustomerServiceModelDataContext
ViewData("Status") = New SelectList(dataContext.hdStatus, "StatusID", "Status", calls.StatusID)
ViewData("Type") = New SelectList(dataContext.hdCategories, "CategoryID", "Title", calls.CategoryID)
ViewData("Company") = calls.hdCompany.Company
ViewData("Priority") = New SelectList(dataContext.hdPriorities, "PriorityID", "Priority", calls.PriorityID)
ViewData("CallDetails") = calls.CallDetails
ViewData("Customer") = calls.hdCustomer.CustomerName
ViewData("CustomerID") = calls.hdCustomer.CustomerID
ViewData("CustomerCallCount") = callRepository.CountCallsForThisCustomer(calls.hdCustomer.CustomerID).Count()
ViewData("ContactNumber") = calls.hdCustomer.Telephone
ViewData("AssignedTo") = New SelectList(dataContext.aspnet_Users, "UserName", "UserName", calls.AssignedTo)
Dim callComments = callRepository.GetCallComments(id)
Dim db As New CustomerServiceModelDataContext
Try
Dim tComment As New hdComment
tComment.Comment = collection("wmd-input")
tComment.MadeOn = DateTime.Now
tComment.UserID = Session("LoggedInUser")
tComment.CallID = id
If Not tComment.Comment.Trim().Length = 0 Then
db.hdComments.InsertOnSubmit(tComment)
End If
'Update any call changes
Dim tCall = (From c In db.hdCalls _
Where c.CallID = id _
Select c).SingleOrDefault
tCall.updatedOn = DateTime.Now
tCall.UpdatedBy = Session("LoggedInUser")
tCall.StatusID = collection("Status")
tCall.AssignedTo = collection("AssignedTo")
tCall.CategoryID = collection("Type")
tCall.PriorityID = collection("Priority")
db.SubmitChanges()
Return Redirect("/Calls/Details/" & id)
Catch ex As Exception
ModelState.AddModelError("Error", ex)
Return View(callComments)
End Try
Return View(callComments)
End Function
The rest of the code works, if the wmd-input field is left blank on the form, it's only when there is something in it does it throw the error.
EDIT bit of an update to this, this line:
If Not tComment.Comment.Trim().Length = 0 Then
now reads
If (Not tComment.Comment.Trim().Length = 0) Then
and the page updates if nothing is in the wmd-input box, but if there is, it returns the The value '' is invalid.
You are probably missing a reference. Or the framework version is different.
Also is it the same development machine, is asp.net-mvc installed both places?
I managed to fix this, the problem actually lay in the Foriegn Key Contraints between hdCalls and hdComments.
I removed the contraints and recreated them and all of a sudden it was fine.