I'm new to working with background workers, and I'm trying to run the following code. But I recieve a run-time error on the m._Value_CreatedDate = m._MyCMD.ExecuteScalar() line. The error is:
Additional information: ExecuteScalar: CommandText property has not
been initialized
Try
Dim m As MyParameters = DirectCast(e.Argument, MyParameters)
m._Con.Open()
m._QueryStr = "SELECT TOP 1 CONVERT(varchar(10),aCreated,103) FROM Account WHERE aMember_ID = " & m._Selected_MemberID & ""
m._MyCMD.CommandType = CommandType.Text
m._Value_CreatedDate = m._MyCMD.ExecuteScalar()
Catch ex As Exception
m._Value_CreatedDate = "N/A"
End Try
Here's the Parameter's I'm using:
Class MyParameters
Friend _QueryStr As String
Friend _Value_CreatedDate As Object
Friend _AccountID As Object
Friend _Selected_MemberID As String = Committee_Database.GridView1.GetFocusedRowCellValue("Unique ID").ToString
Friend _Con As New SqlConnection('Connection string ommitted)
Friend _MyCMD As New SqlCommand(_QueryStr, _Con)
End Class
Please forgive me if I'm doing something extremely wrong, I'm self taught and experimenting with the backgroundworker. It's worth noting that _QueryStr will change multiple times as the background worker runs multiple queries against the same database and (as I understand it) stores each of the returned values from the queries into variables - _Value_CreatedDate is the variable I am using in this code. I've included an example of how I'm recycling the _QueryStr variable below and storing the returned value into a diffent Variable each time.
Try
m._QueryStr = "SELECT TOP 1 aAccount_ID FROM Account WHERE aUser_Name='" & _Selected_AccountID & "'"
m._MyCMD.CommandType = CommandType.Text
m._AccountID = m._MyCMD.ExecuteScalar()
Catch ex As Exception
End Try
Am I doing something wrong?
In the implementation of your class MyParameters you initialize the SqlCommand directly with the declaration using the value of the variable _QueryStr. At that point in time the variable _QueryStr is not yet initialized, so it is an empty string.
After the initialization of an instance of MyParameters, you change the value of _QueryStr (many times according to you) but these changes are not automatically passed to the CommandText of your SqlCommand. It still contains the empty initial value.
You could fix this problem building appropriate getter and setter for a new QueryStr property. When someone tries to set the property the code below change the value of the internal field _QueryStr (now private) and reinitializes the CommandText property of your SqlCommand.
Class MyParameters
Private _QueryStr As String
Public Property QueryStr() As String
Get
Return _QueryStr
End Get
Set(ByVal value As String)
_QueryStr = value
_MyCMD.CommandText = _QueryStr
End Set
End Property
..... other properties
Friend _MyCMD As New SqlCommand(_QueryStr, _Con)
End Class
Now when you write
Try
m.QueryStr = "SELECT ...."
....
the new command text is correctly assigned to your command.
As a side note: I suggest to use plain ADO.NET objects (or learn how to use an ORM tool). Do not try to encapsulate them in custom classes unless you have a very deep understanding on how these ADO.NET objects works. You gain nothing and expose your code to many problems. For example your code is very easy to exploit with Sql Injection because the MyParameters class has no provision to use a parameterized query. Your code has no method to close and dispose the SqlConnection embedded in your class thus leading to resource leaks.
Related
I'm having trouble with selecting only part of a collection and passing it by reference.
So I have a custom class EntityCollection which is , who guessed, a collection of entities. I have to send these entities over HTTPSOAP to a webservice.
Sadly my collection is really big, let's say 10000000 entities, which throws me an HTTP error telling me that my request contains too much data.
The method I am sending it to takes a Reference of the collection so it can further complete the missing information that is autogenerated upon creation of an entity.
My initial solution:
For i As Integer = 0 To ecCreate.Count - 1 Step batchsize
Dim batch As EntityCollection = ecCreate.ToList().GetRange(i, Math.Min(batchsize, ecCreate.Count - i)).ToEntityCollection()
Q.Log.Write(SysEnums.LogLevelEnum.LogInformation, "SYNC KLA", "Creating " & String.Join(", ", batch.Select(Of String)(Function(e) e("nr_inca")).ToArray()))
Client.CreateMultiple(batch)
Next
ecCreate being an EntityCollection.
What I forgot was that using ToList() and ToEntityCollection() (which I wrote) it creates a new instance...
At least ToEntityCollection() does, idk about LINQ's ToList()...
<Extension()>
Public Function ToEntityCollection(ByVal source As IEnumerable(Of Entity)) As EntityCollection
Dim ec As New EntityCollection()
'ec.EntityTypeName = source.FirstOrDefault.EntityTypeName
For Each Entity In source
ec.Add(Entity)
Next
Return ec
End Function
Now, I don't imagine my problem would be solved if I change ByVal to ByRef in ToEntityCollection(), does it?
So how would I actually pass just a part of the collection byref to that function?
Thanks
EDIT after comments:
#Tim Schmelter it is for a nightly sync operation, having multiple selects on the database is more time intensive then storing the full dataset.
#Craig Are you saying that if i just leave it as an IEnumerable it will actually work? After all i call ToArray() in the createmultiple batch anyway so that wouldn't be too much of a problem to leave out...
#NetMage you're right i forgot to put in a key part of the code, here it is:
Public Class EntityCollection
Implements IList(Of Entity)
'...
Public Sub Add(item As Entity) Implements ICollection(Of Entity).Add
If IsNothing(EntityTypeName) Then
EntityTypeName = item.EntityTypeName
End If
If EntityTypeName IsNot Nothing AndAlso item.EntityTypeName IsNot Nothing AndAlso item.EntityTypeName <> EntityTypeName Then
Throw New Exception("EntityCollection can only be of one type!")
End If
Me.intList.Add(item)
End Sub
I Think that also explains the List thing... (BTW vb or c# don't matter i can do both :p)
BUT: You got me thinking properly:
Public Sub CreateMultiple(ByRef EntityCollection As EntityCollection)
'... do stuff to EC
Try
Dim ar = EntityCollection.ToArray()
Binding.CreateMultiple(ar) 'is also byref(webservice code)
EntityCollection.Collection = ar 'reset property, see below
Catch ex As SoapException
Raise(GetCurrentMethod(), ex)
End Try
End Sub
And the evil part( at least i think it is) :
Friend Property Collection As Object
Get
Return Me.intList
End Get
Set(value As Object)
Me.Clear()
For Each e As Object In value
Me.Add(New Entity(e))
Next
End Set
End Property
Now, i would still think this would work, since in my test if i don't use Linq or ToEntityCollection the byref stuff works perfectly fine. It is just when i do the batch thing, then it doesn't... I was guessing it could maybe have to do with me storing it in a local variable?
Thanks already for your time!
Anton
The problem was that i was replacing the references of Entity in my local batch, instead of in my big collection... I solved it by replacing the part of the collection that i sent as a batch with the batch itself, since ToList() and ToEntityCollection both create a new object with the same reference values...
Thanks for putting me in the correct direction guys!
I am trying to write some code in excel VBA using the Object Oriented Concept. Therefore I wanted to initialize my objects with constructors, like we usually do in Java. However I discovered that the default Class_Initialize() Sub that is offered in VBA does not take arguments. After searching a bit, I found that the answer for this Question proposed a pretty good alternative.
Here is a sample of my Factory Module (I Named it Creator):
Public Function CreateTool(ToolID As Integer) As cTool
Set CreateTool = New cTool
CreateTool.InitiateProperties (ToolID) '<= runtime error 91 here
End Function
The class cTool:
Private pToolID As Integer
Private pAttributes As ADODB.Recordset
Private pCnn As ADODB.Connection
Public Sub InitiateProperties(ToolID As Integer)
Dim sSQL As String
Set pCnn = connectToDB() 'A function that returns a connection to the main DB
pToolID = ToolID
sSQL = "SELECT Tool_ID, Status, Type, Tool_Number " _
& "FROM Tool WHERE Tool_ID = " & pToolID
pAttributes.Open sSQL, pCnn, adOpenKeyset, adLockOptimistic, adCmdText
End Sub
This is how I call the constructor:
Dim tool As cTool
Set tool = Creator.CreateTool(id)
My issue is that when I run the code, I get the following error:
Run-Time error '91' : Object Variable or With Block Variable not Set
The debug highlights the CreateTool.InitiateProperties (ToolID) line of my CreateTool Function.
I know that this usually happens when someone is setting a value to an object without using the keyword Set but it does not seem to be my case.
Any help, advice to resolve this issue would be greatly appreciated!
Thanks.
Might not be the cause of your error, but this:
Public Function CreateTool(ToolID As Integer) As cTool
Set CreateTool = New cTool
CreateTool.InitiateProperties (ToolID) '<= runtime error 91 here
End Function
Is problematic for a number of reasons. Consider:
Public Function CreateTool(ByVal ToolID As Integer) As cTool
Dim result As cTool
Set result = New cTool
result.InitiateProperties ToolID
Set CreateTool = result
End Function
Now, looking at the rest of your code, you're doing the VBA equivalent of doing work in the constructor, i.e. accessing database and other side-effects to constructing your object.
As #Jules correctly identified, you're accessing the unitialized object pAttributes inside InitiateProperties - that's very likely the cause of your problem.
I'd strongly recommend another approach - if you come from Java you know doing work inside a constructor is bad design... the same applies to VBA.
Get your code working, and post it all up on Code Review Stack Exchange for a full peer review.
I have a form with information pulled from SQL that can be edited, once the form is closed I want to either write any changes back to the database or discard them. I don't want to store two sets of the data for comparison and I don't want to re-query SQL for the same.
I came up with the idea of creating a List of SQLCommand items and processing them if changes are to be saved however I get the following error when trying to add a SQLCommand to the list:
An unhandled exception of type 'System.NullReferenceException' occurred in Application1.exe
Additional information: Object reference not set to an instance of an object.
I've probably missed something really simple but I can't see what myself.
My code is below:
Public Class frm1
Public Property ContID As String
Dim PendingSQLChanges As List(Of SqlCommand)
Private Sub btnAddTel_Click(sender As Object, e As EventArgs) Handles btnAddTel.Click
Using x As New SqlCommand("INSERT into ContactTels (Tel, CoID) Values (#NewValue, #ContID) ;--", cnn)
x.Parameters.Add("#NewValue", SqlDbType.NVarChar, 100).Value = strNewvalue
x.Parameters.Add("#ContID", SqlDbType.Int).Value = ContID
PendingSQLChanges.Add(x) <This is the line I get the error on.
btnSave.Enabled = True
End Using
End Sub
As you can see I am adding parameters to the SQLCommand otherwise I would have used a List of strings containing the SQLCommand.Commandtext and used that later.
If I can get the list working the code I will use to process the saved commands is:
For x = 0 To PendingSQLChanges.Count - 1
PendingSQLChanges(x).ExecuteNonQuery()
Next
Is that correct as well?
Try using New in your List(of SqlCommand) declaration:
Dim PendingSQLChanges As New List(Of SqlCommand)
It was not instantiated thus the Null Reference.
I'm triying to build a language dictionary in VB NET in order to be able to have several languages in the application.
This dictionary has a init method that loads from database the entire dictionary and stores it in memory.
In the rest of the classes of the project, I added the reference and I can use directly the object without create a new instance because their methods are shared.
My question is how i have to load the dictionary content in order that the rest of classes only accessing to Language.GetWord method obtains the properly record of the collection, same way as My.Settings class.
When My.Settings is used from any class the values are loaded. I'm looking for the same effect.
This is the code of the class:
Public Class LanguageProvider
Private Shared CurrentLanguage As Collection
Public Shared ReadOnly Property GetWord(ByVal Label As String)
Get
Try
Return CurrentLanguage.Item(Label)
Catch ex As Exception
Return Label
End Try
End Get
End Property
Public Shared Sub LoadLanguage(ByVal CultureId As Integer)
Dim SQLController As New SqlDataAccessController
SQLController.SQLSentence = "SELECT DNF_CULTURE_LANGUAGE_LABELS.LABEL, DNF_CULTURE_LANGUAGE_LABELS.VALUE FROM DNF_CULTURE_LANGUAGE_LABELS WHERE DNF_CULTURE_LANGUAGE_LABELS.CULTUREID = " & CultureId & " ORDER BY LABEL;"
SQLController.OpenConnection()
Dim dr As SqlClient.SqlDataReader
dr = SQLController.GetData()
CurrentLanguage = New Collection
While dr.Read()
CurrentLanguage.Add(dr.Item("Value"), dr.Item("Label"))
End While
dr.Close()
SQLController.CloseConnection()
End Sub
End Class
Function LoadLanguage must be called when the application loads, in order to access once to database.
After that property GetWord must access to the collection with the words and return the result. The problem is that the instances are not the same and the dictionary is not loaded when a class uses it.
Thanks.
Something along the lines of
Public Shared ReadOnly Property GetWord(ByVal Label As String)
Get
Try
If CurrentLanguage Is Nothing then
LoadLanguage(theDefaultCultureIdYouWant)
' Now CurrentLanguage is not Nothing any more,
' so LoadLanguage won't be called again
end if
Return CurrentLanguage.Item(Label)
Catch ex As Exception
Return Label
End Try
End Get
End Property
Of course, you have to provide a value for theDefaultCultureIdYouWant, depends on what you want to happen if the user just calls GetWord without explicitly mentioning a specific culture.
Is this the right way of declaration dbreaders when mulitple users access the same page?
public dbReader as system.Data.IDataReader at class level or
Dim dbReader as System.Data.IDataReader in each function inside a class.
What would be the best practice to make the dbReader thread safe in VB.Net?
Does declaring them as static makes it thread safe?
Thanks in Advance,
If you'd like each thread to modify the variable without 'fear' another thread will change it somewhere along the line, it is best you adorn the variable with the ThreadStatic attribute.
The ThreadStatic attribute creates a different instance of the variable for each thread that's created so you're confident there won't be any race conditions.
Example (from MSDN)
Imports System
<ThreadStatic> Shared value As Integer
I would recommend you using reentrant functions when possible which are thread safe by definition instead of using class fields:
Function GetIds() As IEnumerable(Of Integer)
Dim result = New List(Of Integer)()
Using conn = New SqlConnection("SomeConnectionString")
Using cmd = conn.CreateCommand()
conn.Open()
cmd.CommandText = "SELECT id FROM foo"
Using reader = cmd.ExecuteReader()
While reader.Read()
result.Add(reader.GetInt32(0))
End While
End Using
End Using
End Using
Return result
End Function
If you are Diming the variable in a function, no other thread can access that variable making it thread-safe by definition.
However, if you are declaring it at a class level, you might want to use SyncLock which will prevent other threads from accessing it if it is currently being used by an other one.
Example:
Public Sub AccessVariable()
SyncLock Me.dbReader
'Work With dbReader
End SyncLock
End Sub