Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 538
  • Last Modified:

.net 2.0 how to handle session or state ?

Hello,
I am new to .NET

Using .net 2.0 Visual Web Developer (Beta) I have managed to set up a system for users to register and authenticate on to a secure part of my website.

However I would like to be able to use the authenticated users information on these secure pages retreived from the Access database it is bound to (i.e display, edit his name, contact info etc.)

I vaguely understand that this can be done using "application state" or "session state" but didnt have any luck gettting this right.


The problem is in this bit
SelectCommand="SELECT UserId, Email FROM aspnet_Membership WHERE (UserId = @Param1)"

I dont know how to set the @param1 to the userId on the previous (authentication) page so that it can be recalled throughout the session.

Without having set a value to userId filed I also tried the following assuming this would be handled by .NET but didnt have much luck

SelectCommand="SELECT UserId, Email FROM aspnet_Membership WHERE (UserId = @UserId)"
@UserId or ? (question Mark for MS Access) works fine on the same page, but not on others.

Could someone please help, remember I'm new to this game.

Many Thanks
Mal

Following is my code on the page 2. first page is a basic authentication page which is pasted at the bottom

<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:AccessDataSource ID="AccessDataSource1" Runat="server" DataFile="~/Data/AspNetDB.mdb"
         SelectCommand="SELECT UserId, Email FROM aspnet_Membership WHERE (UserId = @Param1)" UpdateCommand="UPDATE aspnet_Membership SET Email = ? WHERE UserId = ?" EnableCaching="True"
        >
            <SelectParameters>
                <asp:SessionParameter Name="?"></asp:SessionParameter>
            </SelectParameters>
            </asp:AccessDataSource>&nbsp;
        <asp:DetailsView ID="DetailsView1" Runat="server" DataKeyNames="UserId" AutoGenerateEditButton="True"
            AutoGenerateRows="False" DataSourceID="AccessDataSource1">
            <Fields>
                <asp:BoundField ReadOnly="True" HeaderText="UserId" DataField="UserId" SortExpression="UserId"></asp:BoundField>
                <asp:BoundField HeaderText="Email" DataField="Email" SortExpression="Email"></asp:BoundField>
            </Fields>
        </asp:DetailsView><br />
    </div>
        <asp:LoginName ID="LoginName1" Runat="server" /><br />
        <br />
        <br />
        &nbsp;
    </form>
</body>
</html>




FIRST PAGE


<%@ Page Language="VB" AutoEventWireup="false" CompileWith="Default.aspx.vb" ClassName="Default_aspx" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;&nbsp;
        <asp:CreateUserWizard ID="CreateUserWizard1" Runat="server" ContinueDestinationPageUrl="~/check.aspx"
            EnableTheming="False">
            <WizardSteps>
                <asp:CreateUserWizardStep Runat="server" Title="Sign Up for Your New Account">
                </asp:CreateUserWizardStep>
                <asp:CompleteWizardStep Runat="server" Title="Complete">
                </asp:CompleteWizardStep>
            </WizardSteps>
        </asp:CreateUserWizard>
        </div>
    </form>
</body>
</html>
0
malboteju
Asked:
malboteju
  • 9
  • 6
1 Solution
 
maXXXeECommented:
u can just store it in a session variable
Session["key"]="value"
0
 
malbotejuAuthor Commented:
thanks a lot, can you please elaborate a bit more,  am very new to this.

I assume the code in the firstpage (login.aspx) should be

session["user"]=@UserId

and then not quite sure how to recall it on another page ???

Could you please post a sample code ?
many thanks
mal
0
 
maXXXeECommented:
assuming u r getting the username from a textbox from the login page
c#
<% Session["username"]=TextBox1.Text;   %>
i think the vb code wud be <% Session("username")=TextBox1.Text  %>

u wud access it like this
SELECT UserId, Email FROM aspnet_Membership WHERE UserId = Session("username")
0
Free recovery tool for Microsoft Active Directory

Veeam Explorer for Microsoft Active Directory provides fast and reliable object-level recovery for Active Directory from a single-pass, agentless backup or storage snapshot — without the need to restore an entire virtual machine or use third-party tools.

 
malbotejuAuthor Commented:
Thanks Again,  but I get the following Error.

I was not trying to get the username from a textbox but from the CreateUserWizard or from the Login control, I think these are called DataBoundControls in .NET 2.0 but there is no documentation to say how to retreive the values that get stored in them.

