Invalid Cast Exception when filling datatable wth table adaptor - sql

I am using VB.NET 2010 (Visual Basic 2010 Express) on a WPF-based project. I am also using the SQL Server Express built-in to Visual Basic 2010 express.
I have just about finished refining my code for hooking up my wpf-based form to an existing SQL database (agentroster.sdf). I have a global data source (AGENT_ROSTER) connected to this database. Connections are confirmed to work properly.
This is the first part of the code I'm using, irrelevant code omitted,
Dim table_adaptor As New AGENT_ROSTERTableAdaptors.AGENT_ROSTERTableAdaptor
Dim roster_table As New DataTable("roster_table")
Dim rowposition As Integer
Private Sub ROSTER_Loaded...
table_adaptor.Fill(roster_table)
End Sub
I am getting the following errors:
(In Immediate Window)
A first chance exception of type 'System.InvalidCastException' occured in VBP-WORD4WORD.exe
(In Message, pointing to the line: "table_adaptor.Fill(roster_table)')
InvalidCastException was unhandled
Unable to cast object of type 'System.Data.DataTable' to type 'AGENT_ROSTERDataTable'.
What am I doing wrong, and furthermore, how do I fill roster_table with table_adaptor (or alternate method)?

Assuming that your strongly typed DataSet is called "AGENT_ROSTER":
Dim table_adaptor As New AGENT_ROSTERTableAdaptors.AGENT_ROSTERTableAdaptor
Dim roster_table As New AGENT_ROSTER.roster_table
table_adaptor.Fill(roster_table)
Have a look at Efficient Coding With Strongly Typed DataSets.

Related

Late Binding & Type Issues In VB

I'm trying to run my code which was originally created using Visual Studio through another application where late bindings are disallowed and this option cannot be altered unfortunately. I am very new to programming in general and struggling to get my head around the issue. Here is the code im using in the invoke code stage:
Dim objIEShell As Object = CreateObject("Shell.Application")
Dim objIEShellWindows As Object = objIEShell.Windows
Dim objIEWin As Object
For Each objIEWin In objIEShellWindows
If InStr(objIEWin.LocationURL,"google")>0 Then
objIEWin.Quit
objIEWin = Nothing
End If
Next
The code simply closes all instances of Internet Explorer with "google" in the URL. This is the error message I get when trying to compile it:
Message: Error compiling code
error BC30574: Option Strict On disallows late binding. At line 2
error BC32023: Expression is of type 'Object', which is not a collection type. At line 4
From the research I've done so far I realise the first error message on line 2 is to do with the type difference between objIEShell and the Windows method. I think I have to convert objIEShell like this, CType(objIEShell,?), but I don't know the type of the .Windows method or how to find this out. Also any insight on how the fix the second error would be greatly appreciated as I'm not sure where to start with that one either.
This dates back to the wonky days when Microsoft still had plans to make Explorer behave like a web browser. Makes it pretty hard to arrive at the correct code, it is a combination of two separate COM components that don't have much to do with each other.
You need to first add two references to those components so the compiler understands the names. Use Project > Add Reference > COM tab and tick "Microsoft Internet Controls" and "Microsoft Shell Controls and Automation". That adds the Shell32 and SHDocVw namespaces.
Now you can write the code early-bound like this:
Dim objIEShell = New Shell32.Shell
Dim objIEShellWindows = CType(objIEShell.Windows, SHDocVw.IShellWindows)
Dim objIEWin As SHDocVw.WebBrowser
For Each objIEWin In objIEShellWindows
If InStr(objIEWin.LocationURL, "google") > 0 Then
objIEWin.Quit()
End If
Next
The CType() expression is probably the most unintuitive one, the Shell.Windows property is of type Object to break the dependency between those two components. The cast is the necessary voodoo to keep the compiler happy.

How to use Lambda functions with embedded code in SSRS 2008 R2 reports?

Using SSRS 2008 R2 with embedded code, the VB.Net code compiler seems to err whenever I need to do anything beyond the simplest of statements.
For instance, I want to use the LINQ Select function to perform some operations on the elements of a collection, but BIDS keeps throwing compiler errors on lines of perfectly valid VB.Net code.
Public Function SplitToIDs(ByVal multiValue As String) As Integer()
Dim regex As New System.Text.RegularExpressions.Regex("((?>.*?);#\d*;#)", System.Text.RegularExpressions.RegexOptions.Compiled Or System.Text.RegularExpressions.RegexOptions.ExplicitCapture Or System.Text.RegularExpressions.RegexOptions.CultureInvariant Or System.Text.RegularExpressions.RegexOptions.IgnoreCase)
Dim results As New System.Collections.Generic.List(Of String)()
Dim matches As System.Text.RegularExpressions.MatchCollection = regex.Matches(multiValue)
For Each mvMatch As System.Text.RegularExpressions.Match In matches
results.Add(mvMatch.Value)
Next
'Dim pairs As String() = SplitToPairs(multiValue)
'Dim names As System.Collections.Generic.IEnumerable(Of Integer) = System.Linq.Enumerable.Select(pairs, Function(p) Integer.Parse(Microsoft.VisualBasic.Split(p, ";#")(1)))
Dim names As System.Collections.Generic.IEnumerable(Of Integer) = System.Linq.Enumerable.Select(results, Function(p) Integer.Parse(Microsoft.VisualBasic.Split(p, ";#")(1)))
Return System.Linq.Enumerable.ToArray(names)
End Function
On the line 42, which is the comment immediately above where I call System.Linq.Enumerable.Select, Visual Studio 2008 (the VS Shell installed by SQL Server 2008 R2), gives this error when I attempt to preview my report:
An error occurred during local report processing.
The definition of the report '/XXXX' is invalid.
There is an error on line 42 of custom code: [BC30201] Expression expected.
I have already learned that [BC30201] is a generic error with little relation to a missing expression. As seen in my code, I have fully namespace qualified every function or variable beyond the most basic System namespace classes. In the Report Properties dialog, References tab, I've already referenced both mscorlib and System.Core to make sure all the functions I'm using in my code can be resolved to a System assembly.
So a few questions...
Can Anonymous Functions be called and used in SSRS 2008 R2 Reports' embedded code?
In getting to this point, I was getting the same [BC30201] error when I attempted to call one method in the embedded code from another. Yet, I was sure I had some simpler methods in an earlier iteration of this report (or another report) were this actually worked... Should we be able to call one custom method from another within the embedded code?
Notes:
I'm highly tempted to create a separate code module, but I really don't want to fight the political battle necessary to convince lots of people that we should install custom assemblies on our Reporting servers. But unless, I can call those assemblies directly from various report expressions, I may still need to use the embedded code to make the assemblies' methods available to the report.
The source data comes from a SharePoint 2010 list. Many of the columns are Lookup columns that allow multiple values. The method above strips out the delimiters and values to return a collection of IDs.

Office Developer tools: Can't cast System._Comobject to excel types [duplicate]

This question already has answers here:
Try to open my Excel file using C# and get an error
(3 answers)
Closed 6 years ago.
I am trying to communicate with Excel through Visual Studio, using the Office Developer Tools, but cannot seem to cast the System._comobject objects to the Microsoft.Office.Tools.Excel types:
Private Sub ThisAddIn_Startup() Handles Me.Startup
Me.Application.Workbooks.Add()
Me.Application.Worksheets.Add()
Dim sheet2 = Me.Application.Worksheets.Item(1)
Dim cell = sheet2.range("A2")
cell.Value = sheet2.GetType.ToString()
Dim tmpSheet As Microsoft.Office.Tools.Excel.Worksheet = Me.Application.Worksheets.Item(1)
End Sub
When I run this code, the cell A2 contains "System._ComObject" But I get an exception when casting it to the Worksheet type. The exception is:
Unable to cast COM object of type 'System.__ComObject' to interface
type 'Microsoft.Office.Tools.Excel.Worksheet'. This operation failed
because the QueryInterface call on the COM component for the interface with
IID '{297DC8D9-EABD-45A1-BDEF-68AB67E5C3C3}' failed due to the following
error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
I am aware that this is often due to incorrect registery keys, like here:
unable to cast COM object of type 'microsoft.Office.Interop.Excel.ApplicationClass' to 'microsoft.Office.Interop.Excel.Application'"
But I only have one registery key, removed it, and office itself put it back in it's place, so I guess it's the correct one.
Does anyone know how I can solve this?
I use Visual Studio 2015, and office 2013 Standard, in english.
Thank you in advance!
Apperantly I needed to use the type:
Microsoft.Office.Interop.Excel.Worksheet
Instead of
Microsoft.Office.Tools.Excel.Worksheet

Preview/Print MS Access Report from Visual Basic

I have an Visual Basic 2013 program which connects to a MS Access 2010 database. After the program calculates and writes values out to the DB, I need to print a report that is in the Access DB.
I have read through this: How To Automate Microsoft Access From Visual Basic .NET
I found similar questions such as this: Vb.Net preview report from access database but they do not use the DoCmd.OpenReport method.
The code I have now is as follows:
Imports Access = Microsoft.Office.Interop.Access
Public Class FrmReports
Dim oAccess As Access.application
Private Sub btnSumByPlan_Click(sender As Object, e As EventArgs) Handles btnSumByPlan.Click
oAccess = CreateObject("Access.Application")
oAccess.visible = True
oAccess.opencurrentdatabase ("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|\CLI_CRVM.accdb")
oAccess.docmd.openreport(ReportName:="SumByPlan", View:=Access.AcView.acViewPreview)
End Sub
End Class
This code compiles but gives me the following error when it runs:
An unhandled exception of type 'System.InvalidCastException' occurred in CLI CRVM.exe
Additional information: Unable to cast COM object of type 'Microsoft.Office.Interop.Access.ApplicationClass' to class ype 'CLI_CRVM.Access.applicationclass'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
Thanks in advance.
The argument to the OpenCurrentDatabase() method of an Access.Application object is just the location of the database file, not an OLEDB connection string. Your statement should be something more like
oAccess.OpenCurrentDatabase("C:\path\to\CLI_CRVM.accdb")
Also, I am unable to say for certain if |DataDirectory| is meaningful in that context, but I highly doubt it.

Conversion from type 'String' to type 'String' is not valid

I'm in the process of porting an old excel addin that was writen in VBA to VB .NET. The Excel addin interacts with a number of external com objects. The code sorta looks like this:
Dim hurr as Object
Dim durr as String
hurr = CreateObject("COM Object")
durr = hurr.getString
What I'm trying to do is read the string from the COM object and get it in durr for use later in my program.
That second line results in the exception posted above. If I try casting with CStr/CType I get the same exception. The visual studio watch window reports the type of hurr.getString as a "System.__ComObject" whereas the VBA watch window reports the type as "Variant/Object/String". Microsoft.VisualBasic.Information.TypeName(hurr.getString) says the type is "String". Any ideas how I should go about getting this working?
Thanks!
This is ridiculous but I figured I would post the answer here for completeness. The solution was to add a pair of brackets to the end of hurr.getString
so the working code looks like this:
Dim hurr as Object
Dim durr as String
hurr = CreateObject("COM Object")
durr = hurr.getString()
The above code gave me the casting exception and for whatever reason it needs brackets to work here. I'm just going to add that working with late binding com objects is horrible and should be avoided at all costs.