how to return a object in a function that takes arguments visual basic 6 - vb6

Hi im trying to write a function that returns an object but it gives me an arguments not optional error, this is my code
Public Function searchVehicle(c As String, v As Variant) As Collection
Dim qur As String
qur = "select * from [vehicle] where ( " & c & " like '%" & v & "%')"
Set mobjRst = conn.execQuery(qur)
Dim tmpV As Vehicle
Dim res As Collection
With mobjRst
Do Until .EOF
Set tmpV = New Vehicle
Call tmpV.popVehicle(!ID, !make, !model, !purchaseyear, !totalmilage, !milageafterservice, !servicemilage, !description)
res.Add (tmpV)
.MoveNext
Loop
End With
searchVehicle = res
End Function

My first thought is that since it's an object reference, you need to use Set to set the return value.
Set searchVehicle = res
It may be more helpful to know what line you're seeing the problem on.
As a side note, you may also want to take a look at when you need to use Call and when you don't: https://blogs.msdn.microsoft.com/ericlippert/2003/09/15/what-do-you-mean-cannot-use-parentheses/

Your problem lies in the following call to the function -
searchVehicle = res
You have specified searchVehicle to have a string (c) and a variant (v) combining a collection. This will error as you have set no values to either c or v and then call your function -
searchVehicle = (c, v) collection
give us some more information on how you call this etc in your button click event, what is returned...

Related

Need to pass object and operation in a function that executes it

