Getting A NullRefrenceException And Cannot Find Out Why? - vb.net

My goal here is to create a web browser that has a tab system in VB. Since I cannot explicitly name every single new tab the user will use, I have to make more generalized callings. Here's the conflicting code (my btnGo):
Dim thisBrowser As newWebBrowser = Me.tabBrowser.SelectedTab.Tag
If txtAdressSearch.Text.Contains(".com") Or txtAdressSearch.Text.Contains(".net") Or txtAdressSearch.Text.Contains(".gov") Or txtAdressSearch.Text.Contains(".edu") Or txtAdressSearch.Text.Contains(".org") Then 'More to be checked for
thisBrowser.Navigate(txtAdressSearch.Text)
Else
thisBrowser.Navigate("https://www.google.com/search?sourceid=chrome-psyapi2&rlz=1C1ASAA_enUS445&ion=1&espv=2&ie=UTF-8&q=" + txtAdressSearch.Text)
End If
And here's the newWebBrowser code:
Public Class newWebBrowser
Inherits WebBrowser
Private Sub webBrowserComplete() Handles Me.DocumentCompleted
Dim newTab As TabPage = frmBrowser.Tag()
Dim frmSK As New frmBrowser
Dim hi As String
newTab.Text = Me.DocumentTitle
frmSK.txtAdressSearch.Text = Me.Url.ToString
End Sub
End Class
Any time I enter something into txtAdressSearch, Visual Studio raises a NullRefrenceException and highlights thisBrowser.Navigate(txtAdressSearch.Text). As a side note, it says "Object reference not set to an instance of an object."
Anyone know whats the problem here? Thank you.

After debugging for more than an hour, I looked over my code and saw I was missing a big part of it. I wrote it all in and it worked fine. The issue was the tags weren't being defined correctly (and in some cases, not at all) so .Tag was returning Nothing.
Thanks to all who helped.

Related

Creating a new IUI Automation Handler object in order to subscribe to an automation event

So, here it goes. To start, A disclaimer, I understand that MS Access is not built for this kind of work. It is my only option at this time.
I have done just a bit of Automation using UIAutomationClient and I have successfully used its other features, however I cannot for the life of me get it to subscribe to events.
Normally, it is supposed to be a bit like this:
Dim CUI as new CUIAutomation
Dim FocusHandler as IUIAutomationFocusChangedEventHandler
Set FocusHandler = new IUIAutomationFocusChangedEventHandler(onFocusChanged)
C.AddFocusChangedEventHandler(Element,TreeScope_Children, null, FocusHandler)
end function
'
'
Function onFocusChanged(src as Object, args as AutomationEventArgs)
''my code here
end function
Yet when I attempt this, I get the error "expected end of statement" on the line:
FocusHandler = new IUIAutomationFocusChangedEventHandler(onFocusChanged)
additionally, if I leave off the (onFocusChanged) I get the error "Invalid use of new Keyword".
It seems like I am missing a reference somewhere. The usual drop down when using "new" does not contain the IUI handler classes though they are in the object library.
I am not sure if there is just some piece I am not accounting for in the code since I am using vba, but all examples seem to be for .net or C#/C++. Any help would be appreciated.
Additionally, I have no problem finding the element in question and all other pieces work fine. If you need any other pieces of the code let me know.
Edit: added set to line 3. No change in the problem though.
After two years this probably isn't relevant any more, but perhaps somebody else encounters this problem... The answer is to create a new class that implements the HandleAutomationEvent method.
Here I created a class named clsInvokeEventHandler and (importantly) set the Instancing property to PublicNotCreatable:
Option Explicit
Implements IUIAutomationEventHandler
Private Sub IUIAutomationEventHandler_HandleAutomationEvent(ByVal sender As UIAutomationClient.IUIAutomationElement, ByVal eventId As Long)
Debug.Print sender.CurrentName
End Sub
And to use it:
Sub StartInvokeHandler()
Dim oUIA As New CUIAutomation8
Dim oRoot As IUIAutomationElement
Dim InvokeHandler As clsInvokeEventHandler
Set InvokeHandler = New clsInvokeEventHandler
Set oRoot = oUIA.GetRootElement
oUIA.AddAutomationEventHandler UIA_Invoke_InvokedEventId, oRoot, TreeScope_Descendants, Nothing, InvokeHandler
End Sub

Proper release of COM objects in code

