Results 1 to 16 of 16

Thread: [RESOLVED] InvalidCastException - Frustrating

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Mar 2012
    Posts
    87

    Resolved [RESOLVED] InvalidCastException - Frustrating

    Guys,
    You have got to help me out. I wrote this application that connects to an Oracle database, fetches data and uses the data to produce graphs. To the best of my ability, the program works as expected. So, I copied the project to a different location on the same computer and changed the connection string so that the application can connect to a different database. When I try to run this copy of the program, I get InvalidCastException. The master copy still runs without problems.

    The line of code that triggers this exception is effectively like the following:
    Code:
    Dim TypeOfDatabase As string
    TypeOfDatabase = "Oracle"  'This value is set according to the type of database the user has chosen.
    If TypeOfDatabase.Trim.ToUpper.Equals("ORACLE") Then
    When I tried to search for more information about the exception, it says the file 'f:\dd\ndp\clr\src\BCL\system\string.cs' does not exist. The folder path f:\dd\ndp\clr\src\BCL\system does not even exist in my computer. I do not know what is going on. I have been on this the whole day and I am going crazy.

    Please, help in any way you can.

  2. #2
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: InvalidCastException - Frustrating

    "Effectively like the following" is not the same as "is the following".

    When you get an InvalidCastException, it usually tells you the type it was trying to cast to and the type it was trying to cast from. For example:
    System.InvalidCastException: Conversion from type 'Object' to type 'Integer' is not valid.
    I caused this problem with the simple line "CInt(New Object())". You can't convert Object to Integer, and that's precisely what the exception tells me.

    The code you posted can't throw InvalidCastException because TypeOfDatabase is a String, and "ORACLE" is a String, so there's no non-String being fed to anything that needs conversion.

    So I don't think I can help unless you can tell me what the exception really says, and it'd be especially helpful if instead of "effectively like this" I could see "exactly like this".
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  3. #3
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,754

    Re: InvalidCastException - Frustrating

    Quote Originally Posted by 1369Times View Post
    The line of code that triggers this exception is effectively like the following:
    Code:
    Dim TypeOfDatabase As string
    TypeOfDatabase = "Oracle"  'This value is set according to the type of database the user has chosen.
    If TypeOfDatabase.Trim.ToUpper.Equals("ORACLE") Then
    When I tried to search for more information about the exception, it says the file 'f:\dd\ndp\clr\src\BCL\system\string.cs' does not exist. The folder path f:\dd\ndp\clr\src\BCL\system does not even exist in my computer. I do not know what is going on. I have been on this the whole day and I am going crazy.

    Please, help in any way you can.
    How about the code that fails? Giving us a piece of code that works means it isn't at all like a piece that doesn't.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  4. #4

    Thread Starter
    Lively Member
    Join Date
    Mar 2012
    Posts
    87

    Re: InvalidCastException - Frustrating

    The application is rather huge and it will make no sense posting the codes here. In fact I replaced the line that is causing the program to fail with the following:
    Code:
    ("Oracle").Trim.ToUpper.Equals("ORACLE")
    I put a break point on the line and ran the program. When code execution halted on the line, I stepped Into it and the line threw the InvalidCastException once more. As I said before, the master copy runs without problems. The only thing that is different between the two copies is the connection string; nothing else is different. The connection string is not even the line of code throwing up exception. I have never encountered string.cs before now. This is a C# file, but I have nothing to do with C#.

  5. #5
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,754

    Re: InvalidCastException - Frustrating

    Quote Originally Posted by 1369Times View Post
    The application is rather huge and it will make no sense posting the codes here. In fact I replaced the line that is causing the program to fail with the following:
    Code:
    ("Oracle").Trim.ToUpper.Equals("ORACLE")
    I put a break point on the line and ran the program. When code execution halted on the line, I stepped Into it and the line threw the InvalidCastException once more. As I said before, the master copy runs without problems. The only thing that is different between the two copies is the connection string; nothing else is different. The connection string is not even the line of code throwing up exception. I have never encountered string.cs before now. This is a C# file, but I have nothing to do with C#.
    First of all there has to be more than what you posted, that line won't compile by itself. I tried it this way
    Code:
            Dim TrueOrFalse As Boolean = ("Oracle").Trim.ToUpper.Equals("ORACLE")
    and TrueOrFalse is True. Based on what you have shown there can't be a problem, so it stands to reason it must be what you don't want to show.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  6. #6
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: InvalidCastException - Frustrating

    The file path you are worried about is something you found by digging too deep: it's telling you where the file was when Microsoft compiled your version of the .NET Framework. It's a red herring, so discard it.

    The information you need is the information I told you to look for: InvalidCastException tells you what the "from" and "to" types are. That's going to help you more than the stuff deep in the guts of the exception.

    The line of code you posted works. The line of code you have fails. It seems to me if the only two things on the table are a connection string and these lines, you could post them. Here's my guess:

    You have a connection string declared SOMEWHERE. It's very far away from the line of code that's throwing the exception.

    That connection string is passed around a lot of places, and eventually ends up getting to the line of code you're on. You're saying the line should look like what you pasted in, but I'm going to bet it looks a lot different and you're trying to simplify. Here's the thing.

    The original line is broken, because you don't understand what it's doing. So when you "simplify" it, you use code that's how you THINK it works. But that's not how it works, because there's not a way the line you're posting can throw InvalidCastException.

    So the only two possible conclusions are:
    • The machine where it happens is completely borked. Reformat it.
    • The line of code you aren't posting has a mistake no one's going to figure out until you post it.


    I can make a better psychic guess if you can tell me what the exception's "Message" property says. It should say something like "Cannot cast type '???' to 'String'". That will end the mystery almost as fast as posting the code, or at least it will be a clue that helps me tell you what the missing puzzle pieces look like.

    Let me be clear. Your line of code is doing the same thing as this:
    Code:
    Dim start As String = "Oracle"
    Dim trimmed As String = start.Trim()
    Dim uppercase As String = trimmed.ToUpper()
    Dim result As Boolean = uppercase.Equals("ORACLE")
    Nothing in that sequence requires a cast. "Oracle" is a String. Trim() returns a String. ToUpper() returns a String. Equals technically takes an Object argument, but is expecting a String. No casts should fail in that sequence.

    But.

    This expression returns a value and can't be on a line by itself. It has to be assigned to something. So you're lying, there's more to this line than you let on. It could look like this:
    Code:
    Dim result As ??? = ("Oracle").Trim...
    Or this:
    Code:
    If ("Oracle").Trim...
    Or any of a hundred other constructs. But it doesn't look like what you posted because when I tried pasting it into VS, the compiler complained.

    So pick 2:
    • Please post the information about the exception I asked for.
    • Please post the actual line of code that fails, with no modification, and enough context to sort out the types.
    • Please post the actual line of code that fails, after you "simplify" it.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Mar 2012
    Posts
    87

    Re: InvalidCastException - Frustrating

    Thanks for you response. The issue I am facing is entirely mine and I have no reason to lie about it. Also, the host computer works fine. Your comments prompted me to try and troubleshoot the code one more time. I think I placed the break point at an inappropriate line of code. Not sure why VB would say that it cannot find string.cs when I stepped into the code at that point and it would not complain about string.cs when I run the code normally, past that point. Anyway, I found that the line of code throwing the exception is actually further down. It is the OracleDataAdapter's Fill() method. I have attached an excerpt of the code as shown below. I am still not able to determine the cause of the exception though.

    Code:
    ElseIf TypeOfDatabase.Trim.ToUpper.Equals("ORACLE") Then
                Dim oraConnString As String
                oraConnString = ConnectionDetails  'the database name is the only modification made on the connection string.
                Dim conn As New Oracle.ManagedDataAccess.Client.OracleConnection(oraConnString)
    
                Try
                    'if the connection object is not opened already, then open it.  Connection may fail to open though.
                    If Not conn.State.Equals(ConnectionState.Open) Then
                        conn.Open()  'Connection opens without problem, meaning connection string is valid.
                    End If
    
                    'Create an Oracle TableAdapter object using the SQL statement and the connection object
                    Dim da As New Oracle.ManagedDataAccess.Client.OracleDataAdapter(sqlStatement, conn)
    
                    'Use the TableAdapter object just created to populate a named virtual table in the DataSet.
                    Try
                        da.Fill(ds, tableName) 'ds is a Dataset and tableName contains "RawDailyProductionRecord"
    
                    Catch ex As InvalidCastException
                        MessageBox.Show(ex.Message)
                        Stop
                    End Try
    The above code runs without problem in the master copy of the application. The database name is the only difference between this copy and the master copy. I have no idea about the casting that is going on inside the Fill() method.
    The complete application has more than five thousand lines of code, ten forms and the database to which the application connects. Besides, it contains proprietary information. Apology, I will not be able to attach the complete code to this thread.

  8. #8
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: InvalidCastException - Frustrating

    We're still missing the Message, that would tell you what kind of cast is failing, so we're going to have to keep playing 20 questions. Please give me the information I've asked for at least twice, I promise I'm not withholding answers for fun. We could've saved 12-15 hours if you answered the question I keep asking over and over again. Without that information, you have a lot of work to do:

    Think about what Fill() does. It executes its SELECT query, then converts each row of that resultset into a DataRow in a DataTable in a DataSet, using the typed DataSet information the TableAdapter configured by magic.

    So let's try the most braindead thing first: where is the variable "tableName" declared. What type is it? Is it String? If not, why not? That's a suspect, and you didn't provide the context for me to know what tableName is.

    The next most likely cause is "something inside Fill() tries to make a cast and for some reason that cast fails." That's a hard thing to debug, you'll have to consider your table schemas and every row. Coudl it possibly be the problem?

    "Why does it work on one machine and not the other?" The way to answer that question is always to ask, "Well, what could be different?" The code probably isn't changing, but you're working with two different machines. You've changed the connection string on the "broken" machine. That's different, but we agree is not likely the problem. But it implies the database is different between the two machines. That could be a very big deal.

    If you accidentally set up the 2nd database differently, it could have a column in one table that isn't the same. If you generated your TableAdapter against "database 1", and "database 2" is different in some way, you'll get weird, unpredictable results. The TableAdapter might encounter a situation like, "I expect this column to be VARCHAR(8), but it's some kind of blob type instead." That would be a situation where you can't cast from "what's in the database" to "a string", which is precisely the problem you have.

    So the next-most-likely problem requires:
    1. You are connecting to two different databases.
    2. The 2nd database schema doesn't perfectly match the first one.

    Investigate that. Alternatively, throw off the "magic TableAdapter gloves" and use lower-level types like DataReader to have a peek at the query results. What do you expect them to be? What are they in reality? If they are different, why?

    (This is why I argue against starting your life as a TableAdapter user. If you know how to write your own TableAdapter, you can write better tools to answer questions like, "Why is the TableAdapter broken on just this machine?")
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,988

    Re: InvalidCastException - Frustrating

    I would suggest throwing off the "magic TableAdapter" as an early step, too, if only for testing. After all, setting that particular code up to try it with a standard datatable wouldn't be too hard. It would be quite interesting if THAT approach failed, too. A TableAdapter makes some assumptions as to what the incoming data is. You seem to be violating one of those assumptions (though there are other alternatives, as Sitten pointed out). The standard datatable lacks the assumptions of a TableAdapter, but gets the schema from the DB table. It's a cruder instrument, which would be good for a look. One thing you can then do is look at the table schema for the datatable and see what it is. In fact, you could make up a little method that just create a datatable, fills it...then does nothing with it. If you then output the schema (even if you did something like WriteXML()) from both computers, you would have a file that would be easier to compare than trying to compare DB structures.
    My usual boring signature: Nothing

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Mar 2012
    Posts
    87

    Re: InvalidCastException - Frustrating

    The error message says "specified cast is not valid". But non of my codes has specified any cast so far. Is the DataAdapter specifying any cast behind the scene?

    The table name is definitely type String. See attached image.
    Is there a way to find out the data types the TableAdapter has configured?

    The Fill() method appears to have its own mind, performing type casting according to its own opinion.
    I am working with the same computer. The two copies of the application are in the same computer but obviously in different folders. The two Oracle databases are in this same computer.They have the same schema but they are populated with data from two separate sources.

    The SQL statement used to retrieve data from the databases is the same for both copies of the application. The connection string is also the same, except for the database name. But the connection string does not seem to be the cause because the OracleDataAdapter instance was successfully created based on the connection string.

    I am beginning to think that the issue may be coming from the underlying database and that the InvalidCastException might just be misleading. I am wondering what the Fill() method is trying to cast from one type to another type.

    I will try the TableReader suggestion. Thanks.
    Name:  Error message.PNG