For example if I drag and drop a login name control to this second page it knows whose logged in on the first page and will show the correct ID. Which means the data I am after is already cached and is accessible from the second page. But I dont know what syntax to use to call it !!!

SELECT UserId, Email FROM aspnet_Membership WHERE UserId = ?????

But I did follow your advice to try get the value from a simple text box even that does not seem to work.

Server Error in '/X2' Application.
--------------------------------------------------------------------------------

IErrorInfo.GetDescription failed with E_FAIL(0x80004005).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.OleDb.OleDbException: IErrorInfo.GetDescription failed with E_FAIL(0x80004005).


HEre is my code firstpage

<%@ Page Language="VB" ClassName="LoginPageClass" %>
<% Session("username")=TextBox1.Text  %>  
<head runat="server">
<script runat="server"></script>  
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;<asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
        <a href="check.aspx">check.aspx</a></div>
    </form>
</body>
</html>


Second Page
<%@ Page Language="VB" %>
<head runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:AccessDataSource ID="AccessDataSource1" Runat="server" DataFile="~/Data/AspNetDB.mdb"
         SelectCommand='SELECT UserId, Email FROM aspnet_Membership WHERE UserId= Session("username")'
         UpdateCommand="UPDATE aspnet_Membership SET Email = ? WHERE UserId = ?" EnableCaching="True"
        >
        </asp:AccessDataSource>&nbsp;
        <asp:DetailsView ID="DetailsView1" Runat="server" DataKeyNames="UserId" AutoGenerateEditButton="True"
            AutoGenerateRows="False" DataSourceID="AccessDataSource1">
            <Fields>
                <asp:BoundField ReadOnly="True" HeaderText="UserId" DataField="UserId" SortExpression="UserId"></asp:BoundField>
                <asp:BoundField HeaderText="Email" DataField="Email" SortExpression="Email"></asp:BoundField>
            </Fields>
        </asp:DetailsView>
        </div>
        </form>
</body>
</html>
0
 
maXXXeECommented:
i might have to use ToString() with Session("username")
Session("username").ToString()
0
 
malbotejuAuthor Commented:
Could you please elaborate a bit more on this one, I'm not quite sure what you mean as I am very new here. Please see if you can help me to find answers to these questions

1. Is it possible to recall the userId that is entered into the login or createuserwizard DataBoundControls ? I saw somwhere it says this can be done easily, but nothing more on how to do it. and I am sure it can be done as the Loginname control displays the correct information during the session.

2. Failing the above can you please tell me how to do what you tried to do above (i.e from a text box)

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconpassingservercontrolvaluesbetweenpages.asp

0
 
maXXXeECommented:
cud u paste ur authentication page code?
0
 
malbotejuAuthor Commented:
This is my authentication page code (using the createuserwizard

<%@ Page Language="VB" autoeventwireup="false" compilewith="Default.aspx.vb" ClassName="Default_aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>&nbsp;&nbsp;
            <asp:CreateUserWizard id="CreateUserWizard1" EnableTheming="False" ContinueDestinationPageUrl="~/check.aspx" Runat="server">
                <WizardSteps>
                    <asp:CreateUserWizardStep Runat="server" Title="Sign Up for Your New Account"></asp:CreateUserWizardStep>
                    <asp:CompleteWizardStep Runat="server" Title="Complete"></asp:CompleteWizardStep>
                </WizardSteps>
            </asp:CreateUserWizard>
        </div>
    </form>
</body>
</html>



Default.aspx.vb is EMPTY like this

Partial Class Default_aspx
End Class
0
 
malbotejuAuthor Commented:
I have managed to pass values between two pages (i.e from a text box) to the second page using the inline code methode described below. It uses a Class for the job and works well.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconpassingservercontrolvaluesbetweenpages.asp

However in my scenario I dont have a textbox, but a "login control" or a "createuserwizard control" which does everything for me. These controls stores the UserId value somewhere which is why they can be recall using the "login name" control anywhere during the session. Without reinventing the wheel can I do the same ? Failing this I'll have to code the complete login control and password recovery system.

http://beta.asp.net/QUICKSTART/aspnet/doc/ctrlref/login/loginname.aspx
If you look above it says that this loginname control uses the value returned by calling the page.user.identity ?

How do I do this myself ?

0
 
malbotejuAuthor Commented:
Trying to put the above two together I came up with the following
trying to set the value of the first variable to page.user.identity but it returns the following error.

I get the"Implicit conversion from System.Security.Principal.IIdentity to string" when I move the mouse over
Return Page.User.Identity                      

Which shows that there is something wrong !


<%@ Page Language="VB" ClassName="FirstPageClass" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">
    <title>Untitled Page</title>
    <script runat="server">
      Public ReadOnly Property FirstName() As String
         Get
            ' first is the name of a TextBox control.
            Return first.Text
         End Get
      End Property

      Public ReadOnly Property LastName() As String
         Get
            ' last is the name of a TextBox control.
                Return Page.User.Identity                      
         End Get
      End Property

      Sub ButtonClicked(sender As Object, e As EventArgs)
         Server.Transfer("secondpage.aspx")
      End Sub

   </script>

</head>
<body>
    <form id="Form1" runat="server">
      First Name:
      <asp:TextBox id="first"
           runat="server"/>
      <br>
      Last Name:
      <asp:TextBox id="last"
           runat="server"/>
      <br>
      <asp:Button ID="Button1"
           OnClick="ButtonClicked"
           Text="Go to second page"
           runat=server />
        <asp:CreateUserWizard ID="CreateUserWizard1" Runat="server" ContinueDestinationPageUrl="~/secondpage.aspx">
            <WizardSteps>
                <asp:CreateUserWizardStep Runat="server" Title="Sign Up for Your New Account">
                </asp:CreateUserWizardStep>
                <asp:CompleteWizardStep Runat="server" Title="Complete">
                </asp:CompleteWizardStep>
            </WizardSteps>
        </asp:CreateUserWizard>
   </form>

</body>
</html>











Server Error in '/X2' Application.
--------------------------------------------------------------------------------

Specified cast is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Specified cast is not valid.

Source Error:

The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:

1. Add a "Debug=true" directive at the top of the file that generated the error. Example:

  <%@ Page Language="C#" Debug="true" %>

or:

2) Add the following section to the configuration file of your application:

