Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

How to handle Null DateTime from Sql Db for Login Check

Posted on 2013-06-26
4
Medium Priority
?
619 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

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

604 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