[/size][/color][color=#800000][size=3]appSettings[/size][/color][color=#0000ff][size=3]> <[/size][/color][color=#800000][size=3]system.web[/size][/color][color=#0000ff][size=3]>[/size][/color] [/code] These lines of code do several things. 1. Eliminates the need for creation of a connection string ([b]strConn[/b]) each time you want to connect to the Database(DB). Who wants to write that out each time. Now you have "pseudo-global" variable for use in your entire application. 2. Makes it secure, so no user can see where the DB is actually located. 3. And most importantly tells the application the location of the said DB. [b]b.[/b][i]Code the "meat" of the Login in page. [/i] - Mine is in the code behind rather than a script block, but the principles are the same. - Add the following Imports to your code behind, just above the class declaration. [code][color=#0000ff][size=3]Imports [/size][/color][size=3]System.Web.Security [color=#008000]' ||||| Required Class for Authentication [/color][color=#0000ff]Imports [/color]System.Data [color=#008000]' ||||| DB Accessing Import[/color][/size] [color=#0000ff][size=3]Imports [/size][/color][size=3]System.Data.OleDb [color=#008000]' |||||| Access Database Required Import! [/color][color=#0000ff]Imports [/color]System.Configuration [color=#008000]' |||||| Required for Web.Config appSettings |||||[/color][/size] [/code] This will provide the library imports you need for Authentication, accessing an OleDB (i.e. Access), and accessing the web.config file (contains your connection string) [b]c.[/b] [i]Create a Function to connect to the DB return result(s)[/i] - This is the main function of this entire webform. [code] [color=#0000ff][size=3]Function [/size][/color][size=3]DBConnection([color=#0000ff]ByVal [/color]strUserName [color=#0000ff]As String[/color], [color=#0000ff]ByVal [/color]strPassword [color=#0000ff]As String[/color]) [color=#0000ff]As Boolean [/color][color=#008000]' ' ||||| Declare Required Variables ' ||||| Access appSettings of Web.Config for Connection String (Constant) ' [color=#008000]' ||||| First is the Connection Object for an Access DB [/color][color=#0000ff]Dim [/color]MyConn [color=#0000ff]As [/color]OleDbConnection = [color=#0000ff]New [/color]OleDbConnection(ConfigurationSettings.AppSettings("strConn")) [color=#008000]' ||||| This is the Connections Object for an SQL DB SqlConnection(ConfigurationSettings.AppSettings("strConn")) ' ' ||||| Create a OleDb Command Object ' ||||| Pass in Stored procedure ' ||||| Set CommandType to Stored Procedure ' ' ||||| To Access a Stored Procedure in Access - Requires a Command Object [/color][color=#0000ff]Dim [/color]MyCmd [color=#0000ff]As New [/color]OleDbCommand("sp_ValidateUser", MyConn) [color=#008000]' ||||| To Access a Stored Procedure in SQL Server - Requires a Command Object [/color]MyCmd.CommandType = CommandType.StoredProcedure [color=#008000]' ||||| Create Parameter Objects for values passed in [/color][color=#0000ff]Dim [/color]objParam1, objParam2 [color=#0000ff]As [/color]OleDbParameter [color=#008000]' ' ||||| Add the parameters to the parameters collection of the ' ||||| command object, and set their datatypes (OleDbType in this case) ' [/color]objParam1 = MyCmd.Parameters.Add("@UserName", OleDbType.Char) objParam2 = MyCmd.Parameters.Add("@Password", OleDbType.Char) [color=#008000]'' ||||| Set the direction of the parameters...input, output, etc [/color]objParam1.Direction = ParameterDirection.Input objParam2.Direction = ParameterDirection.Input [color=#008000]'' ||||| Set the value(s) of the parameters to the passed in values [/color]objParam1.Value = strUserName objParam2.Value = strPassword [color=#008000]' ||||| Try, catch block! [/color][color=#0000ff]Try [/color][color=#008000]' ||||| Check if Connection to DB is already open, if not, then open a connection [/color][color=#0000ff]If [/color]MyConn.State = ConnectionState.Closed [color=#0000ff]Then [/color][color=#008000]' ||||| DB not already Open...so open it [/color]MyConn.Open() [color=#0000ff]End If [/color][color=#008000]' ||||| Create OleDb Data Reader [/color][color=#0000ff]Dim [/color]objReader [color=#0000ff]As [/color]OleDbDataReader objReader = MyCmd.ExecuteReader(CommandBehavior.CloseConnection) [color=#008000]' ||||| Close the Reader and the Connection Closes with it [/color][color=#0000ff]While [/color]objReader.Read() [color=#0000ff]If CStr[/color](objReader.GetValue(0)) <> "1" [color=#0000ff]Then [/color]lblMessage.Text = "Invalid Login!" [color=#0000ff]Else [/color]objReader.Close() [color=#008000]' ||||| Close the Connections & Reader [/color][color=#0000ff]Return True End If End While Catch [/color]ex [color=#0000ff]As [/color]Exception lblMessage.Text = "Error Connecting to Database!" [color=#0000ff]End Try End Function[/color][/size] [/code] [b]d.[/b] [i]Code the button click event for submitting login to DB[/i] - The code for the onClick event of the Submit button is as follows, but this is very basic and simple. I will be expanding on this further with things like have a maximum number of attempts, and what happens when a user tries to access a page in the application without having logged in; it should redirect the user to the login page/form, otherwise what is the purpose of the login form. [code] [color=#0000ff][size=3]Private Sub [/size][/color][size=3]cmdSubmit_Click([color=#0000ff]ByVal [/color]sender [color=#0000ff]As [/color]System.Object, [color=#0000ff]ByVal [/color]e [color=#0000ff]As [/color]System.EventArgs) [color=#0000ff]Handles [/color]cmdSubmit.Click [color=#0000ff]If [/color]Page.IsValid [color=#0000ff]Then [/color][color=#008000]' ||||| Meaning the Control Validation was successful! ' ||||| Connect to Database for User Validation |||||[/color][/size] [color=#0000ff][size=3]If [/size][/color][size=3]DBConnection(txtUserName.Text.Trim(), txtPassword.Text.Trim()) [color=#0000ff]Then[/color][/size] [size=3]FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, [color=#0000ff]False[/color]) [color=#008000]' ||||| default.aspx Page! [/color][color=#0000ff]Else[/color][/size] [color=#0000ff][size=3]Else [/size][/color][color=#008000][size=3]' ||||| Credentials are Invalid [/size][/color][size=3]lblMessage.Text = "Invalid Login!" [color=#008000]' ||||| 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 [/color][color=#0000ff]End If End If End Sub[/color][/size] [/code] [b]3.[/b] [u]Create the page to send the user to once login is successful [/u]- In Visual Studio.Net go to File -> Add New Item -> Webform - Name it [b]default.aspx[/b] - For ease at this time, just put a text message saying something like "Successful Login". - It is this page that ASP.Net will automatically look for once login is successful, so if you do not create it you will get an application error. [b]4.[/b] [u]Compile and run your code![/u] That is the end of this basic outline of a Login Page using ASP.Net. There were some moderate level of difficulty coding, but I believe my comments inline with the code should clarify any questions you may have. If by chance you have some questions, please post them here. [size=4][u][size=3]Please DO NOT POST replies to this thread that say things like - "Mine doesn't work!" without providing details of what errors you got, what does happen, etc.[/size] [/u] [/size]I can't help you if you do not provide details! Let me say that again [b]I can't help you if you do not provide details![/b] And preferably any code alerations you may have done to the above code for your specific application. Happy Coding.:cool:">
LOL but what cracks me up about this error tho is that when I try to login with just garbage as the username and password 3 times in a row until I get directed to denied.aspx then hit the back button and put in a correct username and pass it works and the Session("Logged_IN") variable is set to "Yes" on my default page. I am like you I am lost here. LOL :sad:
I have tried IE and Mozilla to run the application and from different computers. I started a completely new project with basic controls with the code and I still get the same thing. It redirects me back to login unless I type incorrect username and pass 3 times then try again it finally redirects me and then all the other forms work correctly and the session variable holds throughout. I'm going to give you my IIS setup and maybe u might see something I have wrong.
IIS 5.1 XP Pro
Virtual Directory tab Read - checked Log visits - checked Index this resource - checked
Execute Permissions - Scripts only Application Protection - Medium
Configuration button - Option - Enable session state - 20 min - Enable buffering - checked - Enable parent paths - checked - Default ASP Language - VBScript - ASP Script timeout - 90 seconds - Debugging - Enable ASP server-side script debugging Directory Security tab Anonymous access - checked Allow IIS to control pass - checked
Basic authentication - checked Integrated Windows authentication - checked
For the login.aspx it works properly. It's great. How about odbc? I had tried to use DSN by using ODBC. This is the error "Operator is not defined for type 'DBNull' and type 'Integer'". My e-m: aromsayc@hotmail.com
For the login.aspx it works properly. It's great. How about odbc? I had tried to use DSN by using ODBC. This is the error "Operator is not defined for type 'DBNull' and type 'Integer'". My e-m: aromsayc@hotmail.com
Aromsay
Did you use something like this for creating a DSN connection?
Dim conn As New OdbcConnection("DSN=TestDSN")
Oh, I should mention this now. I do not reply directly to emails, and rarely directly to private messages here (some exceptions). If it is something that I can answer here that will help everyone I would rather do that. So please do not request me to send you an email to answer your specific problem. Fact is, if you have an issue, others may as well.
i have the same problem as millers_35 i do the authorization and if it returns true i redirect to the default.aspx and create the session (ok other way round first session then the redirect) as put in the tutorial so it can only redirect if i am logged in and it has to create a session otherwhyse it msu give an error. ok so i am on default then and the session is disapeared :-( ... i am geting realy frustrated about this. do you have any idea on what is going wrong ...btw i get the same problem on my real webserver hosted by easycgi so it cant be a settingsproblem of my iis
Ok, I am sorry to say I do not follow what you are saying.
You get an error when you try to login ? How do you mean it has to create a session otherwise (correct spelling) it gives an error?
Here is what I would do: 1. I would Recreate a new project, new directory, and build it in stages. i.e. Paste in the HTML code, and compile the code. Paste in the VB.Net code, complie, etc... that way you will see any errors that come up in the code. 2. Provide the error message you are getting and I may be able to give more details.
As I told millers_35, I am really stumped. I have done this same application about 20 times on numerous machines to boot with no issues like this.
Sorry I couldn't provide more help.
On that note, have you tried doing a simple ASP.Net page, like retrieving data from the db? i.e. Create a simple datagrid populating with a simple select statement?
i have the same problem as millers_35 i do the authorization and if it returns true i redirect to the default.aspx and create the session (ok other way round first session then the redirect) as put in the tutorial so it can only redirect if i am logged in and it has to create a session otherwhyse it msu give an error. ok so i am on default then and the session is disapeared :-( ... i am geting realy frustrated about this. do you have any idea on what is going wrong ...btw i get the same problem on my real webserver hosted by easycgi so it cant be a settingsproblem of my iis
Sup guys, I finished the project I was working on. I appreciate the help I got from Paladine. His tutorial helped be quite a bit on getting started. I ended up using cookies instead of session variables. I think the problem I was having with the session variables dropping was because of where the variables were getting stored. Paladine do the variables get stored in server memory or on the local machine memory? That being asked I think the problem lies within this from the web.config file
the sessionState mode will take on different settings "SQLServer, InProc, and StateServer. Could it be that he doesnt have his set to the correct value. Again I am still learning as well and do not have a definite answer and hoping someone could correct me on this if I am wrong.
And miller_35, as far as I know (no resources at my work to verify), but session variables are on the User Side (i.e. When the application is closed, or you close your browser, the session is ended.)
Thanks for the compliments. Folks let me know if there is anything else anyone wants to have a tutorial on for ASP.Net.
Ok, I was reading and I don't know if I got this right but millers_35 if your problem is that you get redirected to default.aspx even if you didn't come from there here is what I found: This is what everybody has in their Login.aspx
But the RedirectFromLoginPage works right if you pass the "ReturnUrl" parameter otherwise it will redirect you to Default.aspx everytime you entered the right username and password. This should be in the page you want to protect. In this case the page name is TestDetails.aspx
Thank you so much for your code and explanations!! I have learned alot. My VB.Net applications has about 30 pages and now they're all protected!! Is it possible to pass the username and password from another program to VB.Net so that the user doesn't have to login again? I use CodeCharge for the data entry section of my application (about 100 screens). Crystal Reports in VB.Net are in another section. Right now, when the user goes to the reports section, they have to login again.
Off the top of my head I would have a flag in the DB to check if a user is logged in or not (useful for real time reporting as well), which gets set true / false based on if the user is logged in or logged out (hasn't logged in yet). Check that as part of your security.
Oh, one last point. You do not have to use the FormsAuthentication.RedirectFromLogin line of code in your application(s).
Use Response.Redirect, if my method is causing an issue.
It is the logic and understanding that matters, not so much the method you use to get there. :cool:
Ok, I was reading and I don't know if I got this right but millers_35 if your problem is that you get redirected to default.aspx even if you didn't come from there here is what I found: This is what everybody has in their Login.aspx
But the RedirectFromLoginPage works right if you pass the "ReturnUrl" parameter otherwise it will redirect you to Default.aspx everytime you entered the right username and password. This should be in the page you want to protect. In this case the page name is TestDetails.aspx
Paladine, firstly thanks for the tutorials you've posted here, they seem great, but i'm having trouble getting it to work for me. Hoping you could help.
I'm trying to build a login page, connecting to an SQL server database using C#, so i've mixed up a few of your tutorials to try to achieve this. here is my C# code for the login page, it uses a connection from another C# file rather than your Web.Config suggestion, but i know the connection works as it is used successfully for other code:
privatevoidSubmit1_ServerClick(object sender,System.EventArgs e){if(Page.IsValid){if(ValidateUser(usernameTxtBx.Text.Trim(), passwordTxtBx.Text.Trim())){
FormsAuthentication.RedirectFromLoginPage (usernameTxtBx.Text,false);}else{
messageLbl.Text ="Invalid Login, please try again!";}}}privateboolValidateUser(string txtUser,string txtPass){// Connect to Database
DataAccess.DBConnection.GetLoginConnection();// Access Stored ProcedureSqlCommand cmd =newSqlCommand("proc_ValidateUser", conn);
cmd.CommandType = CommandType.StoredProcedure;// Create ParametersSqlParameter objParam1;SqlParameter objParam2;SqlParameter returnParam;
objParam1 = cmd.Parameters.Add("@usrName", SqlDbType.NVarChar);
objParam2 = cmd.Parameters.Add("@usrPassword", SqlDbType.NVarChar);
returnParam = cmd.Parameters.Add("@Num_of_User", SqlDbType.Int);// Set the direction of the parameters
objParam1.Direction = ParameterDirection.Input;
objParam2.Direction = ParameterDirection.Input;
returnParam.Direction = ParameterDirection.ReturnValue;// Set the values of the parameters
objParam1.Value = txtUser;
objParam2.Value = txtPass;try{if(conn.State.Equals(ConnectionState.Closed)){
conn.Open();
cmd.ExecuteNonQuery();}if((int)returnParam.Value <1){
messageLbl.Text ="Invalid Login!";returnfalse;}else{
conn.Close();returntrue;}}catch(Exception ex){
messageLbl.Text = ex +"Error connecting to database!";returnfalse;}finally{// Ensures connection has closed
conn.Close();}}
CREATE PROCEDURE proc_ValidateUser
(@usrNamenvarchar(15)= NULL,@usrPasswordnvarchar(15)= NULL,
@Num_of_User int=0)
AS
SET @Num_of_User =(SELECTCOUNT(*) AS Num_of_User
FROM tblUser
WHERE usrName=@usrName AND usrPassword=@usrPassword)
RETURN @Num_of_User
GO
I have a Default.aspx page created too, and everything builds with no errors.
However, when i go to the login page and type in Username and password, regardless of wheter or not the entries are correct, the login page basically refreshes, leaving the username text box filled, and the password text box blank. No error message is shown in the messageLbl control.
I'm no Expert by any means . I am just a beginner at asp.net and very willing to learn by other can anyone tell why i get this error. I though I followed the instruction correctly and it is a very good tutorial Paladine thanks.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.] login.frmlogin.DBConnection(String strUserName, String strPassword) +473 login.frmlogin.cmdSubmit_Click(Object sender, EventArgs e) +115 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +57 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI.Page.ProcessRequestMain() +1292
Unhandled Execution Error Object reference not set to an instance of an object. at login.frmlogin.DBConnection(String strUserName, String strPassword) at login.frmlogin.cmdSubmit_Click(Object sender, EventArgs e) at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) at System.Web.UI.Page.ProcessRequestMain()
First I am new to coding and db but working hard at learning.
The login page comes up fine and no bugs in the build bet...
In the below code I keep getting an exception error??? I have checked that the MDB and LDB files have R/W for the asp.net user but no luck.
The Error connecting to DB keeps comming up and the username and password are correct.
IIS 5.1 Access DB 2003 VS 2003
Any ideas would be great as the rest seems to be fine....
Thanks Heaps :confused:
' ||||| 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!" Else objReader.Close() ' ||||| Close the Connections & Reader Return True End If End While Catch ex As Exception 'lblMessage.Text = "Error Connecting to Database!" Label1.Text = "Error Connecting to Database!" End Try
Well, I need to ask what the error message says. If you could please provide that (more than saying an exception error), I think we can determine what the problem is.
What are the error message details.
First I am new to coding and db but working hard at learning.
The login page comes up fine and no bugs in the build bet...
In the below code I keep getting an exception error??? I have checked that the MDB and LDB files have R/W for the asp.net user but no luck.
The Error connecting to DB keeps comming up and the username and password are correct.
IIS 5.1 Access DB 2003 VS 2003
Any ideas would be great as the rest seems to be fine....
Thanks Heaps :confused:
' ||||| 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!" Else objReader.Close() ' ||||| Close the Connections & Reader Return True End If End While Catch ex As Exception 'lblMessage.Text = "Error Connecting to Database!" Label1.Text = "Error Connecting to Database!" End Try
Well, I need to ask what the error message says. If you could please provide that (more than saying an exception error), I think we can determine what the problem is.
What are the error message details.
I created a second lable box and sent ex to string and this was the result.
I am also building the SQL version to see how that goes.
Thanks for the help, am learning lots on this one...
System.Data.OleDb.OleDbException: Too few parameters. Expected 4. at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior) at WebListSite.WebForm1.DBConnection(String strUserName, String strPassword) in C:\Documents and Settings\Jason Apel\My Documents\My Webs\WebListSite\AdminLogin.aspx.vb:line 89
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.