Any way of condensing this ASP.net System.Net.Mail code - asp.net

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.

Related

The code for my aspx signup page does not work

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.

after logout from users account all page shows error

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

How to check if mysql query returns nothing?

I'm writing a project and at the some point i have to check if there is an entry in database which matches the content of id-textbox and password-textbox. But I don't know how to indicate in my backend code(VB) that the query returns nothing.
This is the code I am using. But it doesn't work somehow. Error messages Are not being prompt:
Try
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = " & IdNumb.Text
Dim smd As MySqlCommand
Dim myreader As MySqlDataReader
smd = New MySqlCommand(stquery, myconn)
myreader = smd.ExecuteReader()
If myreader.Read() = True Then
If myreader.Item("user_ID") = IdNumb.Text Then
If myreader.Item("password") = CurrPass.Text Then
'some code if the user input is valid
Else
errorPassID.Visible = True
End If
Else
errorPassC.Visible = True
End If
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True) myconn.Close()
End Try
Will appreciate any help or suggestion.
I will try to check if the reader return rows and if not, emit an error message.
Also, do not use string concatenation to build queries, use always parametrized queries
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = #id"
Dim smd = New MySqlCommand(stquery, myconn)
smd.Parameters.AddWithValue("#id", Convert.ToInt32(IdNumb.Text))
Dim myreader = smd.ExecuteReader()
if Not myreader.HasRows Then
Dim ErrorMessage As String = "alert('No user found');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
return
else
myreder.Read()
' no need to check if id is equal, you pass it as parameter to a where clause'
If myreader.Item("password") = CurrPass.Text Then
'some code if the user input is valid '
Else
errorPassID.Visible = True
' or error message '
End If
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
Note also that passing a clear text password along the wire is a serious security hole. I hope you have stored an hash of the password and check on that instead.
By the way, why don't pass also the password hash in the query? Somthing like this:
Dim stquery As String = "SELECT * from accountstbl WHERE user_ID = #id AND password = #pwd"
In this way, if you have a record returned the user is validated and your client side code will be simple

ASP.NET Button Click Event Issue (postback)

The issue that i'm having is that trhough a button1 upon click shall save the data entered in the textboxes (see code) however when the page is postback the data is not saved (no confirmation message appears) then if i click again it does saves the record, sometimes takes more than 3 times until the data is stored per confirmation message.
Is this a Con.Dispose Issue??? Shall i use con.close?
Note: in the code i have Con.CLOSE however the page is deployed under Con.Dispose()
Note2: i'm planning to fix more "novice" issues found in the code but urgent question remains in the postback issue.
' *--------Empty Text Validation-------*
If TextBox10_AddData_LabInvest.Text <> "" AndAlso TextBox3_AddData_LabInvest.Text <> "" AndAlso TextBox4_AddData_LabInvest.Text <> "" AndAlso TextBox5_AddData_LabInvest.Text <> "" AndAlso TextBox6_AddData_LabInvest.Text <> "" AndAlso TextBox7_AddData_LabInvest.Text <> "" Then
' *--------SQL Insert command-------*
SqlDataSource_AddData_LabInvest.InsertCommand = "INSERT INTO [LabInvest] (ID_LabInvest, LabInvest_Load, LabInvest_SeqRef_CH, LabInvest_SeqRef_Year, LabInvest_Owner, LabInvest_Subject, LabInvest_DueDate, LabInvest_Code, LabInvest_QSNCCode, LabInvest_OpenByOwner, LabInvest_OpenDateOwner, Status_Text, Status_Int ) VALUES(#ID_LabInvest, #LabInvest_Load, #LabInvest_SeqRef_CH, #LabInvest_SeqRef_Year, #LabInvest_Owner, #LabInvest_Subject, #LabInvest_DueDate, #LabInvest_Code, #LabInvest_QSNCCode, #LabInvest_OpenByOwner, #LabInvest_OpenDateOwner, #Status_Text, #Status_Int)"
SqlDataSource_AddData_LabInvest.InsertParameters.Add("ID_LabInvest", TextBox10_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_Load", "N/A")
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_SeqRef_CH", TextBox1_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_SeqRef_Year", TextBox2_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_Owner", TextBox3_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_Subject", TextBox4_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_DueDate", TextBox5_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_Code", TextBox6_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_QSNCCode", TextBox7_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_OpenByOwner", TextBox8_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_OpenDateOwner", TextBox9_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("Status_Text", "Stage 1 - Just Added")
SqlDataSource_AddData_LabInvest.InsertParameters.Add("Status_Int", "1")
Try
SqlDataSource_AddData_LabInvest.Insert()
' *--------Get Unique ID-------*
Dim Con As New SqlConnection
Dim SQL As String
Dim com As SqlCommand = Con.CreateCommand
Con.ConnectionString = "removed"
Con.Open()
SQL = "SELECT ID_LabInvest FROM LabInvest WHERE ID_LabInvest=" + TextBox10_AddData_LabInvest.Text
Dim cmd As New SqlCommand(SQL, Con)
Dim obj = cmd.ExecuteScalar()
Label1_AddData_LabInvest.Text = "Your record ID is: " + obj.ToString()
' *--------Get Stage-------*
Dim SQL2 As String
SQL2 = "SELECT Status_Text from LabInvest WHERE ID_LabInvest=" & obj
Dim cmd2 As New SqlCommand(SQL2, Con)
Dim obj2 = cmd2.ExecuteScalar()
Label2_AddData_LabInvest.Text = "Record Stage: " + obj2.ToString()
con.close()
Button4_AddData_LabInvest.Enabled = False
' *--------SQL Audit Insert command-------*
Dim Usercheck As String
Usercheck = Request.ServerVariables("LOGON_USER")
SqlDataSource_LabInvest_Audit.InsertCommand = "INSERT INTO [AuditTrial] (ID_Table, AuditTableName, AuditAction, AuditUser, AuditValue1Before, AuditValue2Before, AuditValue1After, AuditValue2After, AuditMasterReason, AuditMasterChange) VALUES(#ID_Table, #AuditTableName, #AuditAction, #AuditUser, #AuditValue1Before, #AuditValue2Before, #AuditValue1After, #AuditValue2After, #AuditMasterReason, #AuditMasterChange)"
SqlDataSource_LabInvest_Audit.InsertParameters.Add("ID_Table", obj)
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditTableName", "LaboratoryInvestigations_Add")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditAction", "Added New Record")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditUser", Usercheck)
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditValue1Before", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditValue2Before", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditValue1After", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditValue2After", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditMasterReason", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditMasterChange", "N/A")
SqlDataSource_LabInvest_Audit.Insert()
Catch ex As Exception
Label1_AddData_LabInvest.Text = "Duplicate NumberID, Please Review Data"
End Try
Else
Label1_AddData_LabInvest.Text = "Please Fill All Options"
End If
The issue was found as the application was residing in a Web Servers Farm with NLB, therefore the blank post-back was due to the NBL redirecting the user to another server from the original connection. (different solutions may apply link NO Cache, Connection Affinity,etc) hope it helps someone in the future.

