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

Specified cast is not valid. Need help debugging.

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

839 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