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
Solved

How to handle Null DateTime from Sql Db for Login Check

Posted on 2013-06-26
4
588 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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

860 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