I need to pass an object and its operation in a function so that each time I can call the function only and save me to write same steps for all the objects like validating the object before performing an operation. Similar way to a Register User Function in QTP/UFT.
However, Testcomplete doesn't have this feature (atleast under my knowledge, would be happy to know if there is)
This is my code that I am trying but unable to:
Call OpenPageorTab("Aliases.Admin.wndMain.toolStrip", ".Visible")
Function OpenPageorTab(obj, method)
'if obj.Exists then
execute a = obj&method
delay(1000)
OpenPageorTab = True
'Else
log.Error "Unable to find the object"
OpenPageorTab = False
'End if
using if condition as i was passing object earlier instead of string
It fails at "execute" statement and gives me VbScript runtime error when executing this statement.
my question is two fold -
How do I pass objects and its operation in a function and execute it
Also is it possible to pass an object it self instead of string for ex:
obtoolbar = "Aliases.Admin.wndMain.toolStrip"
Call OpenPageorTab(obtoolbar, ".Visible")
Appreciate any help or direction on this issue
EDIT 1
I am somewhere close to an answer however not accurately. I am able to pass the object as string - Check the code below
Call OpenPageorTab("Aliases.Admin.wndMain.toolStrip", ".Click")
Function OpenPageorTab(obj, method)
' if obj.Exists then
eobj = "" & obj & method
execute (eobj)
delay(1000)
OpenPageorTab = True
' Else
log.Error "Unable to find the object"
OpenPageorTab = False
' End if
End Function
However I still need to pass the object something like
Set oToolStrip = Aliases.Admin.wndMain.toolStrip
Call OpenPageorTab(oToolStrip, ".Click")
This is something that I'm unable to do.
EDIT 2
I have already got the answer to this problem and have posted the solution. That being said, is there any way that Function can be utilized as a method ?
Here an example of how to reference a function and pass parameteers to it, including objects.
Const forReading = 1, forWriting = 2, forAppending = 8, CreateFile = True
Set my_obj = CreateObject("Scripting.FileSystemObject").OpenTextFile("c:\temp\test.txt", forWriting, CreateFile)
Function my_function(my_obj, method, text)
command = "my_obj." & method & " """ & text & """"
ExecuteGlobal command
End Function
'make a reference to our function
Set proc = GetRef("my_function")
'and call it with parameters, the first being the method invoked
Call proc(my_obj, "WriteLine", "testing")
'cleanup'
my_obj.Close
Set my_obj = Nothing
I was able to finally formulate the solution the below function can work as makeshift register function in TestComplete
Sub test
'Set the Object
Set pToolStrip = Aliases.Admin.wndMain.toolStrip.Button("User Admin")
Call GenericOperationFunc(pToolStrip, ".Click", "N")
'if you want to perform an operation which return a value
b = GenericOperationFunc(Aliases.Admin.wndPopup.Child(2), ".Caption", "Y")
End Sub
Public Function GenericOperationFunc(obj, method, Return)
GenericOperationFunc = False
on error resume next
if obj.Exists then
if Ret = "Y" then
eobj = "NewText="&"obj" & method
execute (eobj)
GenericOperationFunc = NewText
Delay(500)
Else
eobj = "obj" & method
execute (eobj)
delay(1000)
GenericOperationFunc = True
End if
Else
log.Error "Unable to find the object"
GenericOperationFunc = False
End if
End Function
'log.error, delay, aliases, ptoolstrip(object) are testcomplete specific

VB.net anonymous type has incorrect property casing from AJAX call

We have noticed that sometimes from the results of an AJAX call to a controller action that the case of the JSON result is incorrect. The returned case will actually change if we rebuild our solution and try the exact same call. In the following case, the key's case has been correct for over a year until now when it has decided to start randomly changing depending on some seemingly random circumstances.
As you can see in the picture above, the key for the JSON result is lowercase "success". However when I view the results in Chrome's console, it is an uppercase "Success". This is causing our JavaScript to fail since it is checking for the lowercase version.
What is causing this? And more importantly, how do we stop this?
vb.net is case-insensitive as opposed to C# which is case-sensitive. This means that the compiler will generate only one class (from the first instance) for each of the following anonymous types:
Dim a = New With {.success = True} 'Compiler generate a class based on this type
Dim b = New With {.Success = True} 'Same type as `a`
Dim c = New With {.sUcCeSs = True} 'Same type as `a`
Debug.WriteLine(a.GetType().Name)
Debug.WriteLine(b.GetType().Name)
Debug.WriteLine(c.GetType().Name)
VB$AnonymousType_0'1
VB$AnonymousType_0'1
VB$AnonymousType_0'1
Here's how the complied code looks like when compiled back to vb.net:
<DebuggerDisplay("success={success}"), CompilerGenerated> _
Friend NotInheritable Class VB$AnonymousType_0(Of T0)
' Methods
<DebuggerNonUserCode> _
Public Sub New(ByVal success As T0)
Me.$success = success
End Sub
<DebuggerNonUserCode> _
Public Overrides Function ToString() As String
Dim builder As New StringBuilder
builder.Append("{ ")
builder.AppendFormat("{0} = {1} ", "success", Me.$success)
builder.Append("}")
Return builder.ToString
End Function
Public Property success As T0
<DebuggerNonUserCode> _
Get
Return Me.$success
End Get
<DebuggerNonUserCode> _
Set(ByVal Value As T0)
Me.$success = Value
End Set
End Property
Private $success As T0
End Class

How to make a function with two strings as arguments

I'm not entirely sure what I'm doing wrong here. I have tested the code by input and output and it functions as desired no pun intended. :'P
I'm just not setting up this function correctly and I believe it's because my arguments happen to be desirably a string. Where if done correctly "CD" will be inserted into the middle of "ABEF". So, how do I go about doing this?
Thanks!
insertstr(ABEF, CD)
Function insertstr(string1, string2)
nostrmsg = "No string"
fullng = len(string1)
half = len(string1)/2
if half>0 then hfstr1 = mid(string1, 1, half)
str2lng = len(string2)
if str2lng>0 then paste = hfstr1+string2
lshalf = mid(string1, half+1, fullng)
if str2lng+half=str2lng+half then insert = paste+lshalf
End Function
Start with the knowledge that a functions returns a value, a tentative specification of what the function should do, and a basic testing skeleton:
Option Explicit
' returns the string build by inserting m(iddle) into f(ull) at half position
Function insertInto(f, m)
insertInto = "?"
End Function
Dim t, r
For Each t In Array( _
Array("ABEF", "CD", "ABCDEF") _
)
r = insertInto(t(0), t(1))
WScript.Echo t(0), t(1), r, CStr(r = t(2))
Next
output:
cscript 26873276.vbs
ABEF CD ? False
Then learn about Left, Mid, Len, and \ (integer division).
At last, re-write insertInto() so that the result starts with
cscript 26873276.vbs
ABEF CD ABCDEF True

Advise on this . My code has some blocker.i am getting the error 'object required'

I am using the functions below.In the first one i have parsed the node of xml and its value using MSXML. similar func fr other xml.i want to use two nodevalues and highlight it.i tried something.but i am getting error in the line highlighted(**) as 'Object Required'.your quick reply will help me more.
Public Sub DisplayNode1(ByRef Nodes1 As MSXML2.IXMLDOMNodeList, _
ByVal Indent1 As Integer)
some lines
RichTextBox2.Text = Space$(Indent) & xNode1.ParentNode.nodeName & _
":" & xNode1.NodeValue
difference
some lines
Public Sub difference()
Dim a As IXMLDOMText
Dim b As IXMLDOMText
a.NodeValue = xNode.innertext 'i get erroe in line
b.NodeValue = xNode1.innertext
If StrComp(a, b) > 0 Then
a = vbRed
b = vbRed
End If
please help me soon.
There is a lot that is potentially wrong with this.
xnode isn't declared anywhere in your code sample
Neither a, b, or xnode are explicitly set anywhere in your code sample
Unless xnode is a form/module/global level variable then it will be out of scope in the Difference procedure
It's not shown but I'm guessing that you don't have Option Explicit set in your code or by default
You'll need to address these points first before you can get anywhere with this code.

Returning Null or Nothing from VBScript function?

I'm trying to write the VBScript equivalent of a function similar to what's below:
object getObject(str)
{
if ( ... )
{
return object_goes_here;
}
return null;
}
My guess would be below, except that I'm not understanding the difference between Nothing and Null. As a caller, I'd rather test if the return value is set by using IsNull() versus X Is Nothing.
Function getObject(str)
If ... Then
Set getObject = object_goes_here
Exit Function
End If
Set getObject = Nothing // <-- or should this be Null?
End Function
The correct way to not return an object is to return Nothing and test for Is Nothing.
VB's Null is a special value of type Variant/Null. There are other special values, such as Variant/Empty or Variant/Error. They all have their use, but it's not the one.
Use the second Function skeleton. Avoid Null when dealing with objects, because of the Set Assignment abomination.
Dim oX : Set oX = getObject(...)
If oX Is Nothing Then
...
Else
nice object to work with here
End If
vs
Dim vX : vX = getObject(...) ' <-- no Set, no object
If IsNull(vX) Then
...
Else
no object to work with here
End If
In your sample code, the object gets always Nothing because that is the last action. This is how it should be:
Function getObject(str)
If ... Then
Set getObject = object_goes_here
Exit Function
End If
Set getObject = Nothing
End Function
or:
Function getObject(str)
Set getObject = Nothing
If ... Then
Set getObject = object_goes_here
End If
End Function
The answer of GSerg is correct: you should use Nothing. Additionally, to see if an object has a null reference, use:
If Not object Is Nothing Then
' do something
End If

Resources