Views: 907
Size:  2.3 KB
    Name:  tableName is string.PNG
Views: 893
Size:  3.9 KB

  11. #11
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: InvalidCastException - Frustrating

    If you put a breakpoint on the line that is displaying the message box what does the debugger show about the exception - there is a lot of information contained in the exception and all your handler is doing is displaying a fairly small amount of information to the user (who probably should be given a better error message as that will mean nothing to an end user).

  12. #12
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: InvalidCastException - Frustrating

    OK! That tells me it's a tricky error.

    Where you put ex.Message in the MessageBox, put ex.ToString() instead. Let's peek at the stack trace. If we get that, we can peek at the MS source and get a feeling for how this happens. (This is what PlausiblyDamp is suggesting.)

    I have a feeling the error message is so generic because at that point they're not sure if it's safe/interesting to try and print the type name. That implies it is definitely deep in the guts of the TableAdapter/DataAdapter and again I'd like to point out this is the real smoking gun:

    The Fill() method appears to have its own mind, performing type casting according to its own opinion.
    I am working with the same computer. The two copies of the application are in the same computer but obviously in different folders. The two Oracle databases are in this same computer.They have the same schema but they are populated with data from two separate sources.
    The Fill() method DOES have its own mind, it tries to look at the schema and does its best to make the matches. That's why it's "magic". If something goes wrong, it can be hard to figure out exactly what it was. That's the downside to "magic" and why I suggested taking a lower-level approach for sanity.

    "...but they are populated with data from two separate sources" is also a smoking gun. That means the rows are different. There's one row in one of the data sets that's breaking. Maybe you should start using paging to look at 100 records at a time to find the offending records, then 50, then 25, and so on until the set's small enough you can manually inspect them to figure out what's going on.

    What you're looking for is "some column that doesn't seem to have a value that matches what it says it should have."
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  13. #13

    Thread Starter
    Lively Member
    Join Date
    Mar 2012
    Posts
    87

    Re: InvalidCastException - Frustrating

    Thanks. StackTrace is attached. Apology, I blotted out the folder path on the last line at the bottom of the trace because it contains client-identifiable names.
    The idea of checking out the rows in the underlying database makes a lot of sense to me. However, that will require me to look through more than 65,000 rows of data. I will attempt the exercise if only to nail the culprit and stop messing with my codes.
    Name:  StackTrace.PNG