LDAP + ASP Classic + ADODB = 2147217865. (Using LDAP to talk to Active Directory in ASP Classic. Error:2147217865)

I need to use LDAP to authenticate users for an old ASP website.
I have been using the code found here.
It looks like this:
<%# LANGUAGE=VBSCRIPT %>
<%Option Explicit%>
<%
Function getADUserInfo(strUID)
on error resume next
strGeneralLookupError = false
strBase = "<LDAP://DC=[DOMAIN], DC=[DOMAIN EXETENTION]>"
strFilter = "(sAMAccountName=" & strUID & ")"
strAttributes = "cn, mail, company, givenName, sn, ADsPath, name, sAMAccountName, telephoneNumber"
'strAttributes = "cn, company, givenName, sn, ADsPath, name, sAMAccountName, telephoneNumber"
strScope = "subtree"
strFullCommand = strBase & ";" & strFilter & ";" & strAttributes & ";" & strScope
set rsADUserInfo = Server.CreateObject("ADODB.Recordset")
set rsADUserInfo = connAD.Execute(strFullCommand)
if err.number <> 0 then
strGeneralLookupError = true
end if
set getADUserInfo = rsADUserInfo
set rsADUserInfo = Nothing
End Function
Sub getUserData(p_strUserID)
on error resume next
set rsUserData = Server.CreateObject("ADODB.Recordset")
set rsUserData = getADUserInfo(p_strUserID)
if not rsUserData.EOF then
strUserGN = rsUserData("givenName")
strUserSN = rsUserData("sn")
strUserOU = rsUserData("company")
strUserEmail = rsUserData("mail")
strUserPhone = rsUserData("telephoneNumber")
else
strADLookupSuccess = false
end if
rsUserData.Close
set rsUserData = Nothing
End Sub
on error resume next
response.expires = 0
DIM connAD, rsUserData, rsADUserInfo
DIM strUserGN, strUserSN, strUserOU, strUserEmail, strUserPhone
DIM strBase, strFilter,strAttributes, strScope, strFullCommand
DIM strGeneralLookupError, strADLookupSuccess
DIM strUserID
strUserGN = "The user can not be found in the system."
strGeneralLookupError = false
strADLookupSuccess = true
set connAD = Server.CreateObject("ADODB.Connection")
connAD.Provider = "ADsDSOObject"
connAD.Properties("User ID") = "[DOMAIN]\[USERNAME]" ' ### remember to make sure this user has rights to access AD
connAD.Properties("Password") = "[PASSWORD]"
connAD.Properties("Encrypt Password") = true
connAD.Open
strUserID = "[USERNAME YOU WANT INFO FOR]"
call getUserData(strUserID)
connAD.Close
set connAD = Nothing
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>ASP Code to access AD with LDAP Page</title>
</head>
<body>
<%=strUserGN%>
<%=strUserSN%><br />
<%=strUserOU%><br />
<%=strUserEmail%><br />
<%=strUserPhone%><br />
</body>
</html>
I can pull back info using C# so I don't think it's the server that is causing the issue.
All I end up with is a 2147217865 error.
The AD server is Windows Server 2003.
The web server is IIS on XP Pro.
I have tried changing strFullCommand to:
Select cn From 'LDAP://SEVERPATH' where objectClass='user'" & " and objectcategory='person'
No dice there. Any ideas?
This works:
function AuthenticateUser(UserName, Password, Domain)
dim strUser
' assume failure
AuthenticateUser = false
strUser = UserName
strPassword = Password
strQuery = "SELECT cn FROM 'LDAP://" & Domain & "' WHERE objectClass='*' "
set oConn = server.CreateObject("ADODB.Connection")
oConn.Provider = "ADsDSOOBJECT"
oConn.Properties("User ID") = strUser
oConn.Properties("Password") = strPassword
oConn.Properties("Encrypt Password") = true
oConn.open "DS Query", strUser, strPassword
set cmd = server.CreateObject("ADODB.Command")
set cmd.ActiveConnection = oConn
cmd.CommandText = strQuery
on error resume next
set oRS = cmd.Execute
if oRS.bof or oRS.eof then
AuthenticateUser = false
else
AuthenticateUser = true
end if
set oRS = nothing
set oConn = nothing
end function
The first thing I'd do to debug this is get rid of those On Error Resume Next statements. They could be hiding a multitude of sins that you're not seeing properly reported.

Resources