I have just started to migrate some code from VBA to VB.Net. So I am an absolute beginner in VB.Net – but I want to do things right. Maybe some of my questions are stupid but I guess that is because I am a beginner.
So as a first exercise I have developed my first piece of code (see below). Now I thought I have to release ALL COM objects again. Two of them throw errors already while writing the code. And others throw errors at runtime.
But the funny thing is: Weather I release the rest of the COM objects or not (by making the relevant not yet commented lines of Marshal.Release to comments as well – then all lines starting with Marshal.Release are comment lines) the behavior of the code is absolutely the same to my eyes.
Can anybody tell me where I can see/find the difference?
The internet tells me that there must be a difference?
But I guess I just don’t understand (till now).
Besides this many more questions are in my head:
Does every “Dim” statement create a COM Object - that has to be released later on?
If not how do I detect whether a COM object has been created or not? Which “Dim” statements create COM object and which don't?
In this example: Dim ActiveWindow As Object = Nothing Try ActiveWindow = Me.HostApplication.ActiveWindow() Catch End Try
Is
Marshal.ReleaseComObject(ActiveWindow)
identical to
Marshal.ReleaseComObject(Me.HostApplication.ActiveWindow())?
According to this:
http://www.codeproject.com/Tips/235230/Proper-Way-of-Releasing-COM-Objects-in-NET
Would it not be better to release each "level" separately like this:
Marshal.ReleaseComObject(Me.HostApplication.ActiveWindow())
Marshal.ReleaseComObject(Me.HostApplication)
Marshal.ReleaseComObject(Me)
Overall: Am I trying to release too much? Or is it correct / good practie?
And what does "GC.Collect()" and "… = Null" have to do with all this? I have not used it at all. Should I better use it? Why? ( "... = Null" I have seen here:
http://www.codeproject.com/Tips/162691/Proper-Way-of-Releasing-COM-Objects-in-NET)
Why do I get “ShapeCount was not declared …” - Error if I try to do “Marshal.ReleaseComObject(ShapeCount)”? The same with “ShRange”. I think these are COM objects as well?!?
How do I notice when is the best time to release the COM object again? When I process/debug my code step by step with F11 will it be possible for me to determine the best (soonest) point of release? So far I have no “feeling” about when the COM object is not needed anymore and I can release it.
Any help and explanations very welcome.
Here is the code I am talking about:
Imports System.Runtime.InteropServices
Imports System.ComponentModel
Imports System.Windows.Forms
Imports AddinExpress.MSO
Imports PowerPoint = Microsoft.Office.Interop.PowerPoint
'Add-in Express Add-in Module
<GuidAttribute("D75C609E-7632-400F-8A6F-6A6E6E744E75"),
ProgIdAttribute("MyAddin8.AddinModule")> _
Public Class AddinModule
Inherits AddinExpress.MSO.ADXAddinModule
#Region " Add-in Express automatic code "
[…]
#End Region
Public Shared Shadows ReadOnly Property CurrentInstance() As AddinModule
Get
Return CType(AddinExpress.MSO.ADXAddinModule.CurrentInstance, AddinModule)
End Get
End Property
Public ReadOnly Property PowerPointApp() As PowerPoint._Application
Get
Return CType(HostApplication, PowerPoint._Application)
End Get
End Property
Private Sub AdxRibbonButton2_OnClick(sender As Object, control As IRibbonControl, pressed As Boolean) Handles AdxRibbonButton2.OnClick
MsgBox(GetInfoString2())
End Sub
Friend Function GetInfoString2() As String
Dim ActiveWindow As Object = Nothing
Try
ActiveWindow = Me.HostApplication.ActiveWindow()
Catch
End Try
Dim Result As String = "No document window found!"
If Not ActiveWindow Is Nothing Then
Select Case Me.HostType
Case ADXOfficeHostApp.ohaPowerPoint
Dim Selection As PowerPoint.Selection =
CType(ActiveWindow, PowerPoint.DocumentWindow).Selection
Dim WindowViewType As PowerPoint.PpViewType = PowerPoint.PpViewType.ppViewNormal
Dim SlideRange As PowerPoint.SlideRange = Selection.SlideRange
Dim SlideCountString = SlideRange.Count.ToString()
If WindowViewType = 9 And SlideCountString < 2 Then
Dim ShRange As PowerPoint.ShapeRange = Nothing
Try
ShRange = Selection.ShapeRange
Catch
End Try
If Not ShRange Is Nothing Then
Dim ShapeCount = ShRange.Count.ToString()
Result = "You have " + ShapeCount _
+ " shapes selected."
Else
Result = "You have 0 shapes selected."
End If
End If
'Marshal.ReleaseComObject(ShapeCount)
'Marshal.ReleaseComObject(ShRange)
'Marshal.ReleaseComObject(WindowViewType)
'Marshal.ReleaseComObject(SlideCountString)
Marshal.ReleaseComObject(SlideRange)
Marshal.ReleaseComObject(Selection)
Case Else
Result = AddinName + " doesn't support " + HostName
End Select
'Marshal.ReleaseComObject(Me.HostType)
'Marshal.ReleaseComObject(Result)
Marshal.ReleaseComObject(Me.HostApplication.ActiveWindow())
Marshal.ReleaseComObject(Me.HostApplication)
'Marshal.ReleaseComObject(Me)
End If
Return Result
End Function
End Class
The ReleaseComObject method of the Marshal class decrements the reference count of the specified Runtime Callable Wrapper (RCW) associated with the specified COM object, it doesn't release an object. It comes from the COM nature.
Typically you need to release every object returned from the Office (PowerPoint in your case) object model. Exceptions are objects passed to event handlers as parameters.
You may read more about that and find answers to your multiple questions in the When to release COM objects in Office add-ins developed in .NET article.
FinalReleaseComObject calls ReleaseComObject til it returns 0 which means release of COM object. Calling them in reverse order as in Excel objects(Application, Workbook, Worksheet) is the proper way to dispose of COM objects that are related.
Exception Condition
ArgumentException
o is not a valid COM object.
ArgumentNullException
o is null.

Reset ToggleButtons

I am hoping to set all of the togglebuttons in a powerpoint to "false" (unpressed) upon starting the program. Any ideas why this sort of code is working?
Sub Start()
ActivePresentation.Slides(4).ToggleButton1.Value = 0
ActivePresentation.Slides(4).ToggleButton4.Value = 0
ActivePresentation.SlideShowWindow.View.Next
End Sub
Thank you!
The syntax
ActivePresentation.Slides(4).ToggleButton1.Value = 0
is correct; I've just tested it and it works.
Are you actually calling the Sub at any point though? Simply naming it Start() is not enough.
Related question re. running code on startup, could be helpful.
I had an issue calling this
ActivePresentation.Slides(4).ToggleButton1.Value = 0
Getting the error Method or data member not found which im assuming is a scope issue. The VBA editor doesnt autocomplete .ToggleButton1 which supports the error i was getting.
So, it appears im referencing the object incorrectly.
To correct this I have done the following.
Public Sub ToggleThisButton()
' This is code on Slide 1 referencing control on slide 4
ActivePresentation.Slides(4).Shapes("ToggleButton1").OLEFormat.Object.Value = 1
End Sub
Excerpt from MSDN
Use the OLEFormat property for a shape, inline shape, or field to
return the OLEFormat object. The following example displays the class
type for the first shape on the active document.
Use the Object
property to return an object that represents an ActiveX control or OLE
object. With this object, you can use the properties and methods of
the container application or the ActiveX control.

How can I load a 'future' forms controls before I use them? Explained in detail:

I am performing a migration on a vb6 program, to vb.net. The basic knowledge you need to understand this question is that there are two forms that need to talk to each other, frmInput1 and frmInput2. I have the following code (behind frmInput1) that checks if a textbox on frmInput2 has a certain value, seemingly before it has loaded:
If frminput2.lblInputMac.Text <> "(no filename)" Then
Dim calc As CalculationCaster = New CalculationCaster
Call calc.FillMac()
cmdNext.Enabled = False
frminput2.FraInner.Enabled = True
I get the following error on the If line when i run it:
"Object reference not set to an instance of an object."
Which i assume means that the object in frmInput2 has not been loaded yet. How can i load frmInput2 before i show it?
Thanks
Nick
frminput2 is probably the implicit global instance of the type frminput2.
If you define a form type in VB6 called MyForm, the platform automatically creates an implicit global variable of the same name MyForm. Whenever you refer to this variable in code, it automatically loads an instance of the form for you.
It's rather as if you had this code.
Public Function MyForm() As MyForm
Static f As MyForm
If f Is Nothing Then
f = New MyForm
End If
Return f
End Function
dim frm1 as new frmInput1
dim frm2 as new frmInput2
At this point, you should be able to communicate between forms without them being displayed. You should not reference forms without explicitly instantiating them.
Create an instance of the form.
Dim f As New frmInput2
Then you can use any properties, methods, or controls on the form.
If f.lblInputMac.Text <> "(no filename)" Then
...
End If

Installation setup problem (Access a checkbox in custom dialog box)

I’m trying to create a installation setup for my VB.net application. I
need to insert a custom action while setup is running. So I add a
Checkbox Dialog box to my setup. And I add a dll to the setup
installation to capture Before Install and After Install events. Those
are works fine. But I cannot access my check box value in those
events. If u guys can give me a hint to continue my work really
appreciates.
Following is the Before Install event I have created. I have set some
messages to verify my event works correctly. While I run the setup
those messages are prompt properly.
Private Sub Installer_BeforeInstall(ByVal sender As Object, _
ByVal e As System.Configuration.Install.InstallEventArgs) Handles MyBase.BeforeInstall
Dim koFaxPath As String = Nothing
MsgBox("Installer_BeforeInstall: Starts1")
Dim contextParameters As StringDictionary
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder
Dim actionDataName As String = String.Empty
Dim arrayActionData() As String
contextParameters = Me.Context.Parameters
For Each actionDataName In Me.Context.Parameters.Keys
arrayActionData = Me.Context.Parameters(actionDataName).ToString.Split("-")
MsgBox(actionDataName.ToString)
MsgBox(arrayActionData(0).ToString)
MsgBox(Me.Context.Parameters.Item(actionDataName.ToString))
Next
Try
Catch ex As Exception
'needs to impliment
End Try
MsgBox("Installer_BeforeInstall: Ends")
End Sub
Thanks in advance.
I have found the answer for that. It may useful for u as well.
Once you have add your dll to the setup project, Go to dll properties.
There is a property called CustomActionData. Fill it as follows
/CheckBoxSequenceGenerator="[CheckBoxName]"
Now you can access this in following code
Context.Parameters("CheckBoxSequenceGenerator")
Please make sure that your check-box property are not assigned to coding.