Ok so I am using the default WebApplication in Visual Web Developer 2010, and applied Paladine's example of Simple ASP.Net Login page. And it is working, but only to some extent. I am sure I am just missing something INCREDIBLY simple, but after looking at this code for 2 days, I am just banging my head against the wall because I cannot find the errors. Any help that you all could provide in this would be GREATLY appreciated as I cannot afford to keep fixing the wall where I am banging my head (LOL)
First off I get an warning - " Function 'DBConnection' doesn't return a value on all code paths. Are you missing a 'Return' statement? " This is from copying and pasting Paladine's DBConnection function, with a MD5hash function surrounding the password (that is how passwords are stored in the db)
Here is the code from the Login.aspx.vb page:
Imports System.Web.Security
Imports System.Data
Imports System.Data.OleDb
Imports System.Configuration
Imports System.Security.Cryptography
Public Class Login
Inherits System.Web.UI.Page
Public md5Hash As MD5 = MD5.Create
Public Function GetMd5Hash(ByVal md5Hash As MD5, ByVal input As String) As String
Dim data As Byte() = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input))
' Create a new Stringbuilder to collect the bytes and create a string.
Dim sBuilder As New StringBuilder()
' Loop through each byte of the hashed data and format each one as a hexadecimal string.
Dim i As Integer
For i = 0 To data.Length - 1
sBuilder.Append(data(i).ToString("x2"))
Next i
' Return the hexadecimal string.
Return sBuilder.ToString()
End Function
Function DBConnection(ByVal strUserName As String, ByVal strPassword As String) As Boolean
'<sumamry>
' ||||| Declare Required Variables
' ||||| Access appSettings of Web.Config for Connection String (Constant)
'</summary>
' ||||| First is the Connection Object for an Access DB
Dim MyConn As OleDbConnection = New OleDbConnection(ConfigurationManager.AppSettings("strConn"))
'<sumamry>
' ||||| Create a OleDb Command Object
' ||||| Pass in Stored procedure
' ||||| Set CommandType to Stored Procedure
'</summary>
' ||||| To Access a Stored Procedure in Access - Requires a Command Object
Dim MyCmd As New OleDbCommand("sp_ValidateUser", MyConn)
' ||||| To Access a Stored Procedure in SQL Server - Requires a Command Object
MyCmd.CommandType = CommandType.StoredProcedure
' ||||| Create Parameter Objects for values passed in
Dim objParam1, objParam2 As OleDbParameter
'<sumamry>
' ||||| Add the parameters to the parameters collection of the
' ||||| command object, and set their datatypes (OleDbType in this case)
'</summary>
objParam1 = MyCmd.Parameters.Add("@UserName", OleDbType.Char)
objParam2 = MyCmd.Parameters.Add("@Password", OleDbType.Char)
'' ||||| Set the direction of the parameters...input, output, etc
objParam1.Direction = ParameterDirection.Input
objParam2.Direction = ParameterDirection.Input
'' ||||| Set the value(s) of the parameters to the passed in values
objParam1.Value = strUserName
objParam2.Value = GetMd5Hash(md5Hash, strPassword)
' ||||| Try, catch block!
Try
' ||||| Check if Connection to DB is already open, if not, then open a connection
If MyConn.State = ConnectionState.Closed Then
' ||||| DB not already Open...so open it
MyConn.Open()
End If
' ||||| Create OleDb Data Reader
Dim objReader As OleDbDataReader
objReader = MyCmd.ExecuteReader(CommandBehavior.CloseConnection)
' ||||| Close the Reader and the Connection Closes with it
While objReader.Read()
If CStr(objReader.GetValue(0)) <> "1" Then
lblMessage.Text = "Invalid Login!"
Return False
Else
objReader.Close() ' ||||| Close the Connections & Reader
Return True
End If
End While
Catch ex As Exception
lblMessage.Text = "Error Connecting to Database!"
Return False
End Try
End Function
Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
If Page.IsValid Then ' ||||| Meaning the Control Validation was successful!
' ||||| Connect to Database for User Validation |||||
If DBConnection(txtUserName.Text.Trim(), txtPassword.Text.Trim()) Then
lblMessage.Text = "Successful Login!"
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False)
Else
' ||||| Credentials are Invalid
lblMessage.Text = "Invalid Login!"
' ||||| Increment the LoginCount (attempts)
'Session("LoginCount") = CInt(Session("LoginCount")) + 1
' ||||| Determine the Number of Tries
'If Session("LoginCount").Equals(intMaxLoginAttempts) Then
' Response.Redirect("Denied.aspx")
'End If
'If CInt(Session("Num_of_Tries")) > 2 Then ' ||||| If Exceeds then Deny!
' Response.Redirect("Denied.aspx")
'End If
End If
End If
End Sub
End Class
I get the squiggly line under End Function for the DBConnection function. If I comment out the FormsAuthentication.RedirectFromLoginPage(txtUserName.Text) then the login pages refreshes and shows the login was successful, however if I uncomment, the page gets kicked back to the login.
Here is the rest of the code default.aspx
<%@ Page Title="Home Page" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeBehind="Default.aspx.vb" Inherits="CustomerPCTracker._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
</asp:Content>
Web.Config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="strConn" value="Provider = Microsoft.Jet.OLEDB.4.0;Data Source=C:\Inetpub\CompTracking.mdb"/>
</appSettings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
<customErrors mode="Off" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx"
protection="All"
timeout="20"
name="AppNameCookie"
path="/FormsAuth"
requireSSL="true"
slidingExpiration="true"
defaultUrl="default.aspx"
cookieless="UseCookies"
enableCrossAppRedirects="false" />
</authentication>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Global.asax.vb:
Imports System.Web.SessionState
Imports System.Web.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.Data
Imports System.Data.OleDb
Imports System.Configuration
Imports System.Data.SqlClient
Public Class Global_asax
Inherits System.Web.HttpApplication
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application is started
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the session is started
End Sub
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires at the beginning of each request
End Sub
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires upon attempting to authenticate the use
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Fires when an error occurs
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the session ends
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application ends
End Sub
End Class
Login.aspx:
<%@ Page Title="Log In" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeBehind="Login.aspx.vb" Inherits="CustomerPCTracker.Login" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Log In
</h2>
<p>
Please enter your username and password.</p>
<div class="accountInfo">
<table id="mainTable" border="0">
<tr>
<td>
<table id="loginTable" cellspacing="15" cellpadding="0">
<tr>
<td><b>Login: </b>
</td>
<td><asp:textbox id="txtUserName" runat="server" width="160px"></asp:textbox><asp:requiredfieldvalidator id="rvUserValidator" runat="server" display="None" errormessage="You must supply a Username!"
controltovalidate="txtUserName"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td><b>Password: </b>
</td>
<td><asp:textbox id="txtPassword" runat="server" width="160px" textmode="Password"></asp:textbox><asp:requiredfieldvalidator id="rvPasswordValidator" runat="server" display="None" errormessage="Empty Passwords not accepted"
controltovalidate="txtPassword"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td align="center" colspan="2"><asp:button id="cmdSubmit" runat="server" borderstyle="Solid" text="Login"></asp:button></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table id="messageDisplay">
<tr>
<td><asp:validationsummary id="Validationsummary1" runat="server" width="472px" displaymode="BulletList"></asp:validationsummary></td>
</tr>
</table>
</td>
</tr>
</table>
<asp:label id="lblMessage" runat="server" width="288px" forecolor="#C00000" font-size="Medium"
font-italic="True" font-bold="True"></asp:label>
<!-- ||||| End of Form ||||| -->
</div>
</asp:Content>