Solved

Specified cast is not valid. Need help debugging.

Posted on 2006-12-01
5
969 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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
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.

746 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

13 Experts available now in Live!

Get 1:1 Help Now