Solved

Specified cast is not valid. Need help debugging.

Posted on 2006-12-01
5
972 Views
Last Modified: 2008-01-09
I'm getting the error "Specified cast not valid"  I'm newb and need help debugging.  I'm sure it's an issue with the data type but I'm not sure where to look or how to convert.  Here's the full error:

Line 870:                    actualDuration = Convert.ToDecimal(returnData["ProjectActualDuration"]);
Line 871:
Line 872:                Project project = new Project(actualDuration, (string)returnData["ProjectCreatorDisplayName"], (DateTime)returnData["ProjectCompletionDate"], (DateTime)returnData["ProjectCreationDate"], (string)returnData["ProjectDescription"],
Line 873:                                         (Decimal)returnData["ProjectEstimateDuration"], (int)returnData["ProjectId"], (string)returnData["ProjectManagerDisplayName"], (string)returnData["ProjectName"], (decimal)returnData["ProjectNumber"]);
Line 874:                prjList.Add(project);
 

Source File: ...App_Code\DAL\SQLDataAccessLayer.cs    Line: 872

Stack Trace:


[InvalidCastException: Specified cast is not valid.]
   ASPNET.StarterKit.DataAccessLayer.SQLDataAccess.TGenerateProjectListFromReader(SqlDataReader returnData, List`1& prjList) in f:\Documents and Settings\fosterco\My Documents\Visual Studio 2005\WebSites\TimeTracker-C\App_Code\DAL\SQLDataAccessLayer.cs:872
   ASPNET.StarterKit.DataAccessLayer.SQLDataAccess.TExecuteReaderCmd(SqlCommand sqlCmd, TGenerateListFromReader`1 gcfr, List`1& List) in f:\Documents and Settings\fosterco\My Documents\Visual Studio 2005\WebSites\TimeTracker-C\App_Code\DAL\SQLDataAccessLayer.cs:856
   ASPNET.StarterKit.DataAccessLayer.SQLDataAccess.GetAllProjects() in f:\Documents and Settings\fosterco\My Documents\Visual Studio 2005\WebSites\TimeTracker-C\App_Code\DAL\SQLDataAccessLayer.cs:411
   ASPNET.StarterKit.BusinessLogicLayer.Project.GetAllProjects(String sortParameter) in f:\Documents and Settings\fosterco\My Documents\Visual Studio 2005\WebSites\TimeTracker-C\App_Code\BLL\Project.cs:176

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +0
   System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +72
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +358
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +29
   System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method, Boolean disposeInstance, Object& instance) +484
   System.Web.UI.WebControls.ObjectDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +1869
   System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +13
   System.Web.UI.WebControls.DataBoundControl.PerformSelect() +140
   System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +68
   System.Web.UI.WebControls.GridView.DataBind() +4
   System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +61
   System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +67
   System.Web.UI.Control.EnsureChildControls() +97
   System.Web.UI.Control.PreRenderRecursiveInternal() +50
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5730

 
0
Comment
Question by:deloused
  • 3
  • 2
5 Comments
 
LVL 10

Expert Comment

by:_Katka_
ID: 18059038
Hi, this can be caused by many reasons, let me take some of them one at a time:

Line 872:

Project project = new Project(actualDuration,
    (string)returnData["ProjectCreatorDisplayName"], -> a
    (DateTime)returnData["ProjectCompletionDate"], -> b
    (DateTime)returnData["ProjectCreationDate"],  -> c
    (string)returnData["ProjectDescription"], -> d
    (Decimal)returnData["ProjectEstimateDuration"], -> e
    (int)returnData["ProjectId"],  -> f
    (string)returnData["ProjectManagerDisplayName"],  -> g
    (string)returnData["ProjectName"],  -> h
    (decimal)returnData["ProjectNumber"]); -> i

1a) NULL values

You're not handling the case in which "returnData" has some values NULL. To solve that
use the variables to test for NULL values first.

appliable for a-i)

if (returnData["ProjectCreatorDisplayName"] == null)
{
   // custom solution of having NULL value for example
   throw new Exception("Project's creator display name is null !");
}

1b) NULL values (less safer solution)

Use "AS" (variable as Type) operator instead of implicit conversion (Type)variable

Project project = new Project(actualDuration,
    returnData["ProjectCreatorDisplayName"] as String,
    returnData["ProjectCompletionDate"] as DateTime,
    returnData["ProjectCreationDate"] as DateTime,
    returnData["ProjectDescription"] as String,
    returnData["ProjectEstimateDuration"] as Decimal,
    returnData["ProjectId"] as Int32,
    returnData["ProjectManagerDisplayName"] as String,
    returnData["ProjectName"] as String,
    returnData["ProjectNumber"] as Decimal);



2) DBNULL values

You're also not handling the DBNULL values which requires the same preliminary care.

appliable for a-i)

if (returnData["ProjectCreatorDisplayName"] == DBNull.Value)
{
   // custom solution of having DBNULL value for example
   throw new Exception("Project's creator display name is null !");
}

3) possible invalid conversion from long (Int64) to int (Int32) in case of "projectId" case f)
4) alternatively you can check if your type conversions are matching those performed

regards,
Kate
0
 

Author Comment

by:deloused
ID: 18060664
i'm cetain that problem stems from case "i" because it compiled and worked without the "ProjectNumber" added.  Here is my full function code:

        private void TGenerateProjectListFromReader<T>(SqlDataReader returnData, ref List<Project> prjList)
        {
            while (returnData.Read())
            {
                decimal actualDuration = 0;
                if (returnData["ProjectActualDuration"] != DBNull.Value)
                    actualDuration = Convert.ToDecimal(returnData["ProjectActualDuration"]);  
               
                Project project = new Project(actualDuration, (string)returnData["ProjectCreatorDisplayName"], (DateTime)returnData["ProjectCompletionDate"], (DateTime)returnData["ProjectCreationDate"], (string)returnData["ProjectDescription"],
                                         (Decimal)returnData["ProjectEstimateDuration"], (int)returnData["ProjectId"], (string)returnData["ProjectManagerDisplayName"], (string)returnData["ProjectName"], (decimal)returnData["ProjectNumber"]);

                prjList.Add(project);
            }
        }

Where do i put the If Null statement you have above?  I'm new to programing with C#.  Thanks for you help.
0
 
LVL 10

Accepted Solution

by:
_Katka_ earned 300 total points
ID: 18060798
Hi, I would recommend the combination of cases 1a) and 2) or 1b) and 2) at least:

safe approach (value initialization, null check, dbnull check and all covered by exception):

        private void TGenerateProjectListFromReader<T>(SqlDataReader returnData, ref List<Project> prjList)
        {
            while (returnData.Read())
            {
                // variables initialization
                Decimal projectActualDuration = 0;
                String projectCreatorDisplayName = string.Empty;
                DateTime projectCompletionDate = DateTime.Now;
                DateTime projectCreationDate = DateTime.Now;
                String projectDescription = string.Empty;
                Decimal projectEstimateDuration = 0;
                Int32 projectId = 0;
                String projectManagerDisplayName = string.Empty;
                String projectName = string.Empty;
                Decimal projectNumber = 0;

                // variables NULL check
                if (returnData["ProjectActualDuration"] != null && returnData["ProjectActualDuration"] != DBNull.Value)
                {
                    projectActualDuration = (Decimal)returnData["ProjectActualDuration"];    
                }
                else
                {
                    throw new Exception("ProjectActualDuration is null or invalid!");
                }
 
                ...
                and so on (the check above) for the other variables
                ...

                try
                {
                    Project project = new Project(projectActualDuration, projectCreatorDisplayName, projectCompletionDate, projectCreationDate,
                                             projectDescription, projectEstimateDuration, projectId, projectManagerDisplayName, projectName, projectNumber);
                }
                catch (Exception ex)
                {
                    throw new Exception("Error occured while creating new project!", ex);
                }

                prjList.Add(project);
            }
        }

less safe approach but still safer then the original one:

        private void TGenerateProjectListFromReader<T>(SqlDataReader returnData, ref List<Project> prjList)
        {
            while (returnData.Read())
            {
                try
                {
                    Project project = new Project(returnData["ProjectActualDuration"], returnData["ProjectCreatorDisplayName"] as String,
                                             returnData["ProjectCompletionDate"] as DateTime, returnData["ProjectCreationDate"] as DateTime,
                                             returnData["ProjectDescription"] as String, returnData["ProjectEstimateDuration"] as Decimal,
                                             returnData["ProjectId"] as Int32, returnData["ProjectManagerDisplayName"] as String,
                                             returnData["ProjectName"] as String, returnData["ProjectNumber"] as Decimal);
                }
                catch (Exception ex)
                {
                    throw new Exception("Error occured while creating new project!", ex);
                }

                prjList.Add(project);
            }
        }

regards,
Kate
0
 

Author Comment

by:deloused
ID: 18061572
Thanks for your help.  You really saved my sanity!
0
 
LVL 10

Expert Comment

by:_Katka_
ID: 18062327
You're welcome :)

regards,
Kate
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

Suggested Solutions

Title # Comments Views Activity
Image(7) 1 53
which object should i use (efficiency) 5 45
How to measure sizes and angles in scanned images ? 3 52
scanning dentists xray (the small ones) 3 43
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
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.
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

911 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