0

I'm using VS 2012 Professional and SQL Server 2012 Express.

I have two problems.

First: I'm trying to run Registration.aspx, but I'm getting an error on this line from the MasterPage:

 txtLoginUser.Visible = True

Object reference not set to an instance of an object.

MasterPage:

<%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<script runat="server">



    Protected Sub Page_Load(sender As Object, e As EventArgs)

        If Session("userid") = Nothing Then
            txtLoginUser.Visible = True
            txtLoginPass.Visible = True

        Else


            Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
            Dim useridComm As String = "SELECT name, surname FROM users WHERE user_id=@userid"
            Dim sqlUserID As New SqlCommand

            conn.Open()

            Dim userid As String = Session("userid")

            sqlUserID = New SqlCommand(useridComm, conn)
            sqlUserID.Parameters.AddWithValue("@userid", userid)
            Dim datareader As SqlDataReader = sqlUserID.ExecuteReader()
            If datareader.HasRows Then
                Response.Redirect("Default.aspx")
                lblLoggedIn.Text = datareader("name").ToString() & " " & datareader("surname").ToString()
            End If
            datareader.Close()
            conn.Close()

        End If
    End Sub

   Protected Sub Button1_Click(sender As Object, e As EventArgs)

        Dim loginSQL As New SqlCommand
        Dim loginComm As String

        Dim CommonFunctions As New CommonFunctions()
        Dim dec_pass As String = CommonFunctions.EncryptPassword(txtLoginPass.Text.Trim)

        Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")


        loginComm = "SELECT user_id FROM users WHERE username=@username and password=@password"

        conn.Open()


        loginSQL = New SqlCommand(loginComm, conn)
        loginSQL.Parameters.AddWithValue("@username", txtLoginUser.Text.ToString)
        loginSQL.Parameters.AddWithValue("@password", dec_pass)
        Dim dr As SqlDataReader = loginSQL.ExecuteReader()
        dr.Read()


        If dr.HasRows Then
            Session("userid") = dr("user_id")
        ElseIf dr.HasRows = False Then

            lblRegister.ForeColor = Drawing.Color.Red
            lblRegister.Text = "Incorrect Username/Password."
        End If
        dr.Close()
        conn.Close()

    End Sub





</script>



<head>
    <meta charset="utf-8" />
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <title></title>
    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <link rel="stylesheet" href="style.css" type="text/css" media="screen, projection" />
</head>

<body>

    <form id="form1" runat="server">

<div id="wrapper">

    <header id="header">
        <strong>Header:</strong> Mobile CMS

        </header>


<section id="login">

    <div id="login-form">



            <asp:ContentPlaceHolder id="ContentPlaceHolder2" runat="server">

                <p>

                    <asp:Label ID="lblUsername" runat="server" Font-Bold="True" Text="U:"></asp:Label>
&nbsp;<asp:TextBox ID="txtLoginUser" runat="server" BorderStyle="None" BorderWidth="0px" Wrap="False"></asp:TextBox>
&nbsp;
                    <asp:Label ID="lblUsername0" runat="server" Font-Bold="True" Text="P:"></asp:Label>
                    <asp:TextBox ID="txtLoginPass" runat="server" BorderStyle="None" BorderWidth="0px" TextMode="Password" Wrap="False"></asp:TextBox>
&nbsp;
                    <asp:Button ID="btnLogin" runat="server" BorderStyle="None" OnClick="Button1_Click" Text="Login" />

                </p>

                <p>

                    <asp:Label ID="lblRegister" runat="server" Font-Bold="True" Font-Underline="True" ForeColor="#0000CC" Text="Register"></asp:Label>

                    <asp:ContentPlaceHolder ID="ContentPlaceHolder3" runat="server">
                        <asp:Label ID="lblLoggedIn" runat="server" Text=""></asp:Label>
                    </asp:ContentPlaceHolder>

                </p>


                </asp:ContentPlaceHolder>



    </div>

</section>

