?
Solved

How to handle Null DateTime from Sql Db for Login Check

Posted on 2013-06-26
4
Medium Priority
?
612 Views
Last Modified: 2013-06-26
Hello Expert,

I have a method that validate users and check for first time user at Login.  The Db have a "LastPasswordChangedDate" field with Null values.  When I run the app I get this error
>>> "Specified cast is not valid".  How do I handle the null value and perform the check?  See Codes Below:

protected void LoginOnAuthenticate(object sender, AuthenticateEventArgs e)
        {
            TextBox userName = (TextBox)LoginUser.FindControl("UserName");
            TextBox userPassword = (TextBox)LoginUser.FindControl("Password");

            string username = userName.Text;
            string password = FormsAuthentication.HashPasswordForStoringInConfigFile(userPassword.Text, "SHA1");            

            if (Membership.ValidateUser(username, password))
            {
                Session["UserName"] = username;
               
                FirstTimeLoginChecker userInfo = new FirstTimeLoginChecker(username);              
                int daysSincePwdChange = Convert.ToInt32(DateTime.Now.Subtract(userInfo.LastPasswordChangedDate).TotalDays);
                if (daysSincePwdChange > SecurityUtility.DefaultPasswordExpiryInDays || userInfo.CreationDate.ToShortDateString() == userInfo.LastPasswordChangedDate.ToShortDateString() || userInfo.CreationDate == DateTime.Now)                
                {
                   
                    Response.Redirect("~/Account/ChangePassword.aspx");
                                       
                }

                else
                {
                     e.Authenticated = true;
                }              
                                                                           
            }
                                                 
        }





public class FirstTimeLoginChecker
{

    private string username;
    private DateTime lastPasswordChangedDate;
    private DateTime creationDate;

    public string UserName
    {
        get
        {
            return username;
        }

        set
        {
            username = value;
        }
    }

    public DateTime LastPasswordChangedDate
    {
        get
        {
            return lastPasswordChangedDate;
        }

        set
        {
            lastPasswordChangedDate = value;
        }
    }

    public DateTime CreationDate
    {
        get
        {
            return creationDate;
        }

        set
        {
            creationDate = value;
        }
    }

    public FirstTimeLoginChecker(string username)
      {
        using (SqlConnection conn = WhpsInternalConnectionManager.WhpsDbConnection())
        {
            //conn.Open();
            SqlCommand cmd = new SqlCommand("whps.spSelectByUserName", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@username", username);

            SqlDataReader reader = cmd.ExecuteReader();
            reader.Read();            

            this.lastPasswordChangedDate = (DateTime)reader["LastPasswordChangedDate"];
            this.creationDate = (DateTime)reader["CreationDate"];

            reader.Close();
            conn.Close();
        }
      }  
   
}




public class SecurityUtility
{


    public const int DefaultPasswordExpiryInDays = 90;
   

    public static int PasswordExpiryInDays
    {
        get
        {
            string expiry = ConfigurationManager.AppSettings["PasswordExpiryInDays"];
            if (string.IsNullOrEmpty(expiry))
            {
                return DefaultPasswordExpiryInDays;
            }
            else
            {
                return Convert.ToInt32(expiry);
            }
        }
    }
       
}

Thank you for your help.  :)
0
Comment
Question by:iNetBlazer
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 21

Accepted Solution

by:
Dale Burrell earned 2000 total points
ID: 39280060
Two ways to handle that, either modify the SP to not return a null value for the date, but then you have to decide what to return instead - a very old date might work.

Otherwise modify your code by changing

 this.lastPasswordChangedDate = (DateTime)reader["LastPasswordChangedDate"];

Open in new window


to

 object tempPasswordDate = reader["LastPasswordChangedDate"];
 if (tempPasswordDate != System.DBNull.Value) this.lastPasswordChangedDate = (DateTime)tempPasswordDate; /* You may want to set it to a minimum datetime value when the returned value is null, up to you */

Open in new window

0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 39280062
Before casting you need to check if value is DBNull:

http://forums.asp.net/t/1383849.aspx/1
0
 
LVL 16

Expert Comment

by:Surendra Nath
ID: 39280068
There are many ways to handle this situtation, one of the simplest one is to return a far off date as the CreationDate / LastPasswordChangedDate when it is NULL...

The change needs to be done in the stored procedure, to return 01/01/1900 if the value of the either dates is null...

the in the function FirstTimeLoginChecker, check if the dates are equal to 01/01/1900 then ensure that this is the first time user and it didn't change yet.
0
 

Author Closing Comment

by:iNetBlazer
ID: 39280134
Thanx dale_burrell, that worked perfect since I can't change the SP to return an old date.

Again Thank You :)
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question