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

x
?
Solved

Specified cast is not valid. Need help debugging.

Posted on 2006-12-01
5
Medium Priority
?
995 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
[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
  • 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 1200 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

618 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