Weird data type mismatch error VBA [duplicate] - arrays

I need to pass a String array to set a class property using its setter method. Array was declared in Module and it's perfectly set the values using Redim Preserve. When calling the Class setter method it gives error. If I continued to without setting array data type it worked. But I need to declare the data type as String.
I received a compile error "Type mismatch: array or user defined type expected."
Module
Dim sPageDetails() As String
' set some values to array
' Declare class instance
dim x as new X
with x
.SetPageNumberDetails(sPageDetails) ' assume SetPageNumberDetails is the setter method in class X
end with
End module
'class module start X
Private pageDetails() as String
' Setter for pageDetails array
Public Sub SetPageNumberDetails(ByRef sPageDetails() As String)
pageDetails= sPageDetails
End Sub
' Getter for pageDetails array
Public Function GetPageNumberDetails() As String()
GetPageNumberDetails= pageDetails
End Function

.SetPageNumberDetails(sPageDetails)
Remove the parentheses:
.SetPageNumberDetails sPageDetails

Remain the parentheses and add explicit 'Call':
Call .SetPageNumberDetails(sPageDetails)
It took 5-10 CPU ticks (~30 nsec), but code wil be more readable, editable, auditable etc. And it is simply comme il faut...
.

Related

VBA6 type mismatch on parameter array

The following (highly simplified) code produces a type mismatch: array expected on the call to evalexp for parameter xabc. Why?
Public nfa() As String
Public rules() As String
Sub BuildNFA(xabc () As String)
Dim x
ReDim xnfa(5, 10)
x = evalexp(0, xabc)
End Sub
Function evalexp(rnb As Integer, xyz() As String) As String
xyz(rnb, replnode).name = "replnode"
evalregexp = ""
End Function
Xyz is declared as () but used as(,). I.e you declare a 1d array then try to use it as a 2d array. Additionally xyz is declared as string,but you try to access a name property which will not exist. Please install the Rubberduck VBA addin and learn to use its code inspections.

How to filter String Array in VB.Net?

What is VB.Net code to filter a String Array ?
I use following code
Imports System.Reflection
Dim ass As Assembly = Assembly.GetExecutingAssembly()
Dim resourceName() As String = ass.GetManifestResourceNames()
that return a String array
How can I filter resourceName() variable ?
I tried following lines of code
Dim sNameList() As String
= resourceName.FindAll(Function(x As String) x.EndsWith("JavaScript.js"))
but compiler return following error
BC36625: Lambda expression cannot be converted to 'T()' because 'T()' is not a delegate type
How can I correct this error ?
Is there another solution to solve my problem ?
Dim sNameList = resourceName.Where(Function(s) s.EndsWith("JavaScript.js"))
In that case, sNameList is an IEnumerable(Of String), which is all you need if you intend to use a For Each loop over it. If you genuinely need an array:
Dim sNameList = resourceName.Where(Function(s) s.EndsWith("JavaScript.js")).ToArray()
The reason that your existing code didn't work is that Array.FindAll is Shared and so you call it on the Array class, not an array instance:
Dim sNameList = Array.FindAll(resourceName, Function(s) s.EndsWith("JavaScript.js"))

Eiffel: compilation error `Source of assignment is not compatible with target`

With complete void check set in compiler I've got a Variable is not properly set compilation error on following case which for me is right (in my mind). It says that the source of assignment is not compatible with target. What am I missing here??? (DB_SERVICE.load_from_primary_key...)
Class DB_SERVICE
deferred class
DB_SERVICE [G -> DB_ENTITY create make_from_db_result end]
inherit
ACTION
redefine
start,
execute
end
LOGGABLE
rename
make as make_from_loggable
end
feature -- Creation
make (a_db_connection: attached DB_CONNECTION)
require
valid_db_connection: a_db_connection.is_connected
do
make_from_loggable
db_connection := a_db_connection
create last_items.make (100)
create last_column_names.make_empty
ensure
db_connection_setted: a_db_connection = db_connection and db_connection.is_connected
end
feature -- Access
item: detachable G
db_connection: DB_CONNECTION
last_items: HASH_TABLE[like item, INTEGER] -- content of last resultset
last_column_names: ARRAY[STRING] -- Column names of last resultset
feature -- status_report
load_from_primary_key (primary_key: INTEGER)
-- Loads given item into item otherwise item will be Void
require
attached db_connection.base_selection
local
l_db_result: DB_RESULT
do
if attached db_connection.base_selection as bs then
bs.query ("SELECT * FROM " + ({attached like item}).out + " WHERE " + {attached like item}.Primary_key_db_column_name + "=" + primary_key.out)
if bs.is_ok then
bs.load_result
create item.make_from_db_result(last_column_names, bs.cursor)
else
item := Void --HERE is the compiler complaining!
logger.write_critical ("Error while retreiving " + ({like item}).out + " from DB")
end
else
item := Void
logger.write_error ("base_selection is void")
end
end
end -- class
Class COMPANY_SERVICE
class
COMPANY_SERVICE
inherit
DB_SERVICE[COMPANY]
redefine
make
end
...
Class COMPANY
class
COMPANY
inherit
DB_ENTITY
rename
primary_key as id,
set_primary_key as set_id,
Primary_key_db_column_name as Id_db_column_name
redefine
make,
make_from_db_result,
out
end
create
make,
make_from_db_result
....
The type declaration detachable G indicates that if the corresponding actual generic is a reference type, the variable of that type could be detachable. In that case it would be OK to assign Void to such a variable. However, it's also possible that the actual generic is an expanded type. Prefixing an expanded type with detachable has no effect, the type remains the same and the variable cannot be assigned Void.
As an example, let's consider a simpler case, when there is no formal generic constraint for the parameter G. An actual generic could be STRING, and the variable item has a type detachable STRING. In this case, it's OK to assign Void to item.
Now, if the actual generic is INTEGER, the variable has a type detachable INTEGER that is equivalent to INTEGER. Assigning Void to a variable of this type makes no sense and is not permitted by the language rules.
The variable item still can be set to Void if the actual generic parameter is a reference type. For that, a local variable with the same type can be declared and its value can be assigned to item:
local
default_item: like item
do
item := default_item

