BC42104 error code how can I fix this error? - visual-studio

Warning BC42104: Variable 'pass' is used before it has been assigned a value. A null reference exception could result at runtime.
This is my code:
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim uname As String = ""
Dim pword As String
Dim username As String = ""
Dim pass As String
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("Please fill the info")
Else
uname = TextBox1.Text
pword = TextBox2.Text
Dim query As String = "Select Password From Register where Username= '" & uname & "';"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Gui\Documents\Database4.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Try
pass = cmd.ExecuteScalar().ToString
Catch ex As Exception
MsgBox("Username does not exit")
End Try
If (pword = pass) Then
MsgBox("Login success")
Reg.Show()
If Reg.Visible Then
Me.Hide()
End If
Else
MsgBox("login Failed")
TextBox1.Clear()
TextBox2.Clear()
End If
End If
End Sub

As the error is saying, you are not initializing the variable pass and under some condition, you may end up with using it.
To be exact, if the control lands in the 'catch' block, the variable 'pass' will not have any values, which means it is possible that If (pword = pass) statement is reached without this variable having any values.
To fix the error, just assign a null value or empty string to the variable at the point of initialization. For example use this statement:
Dim pass As String = "";

Related

VB6 Error :Object variable or with block variable not set

I get this
"Object variable or with block variable not set" inside 'dblog' sub function
in this line , I guess its with 'm_Session'
If iType >= Int(m_Session("_SysParam_LogLevel")) Then
My Code
Private m_Session As ASPTypeLibrary.Session
Public Function InitializeSite(Optional intCheckMode As Integer = 0) As Boolean
InitializeSite = False
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
DBLog "Initializing started - "
Set cmd = New ADODB.Command
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = DBConnection
end with
end function
Public Sub DBLog(ByVal sTxt As String, Optional ByVal iType As Integer = 0, Optional ByVal sCategory As String = "DEBUG")
'On Error Resume Next
Dim cmd As ADODB.Command
If iType >= Int(m_Session("_SysParam_LogLevel")) Then
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = DBConnection
End With
End If
Set cmd = Nothing
On Error GoTo 0
End Sub
Property Get DBConnection() As String
DBConnection = IIf(Not IsNull(m_Session("_SysParam_DBConnection")), m_Session("_SysParam_DBConnection"), "")
End Property
Please help me moving forward.
Function InitializeSite should also initialize variable m_Session before calling DBLog sub, or you could modify code in DBLog sub adding
If m_Session Is Nothing Then Exit Sub
at the beginning.
Or you could initialize variable m_Session adding this sub to your class
Public Sub OnStartPage(SC As ASPTypeLibrary.ScriptingContext)
Set m_Session = SC.Session
End Sub
Take a look at How to share ASP classic session variable from ASP to VB6?
Try to replace your first line of code with:
Private m_Session As new ASPTypeLibrary.Session

To convert string to double in UFT/QTP

I am trying to convert string to double in UFT but It shows the output without decimal point. below is the code for reference.
vStr = "1000000.589765"
msgbox Typename(vStr)
strV1=CDBL(formatNumber(vStr,4))
msgbox Typename(strV1)
print strV1
Output: 1000000589765
Note that without formatNumber, its not working.
Yet another implementation using DotNetFactory. Just an another thought. I am not denying to use CDbl. But worth to give a shot.
'Test Code
Dim strConvertedCode
strConvertedCode = ConvertDataType("1000000.589765","Double")
If strConvertedCode <> null Then
Msgbox strConvertedCode
End If
Public Function ConvertDataType(ByVal SourceData,ByVal ConversionDataType)
'Initialization of variables
Dim objDotNetFactory
Dim strConvertedData : strConvertedData = null
Dim strSystemNamespace
'Determine the destination data type
Select Case UCase(ConversionDataType)
Case "DOUBLE"
strSystemNamespace = "System.Double"
'Implement further for your data types
'Reference https://msdn.microsoft.com/en-us/library/ms228360(v=vs.90).aspx
Case Default
Set objDotNetFactory = DotNetFactory.CreateInstance("System.Int32")
End Select
Set objDotNetFactory = DotNetFactory.CreateInstance(strSystemNamespace)
'Check the dot net factory instance is successful
If Not IsObject(objDotNetFactory) Then
Reporter.ReportEvent micWarning,"Data type convertor","Conversion from String to " & ConversionDataType & " failed, Since DotNetFactory instance was not created."
ConvertDataType = strConvertedData
Exit Function
End If
strConvertedData = objDotNetFactory.Parse(SourceData)
ConvertDataType = strConvertedData
End Function

How to use DataReader from Oledb and get results in Richtextbox

Dim srch As String
srch = ccode.Text
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + IO.Directory.GetCurrentDirectory + "\ptdr.accdb"
cmd.Connection = conn
conn.Open()
Dim dsrch As New OleDbCommand("SELECT pname, page, vdate, psex, summer, bldp, blds, photh, diag, rl, trtmnt, nvdate FROM ptnt_data WHERE pcode = " & srch & "", conn)
Dim rdr As OleDbDataReader = dsrch.ExecuteReader()
Dim dg As String = ""
'diagnosis'
dg = rdr.GetString(8).ToString()
If String.IsNullOrEmpty(dg) Then
diag1.Text = ""
ElseIf String.IsNullOrWhiteSpace(dg) Then
diag1.Text = ""
Else
diag1.Text = dg
End If
It works fine but when I search for a null it gives an error.
It says that I've an error at the line of
dg = rdr.GetString(8).Tostring()
any suggests?
rdr.GetString(8).ToString()
if rdr.GetString(8) is null this is a classic null reference exception
rdr.GetString(8) IS a string so just remove the .ToString()
As per my comment below you can only run GetString if the DB has an underlying type of string for this data, what is the datatype of column diag?
(ie run rdr.GetFieldType(8) in the debugger and provide the type name)
As you have confirmed this is a string type and the issue is just with null handling (sorry i didn;t spot that from your question) you need:
If rdr.IsDBNull(8) Then diag1.Text = "" Else diag1.Text = rdr.GetString(8) EndIf
Which should replace everything from Dim dg... down