<div class="navigation-bar">
       <ul class="navigation-menu">

            <li><a href="#" class="home">Home</a></li>
            <li><a href="#" class="mainsettings">Settings</a></li>
            <li><a href="#" class="profile">Profile</a>

                <ul>
                    <li><a href="#" class="messages">Messages</a></li>
                    <li><a href="#" class="settings">Profile Settings</a></li>
                </ul>

            </li>
            <li><a href="#" class="uploads">Uploads</a></li>
            <li><a href="#" class="documents">Media</a>


                <ul>
                    <li><a href="#" class="docs">Documents</a></li>
                    <li><a href="#" class="others">Others</a></li>
                </ul>

            </li>

            <li><a href="#" class="projects">Projects</a>


                <ul>
                    <li><a href="#" class="yprojects">Your Projects</a></li>
                    <li><a href="#" class="otherprojects">Other Projects</a></li>
                </ul>

            </li>

        </ul>

    </div>


    <section id="middle">

        <div id="container">
            <div id="content">
                <div>
                    <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

                    </asp:ContentPlaceHolder>
                </div>
        </div>
        </div>



    </section>

    <footer id="footer">
        <strong>Footer:</strong> adsfdsgfds
    </footer>

</div>

    </form>

</body>
</html>

Registration.aspx:

<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Registration.aspx.vb" Inherits="Registration" %>

<%-- Add content controls here --%>
<asp:Content ID="Content1" runat="server" contentplaceholderid="ContentPlaceHolder1">

        <p>
            <strong>Name</strong></p>
        <p>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        </p>
        <p>
            <strong>Surname</strong></p>
        <p>
            <asp:TextBox ID="txtSurname" runat="server"></asp:TextBox>
        </p>
        <p>
            <strong>Username&nbsp;&nbsp;
            <asp:Label ID="lblUsername" runat="server" BorderStyle="Solid" Font-Bold="True" ForeColor="Red" Visible="False"></asp:Label>
            </strong></p>
        <p>
            <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
        </p>
        <p>
            <strong>Password</strong></p>
        <p>
            <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
        </p>
        <p>
            <strong>Confirm Password</strong></p>
        <p>
            <asp:TextBox ID="txtCPassword" runat="server" TextMode="Password"></asp:TextBox>
        </p>
        <p>
            <strong>Email</strong>
            <asp:RequiredFieldValidator ID="req4" runat="server" ControlToValidate="txtEmail" Text="*" />
            <asp:RegularExpressionValidator
              ID="emailValidator"
              runat="server"
              ErrorMessage="Incorrect Email!"
              controltovalidate="txtEmail"
              validationexpression="\w+\w*\@\w+\w+\w*\.(com|edu|org|gov)" Font-Bold="True" ForeColor="Red"

              ></asp:RegularExpressionValidator>

            </p>
        <p>

            <asp:TextBox ID="txtEmail" runat="server" Width="198px"></asp:TextBox>
        </p>
        <p>
            <strong>Confirm Email</strong>

            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtCEmail" Text="*" />
             <asp:RegularExpressionValidator
              ID="RegularExpressionValidator2"
              runat="server"
              ErrorMessage="Incorrect Confirmation Email!"
              controltovalidate="txtCEmail"
              validationexpression="\w+\w*\@\w+\w+\w*\.(com|edu|org|gov)" Font-Bold="True" ForeColor="Red"

              ></asp:RegularExpressionValidator>

        </p>
        <p>
            <asp:TextBox ID="txtCEmail" runat="server" Width="191px"></asp:TextBox>



        </p>
        <p>
            <strong>Address </strong>
        </p>
        <p>
            <strong>
            <asp:TextBox ID="txtAddress1" runat="server" Width="237px"></asp:TextBox>
            </strong>
        </p>
        <p>
            <strong>
            <asp:TextBox ID="txtAddress2" runat="server" Width="238px"></asp:TextBox>
            </strong>
        </p>
        <p>
            <strong>City</strong></p>
        <p>
            <asp:TextBox ID="txtCity" runat="server" Width="143px"></asp:TextBox>
        </p>
        <p>
            <strong>Country</strong></p>
        <p>
            <asp:DropDownList ID="drpCountry" runat="server" DataSourceID="XmlDataSource1" DataTextField="iso" DataValueField="iso">
            </asp:DropDownList>
            <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/countries/countries.xml"></asp:XmlDataSource>
        </p>
        <p>
            <strong>Date of Birth&nbsp;&nbsp;
            <asp:Label ID="lblCal" runat="server" BorderStyle="Solid" Font-Bold="True" ForeColor="Red" Visible="False"></asp:Label>
            </strong></p>
        <p>
            <asp:Calendar ID="calDOB" runat="server" BackColor="White" BorderColor="#999999" Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" Height="180px" Width="200px" CellPadding="4" DayNameFormat="Shortest" EnableTheming="True">
                <DayHeaderStyle Font-Bold="True" Font-Size="7pt" BackColor="#CCCCCC" />
                <NextPrevStyle VerticalAlign="Bottom" />
                <OtherMonthDayStyle ForeColor="#808080" />
                <SelectedDayStyle BackColor="#666666" ForeColor="White" Font-Bold="True" />
                <SelectorStyle BackColor="#CCCCCC" />
                <TitleStyle BackColor="#999999" BorderColor="Black" Font-Bold="True" />
                <TodayDayStyle BackColor="#CCCCCC" ForeColor="Black" />
                <WeekendDayStyle BackColor="#FFFFCC" />
            </asp:Calendar>

        </p>

        <p>
            <asp:DropDownList ID="drpMonth" runat="server" AutoPostBack="True">
            </asp:DropDownList>
            <asp:DropDownList ID="drpYear" runat="server" AutoPostBack="True">
            </asp:DropDownList>
        </p>
        <p>
            <strong>Occupation</strong></p>
        <p>
            <asp:TextBox ID="txtOccupation" runat="server" Width="143px"></asp:TextBox>
        </p>
        <p>
            <strong>Work Location</strong></p>
        <p>
            <asp:TextBox ID="txtWorkLocation" runat="server" Width="143px"></asp:TextBox>
        </p>
        <p>
            &nbsp;</p>
        <p>
            <asp:Button ID="btnRegister" runat="server" BorderStyle="Solid" Text="Register" />
        </p>
        <p>
            <strong>
            <asp:Label ID="lblFields" runat="server" BorderStyle="Solid" Font-Bold="True" ForeColor="Red" Visible="False"></asp:Label>
            </strong>
        </p>
        <p>
            &nbsp;</p>

