Solved

How to handle Null DateTime from Sql Db for Login Check

Posted on 2013-06-26
4
579 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanx dale_burrell, that worked perfect since I can't change the SP to return an old date.

Again Thank You :)
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

771 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

14 Experts available now in Live!

Get 1:1 Help Now