Views: 974
Size:  24.1 KB
    Name:  Source of error.PNG
Views: 917
Size:  5.8 KB

  14. #14
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: InvalidCastException - Frustrating

    Well, shoot. I should've known you said "Oracle". I'm not sure if they publish their code.

    What I can say is you don't have to look at 65,000 rows, not all at once though. I'm not familiar with Oracle, but here's how I'd do it in SQLite.

    I'd start by just doing "the first half":
    Code:
    SELECT whatever, whatever2 FROM yourTable LIMIT 32500
    If it doesn't break, do the 2nd half:
    Code:
    SELECT whatever, whatever2 FROM yourTable LIMIT 50000 OFFSET 32500
    Whichever one breaks, you want to examine half of that half. Let's say the first one breaks:
    Code:
    SELECT whatever, whatever2 FROM yourTable LIMIT 16250
    And
    [/code]
    SELECT whatever, whatever2 FROM yourTable LIMIT 16250 OFFSET 16250
    [/code]

    You'll get down to less than 100 rows in no time. I'm sort of stumped beyond that, I am still suspicious there's a difference in the schema somewhere.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  15. #15

    Thread Starter
    Lively Member
    Join Date
    Mar 2012
    Posts
    87

    Re: InvalidCastException - Frustrating

    Thanks a lot for the advice. I actually fetched one row at a time from the database and the InvalidCastException started at the 1000th row. What's wrong with this row? A field of type Float had a value of 614.28913260219341974077766698. Although I am not amused, this has been a good eye-opener for me and I have already sent a not-so pleasant mail to the Oracle database administrator. I will give update when the issue has been resolved.

  16. #16

    Thread Starter
    Lively Member
    Join Date
    Mar 2012
    Posts
    87

    Re: InvalidCastException - Frustrating

    Right, the Oracle database administrator eventually modified the field in question to have four decimal places. Problem solved! Thanks to everyone for the insights suggested.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width