</asp:Content>

<asp:Content ID="Content2" runat="server" contentplaceholderid="ContentPlaceHolder2">
</asp:Content>

Second: The second problem is that when I run the MasterPage and enter the login details, the login will not work, and if I click do it two times I get this:

Entering twice the login credentials (Result)

What is happening? How can I solve this problem?

What I want to do is that if a session with the 'userid' is available it will display "Welcome, Name Surname" and if not, re-show the login screen (2 textboxes, button + label)

Brian
  • 1,951
  • 16
  • 56
  • 101
  • 1
    You don't put stuff in ContentPlaceHolder in the master page... that is where pages that use the master page put their stuff. – MikeSmithDev Apr 03 '13 at 17:18
  • @MikeSmithDev So the best way would be to put the login a class? – Brian Apr 03 '13 at 17:22
  • Just move it outside of the ContentPlaceHolder. – MikeSmithDev Apr 03 '13 at 17:23
  • @MikeSmithDev Thanks! That fixed the registration.aspx problem. As for the login, it still gives me the same error ! – Brian Apr 03 '13 at 17:26
  • I've never seen a Page_Load as a script in the markup file, and I'm not sure whether that should work. I would put the Page_Load into the codebehind file, e.g. MasterPage.master.vb. – criticalfix Apr 03 '13 at 17:38
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Apr 03 '13 at 17:42
  • 1
    @criticalfix its doable, just not common. Not really different from any other server side code in the markup. Obviously a codebehind file is better. – MikeSmithDev Apr 03 '13 at 18:08
  • Thanks @MikeSmithDev, I wasn't sure whether that was legit. Glad to know it's another option. – criticalfix Apr 03 '13 at 18:23

1 Answers1

1
  1. You need to move the login stuff outside of ContentPlaceHolder with id of ContentPlaceHolder2.

  2. You are getting the 2nd error due to infinite redirects. You are on default.aspx and your master page sees you are logged in, runs your query, and redirects you back to default.aspx... and the cycle continues. You need to get rid of that redirect.

A better way to handle authentication, is instead of using that session variable, just set an authentication cookie. You can use something like FormsAuthentication.RedirectFromLoginPage.

So something like:

If dr.HasRows Then
    FormsAuthentication.RedirectFromLoginPage(dr("user_id"), true)

With this cookie you will be able to use much of the built-in ASP.NET functionality for handling login/authentication.

MikeSmithDev
  • 15,731
  • 4
  • 58
  • 89