Solved

How to handle Null DateTime from Sql Db for Login Check

Posted on 2013-06-26
4
583 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
4 Comments
 
LVL 21

Accepted Solution

by:
Dale Burrell earned 500 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 29

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
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.
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

896 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now