• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 998
  • Last Modified:

Specified cast is not valid. Need help debugging.

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
deloused
Asked:
deloused
  • 3
  • 2
1 Solution
 
_Katka_Commented:
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
 
delousedAuthor Commented:
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
 
_Katka_Commented:
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
 
delousedAuthor Commented:
Thanks for your help.  You really saved my sanity!
0
 
_Katka_Commented:
You're welcome :)

regards,
Kate
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now