<configuration>
   <system.web>
       <compilation debug="true"/>
   </system.web>
</configuration>

Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.

Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario
0
 
maXXXeECommented:
try
Return Page.User.Identity.ToString

did u get it working?
0
 
malbotejuAuthor Commented:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: BC30456: 'ToString' is not a member of 'System.Security.Principal.IIdentity'.

Source Error:

 

Line 17:          Get
Line 18:             ' last is the name of a TextBox control.
Line 19:                 Return Page.User.Identity.ToString
Line 20:                        
Line 21:          End Get
 

Source File: d:\inetpub\wwwroot\X2\firstpage.aspx    Line: 19

0
 
maXXXeECommented:
sorry, forgot name property
Return Page.User.Identity.Name.ToString
0
 
malbotejuAuthor Commented:
It seems to be a correct syntax but I still get this :


Server Error in '/X2' Application.
--------------------------------------------------------------------------------

Specified cast is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Specified cast is not valid.

Source Error:

The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:

1. Add a "Debug=true" directive at the top of the file that generated the error. Example:

  <%@ Page Language="C#" Debug="true" %>

or:

2) Add the following section to the configuration file of your application:

<configuration>
   <system.web>
       <compilation debug="true"/>
   </system.web>
</configuration>
 
0
 
malbotejuAuthor Commented:
Full points for you for trying to help me !

Got it sorted with your help of

"sorry, forgot name property
Return Page.User.Identity.Name.ToString"


This is the working syntax for anyone having the same problem... you can use the same method in secondpage to recall the identity value anywhere in the session.

FIRST PAGE

<%@ Page Language="VB" ClassName="FirstPageClass" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

<head>
    <title>Untitled Page</title>
    <script runat="server">
      Public ReadOnly Property FirstName() As String
         Get
            ' first is the name of a TextBox control.
                Return Page.User.Identity.Name.ToString
            End Get
      End Property

        Sub ButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
            Server.Transfer("secondpage.aspx")
        End Sub
   </script>
</head>
<body>
    <form id="Form1" runat="server">
      <asp:Button ID="Button1"
           OnClick="ButtonClicked"
           Text="Go"
           runat=server />
   </form>
</body>
</html>


SECOND PAGE

<%@ Page Language="VB" %>
<%@ Reference Page="firstpage.aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <script runat="server">
        Dim fp As FirstPageClass
        Sub Page_Load()
            If Not IsPostBack Then
                fp = CType(Context.Handler, FirstPageClass)
            End If
        End Sub
   </script>
</head>
<body>
   <form id="Form1" runat="server">
      Hello <%=fp.FirstName%>
   </form>
</body>
</html>
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

  • 9
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now