user login using session not working - asp.net

i need to retrive some data from table registration of database to show.aspx page after login. when i register a new user after registration and redirect it to the profile.aspx page then it works fine(showing all required data). but if i do logout and again do login to the same user then the page show.aspx show nothing
I am using this code for user login:
Protected Sub btnLogin_Click1(ByVal sender As Object, ByVal e As System.EventArgs)
Dim admin As String = "Admin"
Dim objcmd As New SqlCommand(("select * from Login where UserName='" + txtUserName1.Text & "' And Password='") + txtPassword1.Text & "'", con)
Dim objReader As SqlDataReader
con.Open()
objReader = objcmd.ExecuteReader()
If objReader.HasRows Then
While objReader.Read()
If [String].Compare(objReader("UserType").ToString(), admin) = 0 Then
Session("UserName_Admin") = txtUserName.Text.ToString().Trim()
Session("UserName") = txtUserName.Text.ToString().Trim()
Response.Redirect("adminview.aspx")
Else
Session("UserName") = txtUserName.Text.ToString().Trim()
Response.Redirect("show.aspx")
End If
End While
Else
lblLoginMessage.Text = "Login failed. Please try again"
End If
con.Close()
End Sub
code in the show.aspx page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Session("UserName") Is Nothing Then
Response.Redirect("registration.aspx")
End If
binddata()
End Sub
Sub binddata()
Dim mycommand As New SqlCommand("SELECT * FROM registration where UserName = #UserName", con)
mycommand.Parameters.AddWithValue("#UserName", Session("UserName").ToString())
con.Open()
ProfileData.DataSource = mycommand.ExecuteReader
ProfileData.DataBind()
con.Close()
End Sub
Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Redirect("upimg.aspx")
End Sub
i am using a datalist to retrieve data from database in show.aspx page.
is there anything i need to change in web.config file . a help will be appreciated

Is your logout code clearing the session values?
I think you would be far better off using the ASP.net Membership and Roles to handle this functionality because it will be much more secure and flexible.
Check out here an article explaining how to get setup here

I completely agree with #John Mc, using the Membership provider would be a much better idea.
As to clearing out session info, you should use:
Session.Clear()
Session.Abandon()

Related

join between two tables from access database in two different page in vb.net

