Object reference error on form build - vb.net

I'm having issues debugging my project as i'm getting a "An error occurred creating the form. See Exception.InnerException for details. The error is: Object reference not set to an instance of an object."
It appears it relates to the following line
Private allfiles = lynxin.GetFiles("*.txt")
from the below declarations
Public Class Form1
Private numfiles As Integer
Private AllDetail() As FileDetail
Private allfiles = lynxin.GetFiles("*.txt")
Private AllDetails(allfiles.Count) As FileDetail
I'm needing these set so they can be accessed for all controls within Form1
I've read through the troubleshooting tips but cannot seem to fix the issue without moving the line back within the control its primarily used in

Related

Error when I add connection string in a UserControl

I am facing a weird problem, I am trying to create Usercontrol (Add_companies)and add it to panel
Everything work fine but when I add the connection to the user control I face this error :
The variable 'Add_companies1' is either undeclared or was never assigned.
And this is my connection:
Protected configuracion As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("Conn")
Dim Conn As New SqlConnection(configuracion.ConnectionString)
Public Cmd As SqlCommand
Error one image
where the error code must be
and when i go to the code line error there's nothing.
Protected configuracion As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("Conn")
Dim Conn As New SqlConnection(configuracion.ConnectionString)
Public Cmd As SqlCommand
You indicate that you placed this code in your UserControl and now the Form designer is throwing errors. The VS IDE is loading and running an instance of the usercontrol when it is placed on the design surface.
These three lines of code would have to be placed at the class level to support the Protected and Public access modifiers. The issue is that the designer is not able to retrieve ConfigurationManager.ConnectionStrings("Conn") so configuracion is null when it is used in Dim Conn As New SqlConnection(configuracion.ConnectionString).
When you use the syntax: Dim var as New Something() at the class level, the compiler converts that to Dim var as Something and places var = New Something() into the class constructor (Sub New) code.
To fix this problem you need to prevent code that will throw an error while in design mode from executing. All controls have a Boolean property named DesignMode for this purpose. Note that DesignMode will not be valid if used in the constructor code, so trying to use it there will fail.
Imports System.Configuration
Imports System.Data.SqlClient
Public Class Add_companies
Protected configuracion As ConnectionStringSettings
Private Conn As SqlConnection
Public Cmd As SqlCommand
Private Sub Add_companies_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Not Me.DesignMode Then
configuracion = ConfigurationManager.ConnectionStrings("Conn")
Conn = New SqlConnection(configuracion.ConnectionString)
End If
End Sub
End Class

Error with DotNetOpenAuth2 with VB.Net