Check a recordset for an empty field

I'm trying to pre-view if a field of the recordset is empty/null or not.
If IsNull(rs.Fields("fieldname")) = True Then ...
If IsNull(rs.Fields("fieldname")).Value = True Then ...
if IsNull(rs.Fields("fieldName").Value) Then...
All of these methods fires up an error... Why? How may I check if the recordset is null before I assign it's value to a variable.
If I understand correctly, you want to ensure that a field exists in the recordset. If that is correct, you need to either iterate the fields looking for the field you are searching for, or try to directly access the field and trap any errors. Here is a method that iterates the field collection and returns True if the field exists.
Public Function FieldExists(ByVal rsRecSet As ADODB.Recordset, ByVal FieldName As String) As Boolean
Dim fld As ADODB.Field
Dim Rtn As Boolean
If Not rsRecSet Is Nothing Then
For Each fld In rsRecSet.Fields
If StrComp(fld.Name, FieldName, vbTextCompare) = 0 Then
Rtn = True
Exit For
End If
Next fld
End If
FieldExists = Rtn
End Function
Here is a way to print out the columns of a table.
Dim cat
Set cat = CreateObject("ADOX.Catalog")
Set cat.ActiveConnection = db 'db is the adodb.connection object
Dim tbl
Dim clm
For Each tbl In cat.Tables
For Each clm In tbl.Columns
Debug.Print (clm) ' Prints the column name from the table
Next
Next
Try using IsDbNull() instead. DbNull is different than Null.
Edit, just loop through the field names and have a boolean if it found it, otherwise use a try catch structure.
For Each field in rs.Fields
if field.Name = "someFieldName" then
foundField = true
exit for
else
foundField = false
end if
next
I'm using AtValue and AtField helpers like this
Option Explicit
Private Sub Form_Load()
Dim rs As Recordset
If IsEmpty(AtValue(rs, "Test")) Then
Debug.Print "Field is Empty or non-existant"
End If
If LenB(C2Str(AtValue(rs, "Test"))) = 0 Then
Debug.Print "Field is Null, Empty, empty string or non-existant"
End If
'-- this will never fail, even if field does not exist
AtField(rs, "Test").Value = 42
End Sub
Public Function AtValue(rs As Recordset, Field As String) As Variant
On Error GoTo QH
AtValue = rs.Fields(Field).Value
Exit Function
QH:
' Debug.Print "Field not found: " & Field
End Function
Public Function AtField(rs As Recordset, Field As String) As ADODB.Field
Static rsDummy As Recordset
On Error GoTo QH
Set AtField = rs.Fields(Field)
Exit Function
QH:
' Debug.Print "Field not found: " & Field
Set rsDummy = New Recordset
rsDummy.Fields.Append Field, adVariant
rsDummy.Open
rsDummy.AddNew
Set AtField = rsDummy.Fields(Field)
End Function
Public Function C2Str(Value As Variant) As String
On Error GoTo QH
C2Str = CStr(Value)
QH:
End Function
My type-casting helpers are actually using VariatChangeType API (so to work with Break on all errors setting) like this
Public Function C_Str(Value As Variant) As String
Dim vDest As Variant
If VarType(Value) = vbString Then
C_Str = Value
ElseIf VariantChangeType(vDest, Value, VARIANT_ALPHABOOL, VT_BSTR) = 0 Then
C_Str = vDest
End If
End Function
rs.EOF flag will tell whether RecordSet is Empty or not
If Not rs.EOF Then
..Your desired logic..
End If

Getting the cursor location in Visual Studio to clipboard

Often when describing an issue in code, I need to reference it by line/column/function.
Is there a macro/add-in for Visual Studio that copies that information for me?
It would be perfect if it could copy to clipboard: File, Line, column, function name
But I'd take any combination :).
Thanks!
I ended up doing a macro. Unfortunately I was unable to access the clipboard from the macro so I had to use NirCmd for that part. Other than that, it works great!
Public Sub CopyLocation()
Dim fileName = DTE.ActiveDocument.Name
Dim line = ""
Dim column = ""
Dim functionName = ""
Dim className = ""
Dim textDocument = TryCast(DTE.ActiveDocument.Object, TextDocument)
If textDocument IsNot Nothing Then
Dim activePoint = textDocument.Selection.ActivePoint
column = activePoint.DisplayColumn
line = activePoint.Line
Dim codeElement As CodeElement
codeElement = activePoint.CodeElement(vsCMElement.vsCMElementFunction)
If codeElement IsNot Nothing Then
functionName = codeElement.Name
End If
codeElement = activePoint.CodeElement(vsCMElement.vsCMElementClass)
If codeElement IsNot Nothing Then
className = codeElement.Name
End If
End If
Dim output As String = String.Format("File: {0} ", fileName)
If (String.IsNullOrEmpty(line) = False) Then output = output & String.Format("Line: {0} ", line)
If (String.IsNullOrEmpty(column) = False) Then output = output & String.Format("Column: {0} ", column)
If (String.IsNullOrEmpty(className) = False) Then output = output & String.Format("at {0}", className)
If (String.IsNullOrEmpty(functionName) = False) Then output = output & String.Format(".{0}", functionName)
Dim process As System.Diagnostics.Process
process.Start("c:\NoInstall files\nircmd.exe", String.Format("clipboard set ""{0}""", output))
End Sub

Resources