I worked on a VB.NET project and I have a problem in how to connect between tables.
I have access database [database1]
tables : T1 , RequestDetails
T1: U_ID Name Address Phone
RequestDetails: U_ID RqNo Requestport country_of_request RqMethod
On first page, the user should enter his information Name Address Phone. When a buttom is clicked, this data is inserts into the database and navigates to the second page.
On the second page, the user should complete entering his data based on the U_ID
I have 3 dropdownlists: Requestport, country_of_request, and RqMethod
Andd also when a button is clicked, it should insert data and go next.
Everything's ok; I worked on each page in separate. Now I want to make connection between U_ID in T1 and RequestDetails to make data connected from page 1 and page 2.
I don't know how to explain problem I hope every thing was clear.
My code for page 1 :
I build connection class to do connection staff
Imports System.Data
Imports System.Data.OleDb
Imports System
Public Class connection
Dim str As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hp\Documents\Visual Studio 2010\Projects\WebApplication1\WebApplication1\bin\Database1.accdb"
Dim con As New OleDbConnection(str)
Public Sub Insert(ByVal Name As String, ByVal Address As String, ByVal Phone As String)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim adp As New OleDbCommand("insert into T1 values(" & GetMaxID() & ",'" & Name & "','" & Address & "','" & Phone & "') ", con)
adp.ExecuteNonQuery()
con.Close()
End Sub
Public Function GetMaxID() As Integer
Dim x As Integer = 1
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim adp As New OleDbCommand("select max(ID) from T1", con)
Try
x = adp.ExecuteScalar
Return x + 1
Catch ex As Exception
Return x
End Try
End Function
End Class
Then in the button :
Public Class _Default
Inherits System.Web.UI.Page
Dim x As New connection
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
x.Insert(TextBox1.Text, TextBox2.Text, TextBox3.Text)
Response.Redirect("~/ReqDetails.aspx")
End Sub
End Class
There is no problem here.
In the second page in the button:
Imports System.Data
Imports System.Data.OleDb
Imports System
Public Class shipmentDetails
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim str As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hp\Documents\Visual Studio 2010\Projects\WebApplication1\WebApplication1\bin\Database1.accdb"
Dim con As New OleDbConnection(str)
con.Open()
Dim Command As New OleDbCommand("INSERT INTO RequestDetails( Requestport," & "country_of_request," & "RqMethod,")VALUES(#Requestport,#country_of_request,#RqMethod)", con)"
Command.Parameters.Add(New OleDbParameter("#Requestport", Requestport.SelectedItem.Text))
Command.Parameters.Add(New OleDbParameter("#country_of_request", country_of_request.SelectedItem.Text))
Command.Parameters.Add(New OleDbParameter("#RqMethod", RqMethod.SelectedItem.Text))
)
Command.ExecuteNonQuery()
con.Close()
Label1.Text = "Thank You. Your transaction was successful."
Label1.Visible = True
End Sub
End Class
Here is the problem:
If I fill the data and click next it shows me an error because U_Id not fill and it should not null
That means it should read u_id from the page 1...How can I do it?
This looks like VB.NET code within an ASP project. If that's the case, I'd ask you to at least put that in the tags, but you can also use POST to send the U_ID to page two.
If this is a pure VB.NET application opening a second window you should be able to make the second window a child of the parent, make a global public variable called U_ID and be able to call parent.U_ID (Parent should ideally be the name of your original form.). I think ideally you can use the parent call in ASP as well, but I've never tried it myself.
I would have actually asked for some clarification, but I can't seem to do that just yet. If you'd care to confirm which of the two it actually is then I could edit in a little sample code if you need.
EDIT:
Here is something considerably easier than the HTTP Post methodology. For reference, read The msdn article.
Create the following in the main form.
Public ReadOnly Property U_ID() As Integer
Get
Return ID
End Get
End Property
Then append your one function like this (It's about the easiest way I can figure this to work:
Public ID as Integer
Public Function GetMaxID() As Integer
Dim x As Integer = 1
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim adp As New OleDbCommand("select max(ID) from T1", con)
Try
x = adp.ExecuteScalar
ID=x+1
Return x + 1
Catch ex As Exception
Return x
End Try
End Function
Now you have a public variable your second page can read like this:
<%# PreviousPageType VirtualPath="~/SourcePage.aspx" %>
Public U_ID as Integer = PreviousPage.U_ID
Try that. You should be able to access the previous page's U_ID.

Cannot read cookie from another page in different web application on same domain Asp.Net

When I open a page from another web application on same domain I am trying to read the cookie that was created on the original page, But it I cant read the cookie. If I move that page in to the same web application then it works, but thats not what I want.
[Domain: MyCompany.mobi]
[WebApp A] - create cookie and launch page
Protected Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim aCookie As New HttpCookie("TestCookie")
aCookie.Value = "Hello World"
aCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(aCookie)
Dim script = "window.open('http://MyCompany.mobi/webappB/default.aspx?id=TestCookie')"
'open page in WebsiteB
ScriptManager.RegisterStartupScript(Me, Me.GetType, "OpenPage", script, True)
End Sub
[Domain: MyCompany.mobi]
[WebApp B] - read the cookie and display in label
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim id As String = ""
If Request.QueryString("id") IsNot Nothing Then id = Request.QueryString("id").ToString
If Request.Cookies(id) IsNot Nothing Then
Dim aCookie As HttpCookie = Request.Cookies(id)
Label1.Text = aCookie.Name & " : " & aCookie.Value
Else
Label1.Text = "Cannot read cookie"
End If
End Sub
Cookies are associated with domain names; not the physical servers that are pointed to by DNS.
For security reasons, you cannot read cookies from a different domain name.
You need to pass the information in the URL.

displaying Username using session (ASP.NET)

I am using Visual Studio 2010 as my IDE and creating a simple website using Visual Basic I dunno if it's possible but can I display the Username that has just logged into my LoginForm to the other forms using sessions?
I'm not that good enough to understand it but can anyone tell me, is this the right way to contain the value in a session?, how can I display it to the other form?
Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
Dim connect As String = "Provider=Microsoft.ACE.OleDb.12.0;" & _
"Data Source=C:\Users\cleanfuel\Documents\Visual Studio 2010\Projects\FinalProject4a2p\FinalProject4a2p\bin\DBFinalProject.accdb"
Dim query As String
query = "Select Count(*) From tblAccount Where Username = ? And UserPass = ?"
Dim result As Integer = 0
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", TxtUser.Text)
cmd.Parameters.AddWithValue("", txtPass.Text)
conn.Open()
result = DirectCast(cmd.ExecuteScalar(), Integer)
End Using
End Using
If result > 0 Then
Response.Redirect("Menus.aspx")
Session("User") = TxtUser.Text
Session("Pass") = txtPass.Text
Else
Response.Write("<td>")
Response.Write("<div align=""center"">")
Response.Write("<font color='white'>")
Response.Write("Unable to Login, Invalid Username or Password! </font>")
Response.Write("</div>")
Response.Write("</td>")
End If
End Sub
Setup a label in your Master Page (if you have one), assign the user name from your session to the label and it will appear in all the pages. If you don't have Master page then can setup a label in the page (you want username to appear) and then set the label Text property to value from the session.
The way you are storing the values in the session is correct, you should redirect to Menu.aspx once the values are stored in the session like:
If result > 0 Then
Session("User") = TxtUser.Text
Session("Pass") = txtPass.Text
Response.Redirect("Menus.aspx")
....
And to access them you can do :
labelUserName.Text = Session("User").ToString()
Use FormsAuthentication, then you can simply put a LoginName control on your form, or get the UserName from HttpContext.Current.User.Identity.Name
The answers that the other users provide can be used also, but I find this one and successfully got the result that I want to have.
here are my codes:
Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
Dim connect As String = "Provider=Microsoft.ACE.OleDb.12.0;" & _
"Data Source=C:\Users\cleanfuel\Documents\Visual Studio 2010\Projects\FinalProject4a2p\FinalProject4a2p\bin\DBFinalProject.accdb"
Dim query As String
query = "Select Count(*) From tblAccount Where Username = ? And UserPass = ?"
Dim result As Integer = 0
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", TxtUser.Text)
cmd.Parameters.AddWithValue("", txtPass.Text)
conn.Open()
result = DirectCast(cmd.ExecuteScalar(), Integer)
End Using
End Using
If result > 0 Then
Dim myCookie As HttpCookie = New HttpCookie("USER")
myCookie.Value = TxtUser.Text
Response.Cookies.Add(myCookie)
Response.Redirect("Menus.aspx")
Else
Response.Write("<td>")
Response.Write("<div align=""center"">")
Response.Write("<font color='white'>")
Response.Write("Unable to Login, Invalid Username or Password! </font>")
Response.Write("</div>")
Response.Write("</td>")
End If
End Sub
I used HTTPcookie instead of session because I can't satisfy myself because it didn't displayed the value that I want to display and it always shows me the same ERROR over and over again.
here are the codes to display:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Request.Cookies("USER") Is Nothing Then
Label7.Text = "No Account Logged In"
Else
Dim aCookie As HttpCookie = Request.Cookies("USER")
Label7.Text = Convert.ToString(Server.HtmlEncode(aCookie.Value))
End If
End Sub

change textbox's value from pageload event, submit new values issue

I have created a form to update an access DB table. My issue is that when the text in the text boxes is changed and the form is submitted, the .text values stay the same as they were when the datareader loaded them on the page load event. How can I submit the values that the user updates, not what is already there from page load.
Code:
Public Property vehicleid As Integer
Public Property connstring As String = "myconnectionstring..."
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
vehicleid = Integer.Parse(Request.QueryString("vehicID"))
Dim svEnterdate, stocknum, make, model, color As String
Dim conn As New OleDbConnection(connstring)
Dim sql As String = "select * from vehicle where vehicleid=#vid"
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#vid", vehicleid)
conn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
svEnterdate = dr("enterdate").ToString()
stocknum = dr("stock_num").ToString()
make = dr("make").ToString()
model = dr("model").ToString()
color = dr("color").ToString()
End While
conn.Close()
EnterDateTXT.Text = svEnterdate
StockNumTXT.Text = stocknum
MakeTxt.Text = make
ModelTXT.Text = model
ColorTxt.Text = color
End Sub
'inbetween these 2 events the user can manipulate all the controls .text values, yet the
' .text values of the submitted controls below are the same as the ones filled by the
'datareader
Protected Sub SubmitBTN_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SubmitBTN.Click
Dim conn As New OleDbConnection(connstring)
Dim sql As String = "UPDATE Vehicle" & _
" SET stock_num=#stock, make=#make, model=#model, color=#color, enterdate=#enter " & _
"WHERE vehicleid=#vid"
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#vid", vehicleid)
cmd.Parameters.AddWithValue("#stock", StockNumTXT.Text)
cmd.Parameters.AddWithValue("#make", MakeTxt.Text)
cmd.Parameters.AddWithValue("#model", ModelTXT.Text)
cmd.Parameters.AddWithValue("#color", ColorTxt.Text)
cmd.Parameters.AddWithValue("#enter", EnterDateTXT.Text)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub
In your page load code, Check For Post back
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' Write your code to read data from database here
End
End Sub
If you dont check for postback in your page load event, Everytime when you click the submit button, It is going to excute the code in your page load ( load the content again to the text box) first. So whatever you entered in the textbox will be overwritten by the content form the database and that will be saved back again to the database.
To undestand this. Put a breakpoint in your Page_load event code and another in your button click event code. Now enter some value in textbox and click the button and see whether your code block in pageload is executing or not.
Checking the Postback check in your page_load will fix the problem.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx

How to sort a gridview once a radio button is selected

I'm trying to sort records in the gridview right after a radio button is selected. My approach is with the dataview, but because the dataset variable doesn't survive a round trip to the server, I don't know how to make this happen. please help!
Public Sub GetCustomers()
db.RunProcedure("usp_customers_get_all")
db.doSort(radList.SelectedValue)
gvCustomers.DataSource = db.MyView
End Sub
Protected Sub radList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radList.SelectedIndexChanged
If radList.SelectedValue = 0 Then
db.doSort(0)
gvCustomers.DataSource = db.MyView
End If
If radList.SelectedValue = 1 Then
db.doSort(1)
gvCustomers.DataSource = db.MyView
End If
End Sub
Public Sub doSort(ByVal strIn As Integer)
If strIn = 0 Then
MyView.Sort = "lastname, firstname"
Else
MyView.Sort = "username"
End If
End Sub
Public Sub RunProcedure(ByVal strName As String)
Dim objConnection As New SqlConnection(mstrConnection)
Dim mdbDataAdapter As New SqlDataAdapter(strName, objConnection)
Try
mdbDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
Me.mDataset.Clear()
mdbDataAdapter.Fill(mDataset, "tblCustomers")
MyView.Table = mDataset.Tables("tblCustomers")
Catch ex As Exception
Throw New Exception("stored procedure is " & strName.ToString & " error is " & ex.Message)
End Try
End Sub
You could store the dataset in one of the following places and then when the post back happens just load it again from there. I have done many of these on a corporate intranet.
Session Variable
ViewState
QueryString
Cache
I cant really provide more help as you didn't specify if this is done in Ajax or if you do a full postback etc. If you provide more info I would love to help you.

Resources