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:

Miller

I ran your code...and it works.

So something is messed up with either your settings in the browser or IIS?

Hehe..... sorry I dont have a more definite asnwer.

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


Miller

I am sorry...but I am at a total loss.

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

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

<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
			cookieless="false" timeout="20" />

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.


Miller

FYI

Registration Page completed : ASP.Net Registration Page

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

FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);

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

if (Session["Logged_IN"].Equals("No"))
			{
				Response.Redirect("../Members/Login.aspx?[B]ReturnUrl[/B]=/mdb/Admin/TestDetails.aspx");

			}

the code is in C# sorry no time to change.

Dear Paladine,

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.

Sharon Niles

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.

Hope this helps.... I am off to bed now.

Note

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

FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);

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

if (Session["Logged_IN"].Equals("No"))
			{
				Response.Redirect("../Members/Login.aspx?[b]ReturnUrl[/b]=/mdb/Admin/TestDetails.aspx");

			}

the code is in C# sorry no time to change.

Hi Paladine,

I have a stupid question. I am just learning ASP.NET and I am trying to build an ASP.Net login page using SQL.

I wanted to know about the DBConnection function. Where does that go? Does it go in the code_behind or in the aspx page?

I can show you my code thus far but it will be tonight since it is not with me right now.

Thanks in advance
anillm

VB.NET code would be in the code behind. It is a function I created, to provide scalability to the application.

Ok no problem, but you could have sent me a private message rather than posting here.

Please see my response on the other thread. Provide as much detail as you can when you have problem, it makes it easier to narrow it down.

Later

Hi Paladine,
If you have to read mu post please go to this link http://www.daniweb.com/techtalkforums/thread24148.html

I've a problem when i try to work for AccessDB with c#.

thanks,

BeeNarak

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:

private void Submit1_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!";
				}
			}
		}

		private bool ValidateUser(string txtUser, string txtPass)
		{
			// Connect to Database 
			DataAccess.DBConnection.GetLoginConnection();
			// Access Stored Procedure
			SqlCommand cmd = new SqlCommand("proc_ValidateUser", conn);
			cmd.CommandType = CommandType.StoredProcedure;
			// Create Parameters
			SqlParameter 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!";
					return false;
				}
				else
				{
					conn.Close();
					return true;
				}
			}
			catch (Exception ex)
			{
				messageLbl.Text = ex + "Error connecting to database!";
				return false;
			}
			finally
			{
				// Ensures connection has closed
				conn.Close();
			}
		}

Here is my connection code:

public static SqlConnection GetLoginConnection()
		{
			SqlConnection conn = new SqlConnection("Server=(local);Database=YLCdbSQL;Integrated Security=SSPI");
			return conn;
		}

Here is my stored procedure code

CREATE PROCEDURE proc_ValidateUser
(@usrName nvarchar(15) = NULL,
 @usrPassword nvarchar(15) = NULL,
 @Num_of_User int = 0
)

 AS

	SET @Num_of_User  =  (SELECT COUNT(*) 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.

Any ideas what the problem might be?

Thanks again.

Yup, I have a pretty good idea what is wrong. You say you get no build errors? Hmm, because here is what the problem is:

SqlCommand cmd = new SqlCommand("proc_ValidateUser", conn);

You pass in conn for the connection string, but no where in your code do you either declare conn or pass a value for it to retain?

So that is why it just refreshes right back to the Login page.

Hope this helps.

Great code, nice layout, clean, and logical. Well done!

Thanks for the compliments!

Thanks again Paladine, you must be some sort of other worldly genius!! I've got it working!! :cheesy:

Your time and efforts on these forums is much appreciated.

:o

Well thanks for the compliments. Glad it worked out.

I enjoying helping everyone here, just glad to see people are using my tutorials. That is enough of a compliment.

Take care....Happy Coding

:cool:

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()

Thanks for the help in advance

Well I find that interesting. I used your exact code, with only a minor change (debug="true"" in the web.config file) and it ran perfectly fine.


Have you tried setting the debug mode to true and not false? Try rebuilding the solution, before running the application.


Sorry I can't be of more help, but the code runs fine for me.

Thanks for looking at the code for me. I will keep troubleshooting my setup

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

It's my bad. I didn't know that the params in the SP must match the params in .net page

Your example works perfect. Thanks again.

I'm having the same problem can you explain further I am a newbie

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.