My new project demands the implementation OpenAuth. Following is my code.
The line
scopes.Add(CalendarService.Scopes.Calendar.GetStringValue())
in the GetAuthorization gives the following error.
Overload resolution failed because no accessible...
GetStringValue is the most specific for these argument. I can understand that GetStringValue is not the method/argument found in the calendarservice.scopes.calendar but my question is why so? I have downloaded this code from some website and most website is giving example in C# but there are hardly any site that is showing any example in VB.Net. Can anyone help me here.
Regards
P.S. I am using Visual Studio 2008.
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Calendar.v3
Imports Google.Apis.Util
Imports Google.Apis.Calendar.v3.Data
Imports Google.Apis.Tasks.v1
Imports Google.Apis.Tasks.v1.Data
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim provider = New NativeApplicationClient(GoogleAuthenticationServer.Description)
provider.ClientIdentifier = "Client ID Here"
provider.ClientSecret = "Client Secret Here"
Dim auth = New OAuth2Authenticator(Of NativeApplicationClient)(provider, AddressOf GetAuthorization)
Dim service = New CalendarService(auth)
Dim first = service.CalendarList.List.Fetch().Items().First()
Label1.Text = first.Summary
End Sub
Private Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState
Dim scopes As New System.Collections.Generic.List(Of String)
scopes.Add(CalendarService.Scopes.Calendar.GetStringValue())
Dim state As IAuthorizationState = New AuthorizationState(scopes)
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = arg.RequestUserAuthorization(state)
Process.Start(authUri.ToString())
' Open a modal dialogue for user to paste the authorization code from Browser = authCode
Dim authCode As String = Console.ReadLine()
Return arg.ProcessUserAuthorization(authCode, state)
End Function
End Class
GetStringValue is en extension method defined on Google.Apis.Util.Utilities.
Similar VB.NET code to this worked for me on VS2012 with the latest version of the library.
You can find my VB.NET sample in https://codereview.appspot.com/7007048/, but it still wasn't approved, so be careful using it.
In the samples repository (http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FDiscovery.VB.ListAPIs), there is currently only one VB.NET sample, but hopefully the sample above will be approved soon and it will be added to the repository.
Please elaborate more on the references that you have in your project and the stack trace.
It looks like there is another overloading to this GetStringValue somewhere else (http://msdn.microsoft.com/en-us/library/2hx4ayzs(v=vs.80).aspx) in your code or in a reference assembly.

Avoiding File Not Found Exception with Outlook Interop

I've got a simple singleton pattern class by which my application integrates with outlook, and several of the computers that run my application do not have outlook installed. I've wrapped all the interop stuff in try-catches to avoid raising exceptions when outlook is not available, but I'm still getting automated bug reports with FileNotFound exceptions.
Here is (the relevant code) in my class:
Imports Microsoft.Office.Interop
Public Class OutlookIntegration
Private Shared _instance As OutlookIntegration
Public Shared Sub Initialize()
_instance = New OutlookIntegration()
End Sub
Private _outlookApp As Outlook.Application
Private _outlookNs As Outlook.NameSpace
Private ReadOnly _outlookEnabled As Boolean
Private Sub New()
Try
_outlookApp = New Outlook.Application
_outlookNs = _outlookApp.GetNamespace("mapi")
_outlookNs.Logon()
Catch ex As Exception
_outlookApp = Nothing
_outlookEnabled = False
Exit Sub
End Try
_outlookEnabled = True
End Sub
End Class
And the error I'm getting is this:
Message: Could not load file or assembly 'office, Version=11.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its
dependencies. The system cannot find the file specified.
System.IO.FileNotFoundException
at OutlookIntegration..ctor()
at OutlookIntegration.Initialize() in OutlookIntegration.vb:line 7
at MyApplication_Startup(Object sender, StartupEventArgs e) in ApplicationEvents.vb:line 139
(System.IO.FileNotFoundException) Could not load file or assembly 'office, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies. The system cannot find the file specified.
It seems like i'm missing something simple here. Is the stack trace a red herring?
The exception is being thrown when your private members are being loaded into memory (Outlook.Application, Outlook.NameSpace, etc.) during a call to the OutlookIntegration constructor (OutlookIntegration..ctor()) and the appropriate Outlook dependencies don't exist on the client machine.
There are several ways you could handle this:
Handle the error when the constructor throws this exception (try/catch around ctor declaration in your Initialize() method)
Create another class that just tests whether Outlook is installed (avoid using private members)
Read the Windows registry keys which tell you whether Outlook is present or not
It's always best not to throw exceptions for performance reasons - so #3 would be my preference, but as long as you aren't continually performing this check you should be ok to use any of these options.

VBA to COM Exposed .NET assembly - Object doesn't support this property or method

Are shared properties accessible from a COM exposed .NET assembly?
VBA
Dim appExcel As Object
Dim objAppSingleton As Object
Set objAppSingleton = CreateObject("Pitchbook.CommonUtils.Application.PitchbookAppSingleton")
appExcel = objAppSingleton.CurrentPitchbookExcelApp
VB.NET
<ProgId("Pitchbook.CommonUtils.Application.PitchbookAppSingleton")> _
Public Class PitchbookAppSingleton
Private Shared _currentPitchbookExcelApplication As PitchbookAppExcel
Private Shared _syncLockExcel As Object = New Object()
Public Shared ReadOnly Property CurrentPitchbookExcelApp As PitchbookAppExcel
Get
If _currentPitchbookExcelApplication Is Nothing Then
SyncLock [_syncLockExcel]
If _currentPitchbookExcelApplication Is Nothing Then
Dim currPitchbookExcelApplication As New PitchbookAppExcel()
_currentPitchbookExcelApplication = currPitchbookExcelApplication
End If
End SyncLock
End If
Return _currentPitchbookExcelApplication
End Get
End Property
End Class
Public Class PitchbookAppExcel
Inherits PitchbookApp
Protected Friend Sub New()
MyBase.New()
End Sub
End Class
The line appExcel = objAppSingleton.CurrentPitchbookExcelApp gives the error:
Run-time error '438':
Object doesn't support this property or method
You need to say Set in VB to set an object variable.
Set appExcel = objAppSingleton.CurrentPitchbookExcelApp
If you don't say "Set" then VBA will look for the default method, and call that, to obtain a non-object type. If there is no default method defined (dispid=0) then it will fail with the error you are getting.
This is a very simple problem but if anyone doesn't know the answer already it's no you cannot access shared properties from a COM exposed .NET assembly. At least not directly... you can however access shared properties if you create an instance wrapper.
http://www.xtremevbtalk.com/showthread.php?p=1326018
http://support.microsoft.com/Default.aspx?kbid=817248
In my case I used the Facade pattern to create an object specifically for use by VBA that exposed the relevant shared utility functions via instances. Thanks to everyone for their comments.
http://en.wikipedia.org/wiki/Facade_pattern

Handling VB.NET events in VB6 code

I have some VB6 code that instantiates a class which handles events that are being raised from a VB.NET component. The VB6 is pretty straightforward:
private m_eventHandler as new Collection
...
public sub InitSomething()
dim handler as EventHandler
set handler = new EventHandler
m_eventHandler.Add handler
...
m_engine.Start
end sub
Note that the event handler object has to live beyond the scope of the init method (which is why it is being stored in a Collection). Note also that m_engine.Start indicates the point in the program where the VB.NET component would start raising events.
The actual event handler (as requested):
Private WithEvents m_SomeClass As SomeClass
Private m_object as Object
...
Private Sub m_SomeClass_SomeEvent(obj As Variant)
Set obj = m_object
End Sub
Note that m_object is initialized when an instance of EventHandler is created.
The VB.NET code which raises the event is even simpler:
Public ReadOnly Property SomeProp() As Object
Get
Dim obj As Object
obj = Nothing
RaiseEvent SomeEvent(obj)
SomeProp = obj
End Get
End Property
My problem is that when I debug the VB6 program, the first time InitSomething gets called, the event will not be handled (the VB6 event handler is never entered). Subsequent calls to InitSomething does work.
Everything works as I would have expected when I run the program outside the debugger. At this point, I'm not even sure if this is something I should be worried about.
It may or may not be relevant but the VB.NET was converted from a VB6 using the Visual Studio code conversion tool (and subsequently manually cleaned up).
I've found that if you are writing .Net Components for Consumption in VB6 (or any other COM environment) the utilisation of Interfaces is absolutely criticial.
The COM templates that comes out of the box with VStudio leave a lot to be desired especially when you are trying to get Events to work.
Here's what I've used.
Imports System.Runtime.InteropServices
Imports System.ComponentModel
<InterfaceType(ComInterfaceType.InterfaceIsDual), Guid(ClientAction.InterfaceId)> Public Interface IClientAction
<DispId(1), Description("Make the system raise the event")> sub SendMessage(ByVal theMessage As String)
End Interface
<InterfaceType(ComInterfaceType.InterfaceIsIDispatch), Guid(ClientAction.EventsId)> Public Interface IClientActionEvents
<DispId(1)> Sub TestEvent(ByVal sender As Object, ByVal e As PacketArrivedEventArgs)
End Interface
<ComSourceInterfaces(GetType(IClientActionEvents)), Guid(ClientAction.ClassId), ClassInterface(ClassInterfaceType.None)> _
Public Class ClientAction
Implements IClientAction
Public Delegate Sub TestEventDelegate(ByVal sender As Object, ByVal e As PacketArrivedEventArgs)
Public Event TestEvent As TestEventDelegate
public sub New()
//Init etc
end sub
public sub SendMessage(theMessage as string) implements IClientAction.SendMessage
onSendMessage(theMessage)
end sub
Protected Sub onSendMessage(message as string)
If mRaiseEvents Then
RaiseEvent TestEvent(Me, New PacketArrivedEventArgs(theMessage))
End If
End Sub
end Class
I've been able to get COM and .Net consumers of the Assembly/Component to work properly with events and be able to debug in and out of the component.
Hope this helps.
Just something to try - I have an inherent distrust of "As New .."
Can you try
private m_eventHandler as Collection
public sub InitSomething()
dim handler as EventHandler
set handler = new EventHandler
If m_eventHandler Is Nothing Then
Set m_eventHandler = New Collection
End if
m_eventHandler.Add handler
...
m_engine.Start
end sub
Alas, I've got no idea why this works in normal execution and not in debug except some vague suspicions that it's to do with .NET being unable to instantiate the VBA.Collection object (MS recommends that you write a quick VB6 component to do so), but since you're not creating collections in .NET code, it is still just a vague suspicion.