why is the index of the one-dimensional array changing this way?

I'm a beginner and I'm encountering a problem with an index of a one-dimensional array of strings (m_nameList in the code) that I'm struggling to understand. I have one method (in a class of a Windows Form Application that is not the MainForm) that returns FALSE if a string of the array at a certain index is empty, and viceversa. It looks like this:
Public Function IsReserved(index As Integer) As Boolean
Dim reserved As Boolean = False
If (Not String.IsNullOrEmpty(m_nameList(index))) Then
reserved = True
Else
reserved = False
End If
Return reserved
End Function
I have also a method on the MainForm that calls for it, and if the first method returns true then the second one displays a dialog box, otherwise it doesn't (lstResults is a listbox that has for items the strings of the array):
Private Function CheckIfSeatIsAlreadyReserved() As Boolean
Dim reserved As Boolean = m_seatMngr.IsReserved(lstResults.SelectedIndex)
If (reserved) Then
Dim msgBox As Integer = MessageBox.Show("The seat is already reserved. Would you like to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If (msgBox = DialogResult.Yes) Then
Return True
Else
Return False
End If
Else
Return True
End If
End Function
The problem I find is: if as in the code of the first method above I don't initialize index to any value, the second method will work perfectly, but I'll get a runtime error if I don't select any item on the listBox (and therefore index = -1). On the other hand, if I initialize index to 0 or to m_nameList.Length, then the program won't have any problems if I don't select any item on the ListBox and it will nicely display a warning message I wrote for that case, BUT the second method will behave in a weird way: it will find ALL the strings of the array full even if I only "write" the first one, or it will find ALL the strings empty if I "write" any string that it's not the first one (by writing I mean that I call for a method that puts my input as the text of the string selected). Any idea on why this happens and how I can fix it? Thank you so much.
I will get to the answer below, follow the logic, lets look at your first method. You can refactor it to
Public Function IsReserved(index As Integer) As Boolean
Return Not String.IsNullOrEmpty(m_nameList(index))
End Function
Everything else is called "noise". But as Fabio pointed, what if index is bad? Lets add useful code
Public Function IsReserved(index As Integer) As Boolean
If index < 0 OrElse index > m_nameList.Length - 1 Then
Throw New ArgumentOutOfRangeException(". . . . .")
End If
Return Not String.IsNullOrEmpty(m_nameList(index))
End Function
If you get this exception, your program has a bug - and you know to fix the consumer of this function.
And now lets get to your message
second method will behave in a weird way: it will find ALL the strings of the array full even if I only "write" the first one, or it will find ALL the strings empty if I "write" any string
Most likely reason why it happens - simply because you create condition when you send same value over and over again. Therefore result is same. And this is most likely a bug
If (reserved) Then
. . . . . .
Else
Return True ' <---- BUG ALLERT
End If
And two more things, your second method can shrink down to 1 line too.
Private Function CheckIfSeatIsAlreadyReserved() As Boolean
Return m_seatMngr.IsReserved(lstResults.SelectedIndex) AndAlso _
DialogResult.Yes = MessageBox.Show("The seat is already reserved. Would you like to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
End Function
And, if you do some sort of reservation, array is not really good idea. How about Dictionary(Of String, Boolean)? Your theater or airplane has bunch of seats and you pre-load your dictionary with those
d.Add("1A", False)
d.Add("1B", False)
d.Add("1C", False)
d.Add("1D", False)
d.Add("1E", False)
d.Add("1F", False)
This is your whole airplane row. Now you can do much more with it

Remove duplicate items from processes array using VB .net

I have to code to get all accessible process, but I need to remove duplicated items on this array and show only one time each process.
How is the best method to do this, because I think processes array is not like a normal array.
My code:
For Each p As Process In Process.GetProcesses
Try
'MsgBox(p.ProcessName + " " + p.StartTime.ToString)
Catch ex As Exception
'Do nothing
End Try
Next
Thanks in advance
The Process.GetProcesses() method returns an array. You can use the Distinct method, providing an IEqualityComparer to it.
An example would be as comparer:
Public Class ProcessComparer
Implements IEqualityComparer(Of Process)
Public Function Equals1(p1 As Process, p2 As Process) As Boolean Implements IEqualityComparer(Of Process).Equals
' Check whether the compared objects reference the same data.
If p1 Is p2 Then Return True
'Check whether any of the compared objects is null.
If p1 Is Nothing OrElse p2 Is Nothing Then Return False
' Check whether the Process' names are equal.
Return (p1.ProcessName = p2.ProcessName)
End Function
Public Function GetHashCode1(process As Process) As Integer Implements IEqualityComparer(Of Process).GetHashCode
' Check whether the object is null.
If process Is Nothing Then Return 0
' Get hash code for the Name field if it is not null.
Return process.ProcessName.GetHashCode()
End Function
End Class
And you can use it like this:
Sub Main()
Dim processes As Process() = Process.GetProcesses()
Console.WriteLine(String.Format("Count before Distinct = {0}", processes.Length))
' Should contain less items
Dim disProcesses As Process() = processes.Distinct(New ProcessComparer()).ToArray()
Console.WriteLine(String.Format("Count after Distinct = {0}", disProcesses.Length))
Console.ReadLine()
End Sub
You probably have to refine the Comparer to your specifications and for the situation you are going to use it.

Resources