reader with blank or null records - vb.net

Thought the code would catch empty records but it turns out it has not been and no error.
turns out my function always returns FALSE
Try
conn.Open()
Dim strQuery As String = "Select * FROM [UsersDataTbl] " & _
"WHERE [UserName] = """ & UserName & """"
Dim comm As New Data.OleDb.OleDbCommand(strQuery, conn)
Dim reader As Data.OleDb.OleDbDataReader = comm.ExecuteReader()
While reader.Read()
If noNull(reader("StudentID") = "") _
Or noNull(reader("LastName") = "") _
Or noNull(reader("FirstName") = "") _
Or noNull(reader("Affiliation") = "") Then
BlankFields = True
Else
BlankFields = False
End If
End While
conn.Close()
Catch ex As Exception
ADDED:
found my noNull method:
Public Function noNull(ByRef o As Object) As String
If (o Is Nothing) Then
Return ""
End If
Return o.ToString()
End Function

I process recordfield values like this:
Dim iVal As Integer = NoNull(r.Fields("someintegerfield").Value, "0", False)
Public Function NoNull(ByVal uAny As Object, Optional ByVal uFillString As String = "", Optional ByVal uTreatDecimalNullAsNothing As Boolean = False) As String
Dim sRet As String = String.Empty
If Not Convert.IsDBNull(uAny) AndAlso Not uAny Is Nothing Then
Debug.Assert(uAny.GetType.ToString <> "cField") 'checking if the argument is a "cField" helps me to check whether I passes "r.fields("somefield").value to this function, or if I forgot the ".value")
sRet = uAny
Else
sRet = String.Empty
End If
If StrLen(sRet) = 0 Then
If modStrings.StrLen(uFillString) > 0 Then
sRet = uFillString
End If
End If
If uTreatDecimalNullAsNothing Then
If sRet = "0" Then
sRet = uFillString
End If
End If
Return sRet
End Function
Public Function StrLen(ByVal uString As String) As Integer
If (Not uString Is Nothing) AndAlso (Not uString = "") Then
Return uString.Length
Else
Return 0
End If
End Function

I hope this can help you.
Dim con As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\yourDB.accdb;")
Dim cb As String = "SELECT * FROM Table1 "
Dim dr As System.Data.OleDb.OleDbDataReader
Dim cmd As New System.Data.OleDb.OleDbCommand
cmd.Connection = con
cmd.CommandText = cb
con.Open()
dr = cmd.ExecuteReader
While dr.Read()
If Not IsDBNull(dr("value1")) Then MessageBox.Show(dr("value1"))
End While
con.Close()

Supposing that the noNull method is something like this
Public Function noNull(dbValue As Object) as Boolean
if dbValue = DBNull.Value OrElse dbValue = "" Then
return True
else
return False
End If
End Function
Then you call it with
....
noNull(reader("LastName") = "")
....
This means that you compare the value of the LastName field to an Empty string and the result is a boolean True or False, but passing a Boolean value to noNull means that it will never be equal to an empty string or to a DBNull.Value and thus it will return always false
You need to call the method with
If noNull(reader("StudentID")) _
Or noNull(reader("LastName")) _
Or noNull(reader("FirstName")) _
Or noNull(reader("Affiliation")) Then
Or without the noNull method
If reader.IsDBNull(reader.GetOrdinal("StudentID")) _
OrElse reader("StudentID") = "" _
OrElse reader.IsDBNull(reader.GetOrdinal("LastName")) _
OrElse reader("LastName") = ""
OrElse reader.IsDBNull(reader.GetOrdinal("FirstName")) _
OrElse reader("FirstName") = "" _
OrElse reader.IsDBNull(reader.GetOrdinal("Affiliation")) _
OrElse reader("Affiliation") = "" Then
BlankFields = True
Else
BlankFields = False
End If
As you can see this is really ugly, so I suppose that a method like noNull iomplemented above could be useful in this context
EDIT Now, looking at the code of your noNull method then it is clear where is the error.
You should just change the parenthesis position.
If noNull(reader("StudentID")) = "" _
Or noNull(reader("LastName")) = "" _
Or noNull(reader("FirstName")) = "" _
Or noNull(reader("Affiliation")) = "" Then

Related

I now am getting this error "The type initializer for 'iTrac.SalesOrder' threw an exception."

I have a function that works fine iTrac.SalesOrder.SalesOrdersByBody_JB, when I try to call it from the web service, it fails and throws the exception
"The type initializer for 'iTrac.SalesOrder' threw an exception."
I see this is a fairly common situation and I did go through ALL of the similar questions but I did not see any answer to my problem, or maybe I am too much of a newbie to recognize the answer...?
went through all the similar questions.
Private Sub BrowserMailSender(obj As Object, e As EventArgs)
Dim x As New List(Of iTrac.JBSODetail)
Try
FileIO.WriteToFile("service is started:" + Now + vbNewLine)
x = iTrac.SalesOrder.SalesOrdersByBody_JB(241)
FileIO.WriteToFile(x.ToString)
Catch ex As Exception
FileIO.WriteToFile(ex.Message + vbNewLine)
End Try
End Sub
function that throws the exception
Public Shared Function SalesOrdersByBody_JB(ByVal BodyID As String) As List(Of JBSODetail)
Dim SalesOrderList As New List(Of JBSODetail)
Using context = New iTracContext
Dim BOMList = New List(Of Integer)
Dim StatusList As New List(Of String)
BOMList = context.BillOfMaterials.Where(Function(b) b.Child =
BodyID And b.ParentClass = "RTS").Select(Function(b)
b.Parent).ToList
If BOMList Is Nothing Then
Return Nothing
Else
StatusList.Add("OPEN")
StatusList.Add("HOLD")
StatusList.Add("BACKORDER")
End If
Dim query =context.JBSODetails.Include
("Part").Include("SOHeader").AsQueryable
If Not String.IsNullOrEmpty(BodyID) Then
query = query.Where(Function(s)
BOMList.Contains(s.pid) And
StatusList.Contains(s.status.ToUpper))
End If
Return query.OrderBy(Function(s) s.promised_date).ToList
End Using
End Function
Imports System.Data.SqlClient
Imports System.ComponentModel.DataAnnotations
Imports iTrac
<Table("tblSODetails")>
Public Class SalesOrder
<Key()>
Public Property sid As Decimal
Public Property SalesOrderNumber As String
Public Property SalesOrderLine As String
Public Property NeedDate As Date
Public Property PromisedDate As Date
Public Property ShipTo As String
Public Property Customer As String
<Column("UnitPriceOfOrder")>
Public Property UnitPrice As Decimal?
<Column("PriceUnitOfOrder")>
Public Property PriceUnit As String
Public Property OrderQuantity As Decimal?
Public Property OrderBalance As Decimal?
Public Property OrderEntryDate As Date
<Column("Material")>
Public Property CustomerPartNumber As String
Public Property LastUpdated As Date
Public Property CustomerPO As String
<NotMapped()>
Public Property NormalizedPartNumber As String
Public Property OfficeNote As String
Public Property pid As Integer?
Public Property aid As Integer?
Public Property cid As Integer?
Public Property TransferTime As Date
Public Property ShipVia As String
<NotMapped>
Public Property RunningTotal As Integer?
<ForeignKey("pid")>
Public Property Inventory As CompiledInventory
<ForeignKey("pid")>
Public Property Part As Part
<NotMapped()>
Public Property RTS
<NotMapped()>
Public Property Plate
<NotMapped()>
Public Property Machined
<NotMapped()>
Public Property Status
Private Shared ConnectionString As String = BrowserUtilities.Settings.ConnectionString
Public ReadOnly Property Blocked As Boolean
Get
Return ShippingBlock.BlockExists(SalesOrderNumber, SalesOrderLine)
End Get
End Property
Public Shared Function OpenSalesOrderList(ByVal CustomerName As String,
ByVal ShipToAddress As String,
ByVal CustomerPartNumber As String,
ByVal CutOffDate As String,
ByVal NormalizedID As String,
ByVal UpdatedWindow As String,
Optional ByVal CustomerPO As String = "") As List(Of SalesOrder)
Dim SalesOrderList As New List(Of SalesOrder)
Using Connection As New SqlConnection(ConnectionString)
Connection.Open()
Dim sqlString = ""
Dim sqlWhereClause = ""
If CustomerName <> "" Then
sqlWhereClause = " where customer = '" & CustomerName & "'"
End If
If ShipToAddress <> "" Then
If sqlWhereClause > "" Then
sqlWhereClause += " and shipto = '"
Else
sqlWhereClause += " where shipto = '"
End If
sqlWhereClause += ShipToAddress + "'"
End If
If CustomerPartNumber <> "" Then
If sqlWhereClause > "" Then
sqlWhereClause += " and material like '"
Else
sqlWhereClause += " where material like '"
End If
sqlWhereClause += CustomerPartNumber + "'"
End If
If CustomerPO <> "" Then
If sqlWhereClause > "" Then
sqlWhereClause += " and customerpo = '"
Else
sqlWhereClause += " where customerpo = '"
End If
sqlWhereClause += CustomerPO + "'"
End If
If NormalizedID <> "" Then
If NormalizedID <> "0" Then
If sqlWhereClause > "" Then
sqlWhereClause += " and pid = '"
Else
sqlWhereClause += " where pid = '"
End If
sqlWhereClause += NormalizedID + "'"
End If
End If
If CutOffDate <> "" And CustomerPO = "" Then
If sqlWhereClause > "" Then
sqlWhereClause += " and promiseddate <= '"
Else
sqlWhereClause += " where promiseddate <= '"
End If
sqlWhereClause += CutOffDate + "'"
End If
If UpdatedWindow <> "" Then
If sqlWhereClause > "" Then
sqlWhereClause += " and "
Else
sqlWhereClause += "where "
End If
sqlWhereClause += "lastupdated between '" & Now.AddHours(-Val(UpdatedWindow)) & "' and '" & Now & "'"
End If
sqlString = "Select s.*, (select NormalizedPartNumber from tblPart where id = pid) as NormalizedPartNumber from tblSODetails as s" & sqlWhereClause
If UpdatedWindow <> "" Then
sqlString += " order by customer, normalizedpartnumber, promiseddate"
Else
sqlString += " order by promiseddate"
End If
Dim command = New SqlCommand(sqlString, Connection)
Dim dataReader As SqlDataReader = command.ExecuteReader()
While dataReader.Read()
Dim so = New SalesOrder()
so.MapDataReader(dataReader, 1)
SalesOrderList.Add(so)
End While
End Using
Return SalesOrderList
End Function
Private Sub MapDataReader(ByVal dataReader As IDataReader, ByVal Method As Integer)
Select Case Method
Case 0, 1
sid = If(IsDBNull(dataReader("sid")), "", dataReader("sid"))
SalesOrderNumber = If(IsDBNull(dataReader("salesordernumber")), "", dataReader("salesordernumber"))
SalesOrderLine = If(IsDBNull(dataReader("salesorderline")), "", dataReader("salesorderline"))
PromisedDate = If(IsDBNull(dataReader("promiseddate")), "", dataReader("promiseddate"))
ShipTo = If(IsDBNull(dataReader("shipto")), "", dataReader("shipto"))
Customer = If(IsDBNull(dataReader("customer")), "", dataReader("customer"))
UnitPrice = If(IsDBNull(dataReader("unitpriceoforder")), 0, dataReader("unitpriceoforder"))
PriceUnit = If(IsDBNull(dataReader("priceunitoforder")), "", dataReader("priceunitoforder"))
OrderQuantity = If(IsDBNull(dataReader("orderquantity")), "", dataReader("orderquantity"))
OrderBalance = If(IsDBNull(dataReader("orderbalance")), "", dataReader("orderbalance"))
OrderEntryDate = If(IsDBNull(dataReader("orderentrydate")), "", dataReader("orderentrydate"))
CustomerPartNumber = If(IsDBNull(dataReader("material")), "", dataReader("material"))
LastUpdated = If(IsDBNull(dataReader("lastupdated")), "", dataReader("lastupdated"))
CustomerPO = If(IsDBNull(dataReader("customerpo")), "", dataReader("customerpo"))
OfficeNote = If(IsDBNull(dataReader("officenote")), "", dataReader("officenote"))
pid = If(IsDBNull(dataReader("pid")), 0, dataReader("pid"))
aid = If(IsDBNull(dataReader("aid")), 0, dataReader("aid"))
cid = If(IsDBNull(dataReader("cid")), 0, dataReader("cid"))
TransferTime = dataReader("transfertime")
ShipVia = If(IsDBNull(dataReader("shipvia")), "", dataReader("shipvia"))
NeedDate = If(IsDBNull(dataReader("new_promised_date")), dataReader("promiseddate"), dataReader("new_promised_date"))
If Method = 1 Then NormalizedPartNumber = If(IsDBNull(dataReader("normalizedpartnumber")), "", dataReader("normalizedpartnumber"))
Case 2
Customer = If(IsDBNull(dataReader("customer")), "Unknown", dataReader("customer"))
End Select
End Sub
Public Shared Function SalesOrdersByBody(ByVal BodyID As String, ByVal CustomerPartNumber As String) As List(Of SalesOrder)
Dim SalesOrderList As New List(Of SalesOrder)
Dim CP As New Part
Using Connection As New SqlConnection(ConnectionString)
Dim sqlString = ""
Connection.Open()
If BodyID > "" Then
sqlString = "Select s.*, d.new_promised_date from tblPart as p " &
"inner join tblSODetails as s on p.id = s.pid " &
"inner join tblJBSODetails d on d.sales_order = s.salesordernumber " &
"inner join tblBillOfMaterial as b on p.id = b.parent and parentclass = 'rts' " &
"where b.child = " & BodyID & " order by s.promiseddate"
Else
sqlString = "Select s.*, d.new_promised_date from tblPart as p " &
"inner join tblSODetails as s on s.pid = p.id " &
"inner join tblJBSODetails d on d.sales_order = s.salesordernumber " &
"where p.CustomerPartNumber = '" & CustomerPartNumber & "' " &
"order by s.promiseddate"
End If
Dim command = New SqlCommand(sqlString, Connection)
Dim dataReader As SqlDataReader = command.ExecuteReader()
While dataReader.Read()
Dim so = New SalesOrder()
so.MapDataReader(dataReader, 0)
SalesOrderList.Add(so)
End While
End Using
Return SalesOrderList
End Function
Public Shared Function SalesOrdersByBody_JB(ByVal BodyID As String) As List(Of JBSODetail)
Dim SalesOrderList As New List(Of JBSODetail)
Using context = New iTracContext
Dim BOMList = New List(Of Integer)
Dim StatusList As New List(Of String)
BOMList = context.BillOfMaterials.Where(Function(b) b.Child = BodyID And b.ParentClass = "RTS").Select(Function(b) b.Parent).ToList
If BOMList Is Nothing Then
Return Nothing
Else
StatusList.Add("OPEN")
StatusList.Add("HOLD")
StatusList.Add("BACKORDER")
End If
Dim query = context.JBSODetails.Include("Part").Include("SOHeader").AsQueryable
If Not String.IsNullOrEmpty(BodyID) Then
query = query.Where(Function(s) BOMList.Contains(s.pid) And StatusList.Contains(s.status.ToUpper))
End If
Return query.OrderBy(Function(s) s.promised_date).ToList
End Using
End Function
Public Shared Function SalesOrdersByPartID(ByVal PartID As Integer) As List(Of SalesOrder)
Dim SalesOrderList As New List(Of SalesOrder)
Using Connection As New SqlConnection(ConnectionString)
Dim sqlString = ""
Connection.Open()
sqlString = "Select s.*, d.new_promised_date from tblPart as p " &
"inner join tblSODetails as s on p.id = s.pid " &
"inner join tblJBSODetails d on d.sales_order = s.salesordernumber " &
"inner join tblBillOfMaterial as b on p.id = b.parent and parentclass = 'rts' " &
"where b.parent = " & PartID & " order by s.promiseddate"
Dim command = New SqlCommand(sqlString, Connection)
Dim dataReader As SqlDataReader = command.ExecuteReader()
While dataReader.Read()
Dim so = New SalesOrder()
so.MapDataReader(dataReader, 0)
SalesOrderList.Add(so)
End While
End Using
Return SalesOrderList
'Using context = New iTracContext
' Return context.SalesOrders.Where(Function(s) s.pid = PartID).ToList
'End Using
End Function
Public Shared Function SalesOrdersByPartID_JB(ByVal PartID As Integer) As List(Of JBSODetail)
Dim SalesOrderList As New List(Of JBSODetail)
Using context = New iTracContext
Dim query = context.JBSODetails.Include("SOHeader").Include("Part").AsQueryable
If Not String.IsNullOrEmpty(PartID) Then query = query.Where(Function(s) s.pid = PartID)
query = query.Where(Function(s) s.status = "Open")
Return query.OrderBy(Function(s) s.promised_date).ToList
End Using
End Function
Public Function CustomerList(ByVal CutoffDate As Date) As List(Of String)
Dim CList As New List(Of String)
Using Connection As New SqlConnection(ConnectionString)
Connection.Open()
Dim sqlString = "select customer from tblSODetails where promiseddate <= '" & CutoffDate.ToShortDateString & "' " &
"group by customer order by customer"
Dim command = New SqlCommand(sqlString, Connection)
Dim dataReader As SqlDataReader = command.ExecuteReader()
While dataReader.Read()
MapDataReader(dataReader, 2)
CList.Add(Customer)
End While
End Using
Return CList
End Function
Public Shared Function OpenList(ByVal CutoffDate As Date, ByVal Customer As String, ByVal ShipVia As String) As List(Of SalesOrder)
Using context = New iTracContext
Dim query = context.SalesOrders.Include("Inventory").Include("Part").AsQueryable
query = query.Where(Function(s) s.PromisedDate <= CutoffDate)
If Not String.IsNullOrEmpty(Customer) Then query = query.Where(Function(s) s.Customer = Customer)
If Not String.IsNullOrEmpty(ShipVia) Then query = query.Where(Function(s) s.ShipVia = ShipVia)
Return query.OrderBy(Function(l) l.PromisedDate).ToList
End Using
End Function
Public ReadOnly Property PartNumber As String
Get
If Part IsNot Nothing Then
Return Part.NormalizedPartNumber
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsOk As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_ok
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsHold As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_hold
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsRejected As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_rejected
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsOut As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_out
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsInReceving As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_receiving
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsInShipping As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_in_shipping
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsIssued As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_issued
Else
Return Nothing
End If
End Get
End Property
End Class
This line is throwing the exception:
Private Shared ConnectionString As String = BrowserUtilities.Settings.ConnectionString
Something in the expression BrowserUtilities.Settings.ConnectionString is throwing an exception. It's unclear what it is but I would say that NullReferenceException is the most likely candidate. Maybe BrowserUtilities.Settings is Nothing. It's just guesswork at this point. You'll have to debug it to find out.
When a Shared (static in C#) field, such as ConnectionString in your code, has an initialization expression, that initialization occurs in a special method called a "type initializer". All initialization expressions for the Shared fields in a type are grouped into the type initializer and executed before the first time that type is used*.
*This is a slight simplification for the sake of this explanation.
The first time you called the SalesOrdersByBody_JB function, it first had to initialize the type, which means running the type initializer to initialize ConnectionString. It looked like SalesOrdersByBody_JB threw the exception, but it was really happening slightly before that.

VB service export SQL to CSV

I have created a service that is supposed to pass data from SQL to CSV, by creating a CSV file. It has no errors, but i run it and nothing happens.
1) Is there something I am missing?
2) If it works, and i want to convert to txt file, is it enough to change the "CSV" to "txt" parts?
My code:
#Region "Export SQL TO CSV"
Public Shared Function WriteCSV(ByVal input As String) As String
Try
If (input Is Nothing) Then
Return String.Empty
End If
Dim containsQuote As Boolean = False
Dim containsComma As Boolean = False
Dim len As Integer = input.Length
Dim i As Integer = 0
Do While ((i < len) _
AndAlso ((containsComma = False) _
OrElse (containsQuote = False)))
Dim ch As Char = input(i)
If (ch = Microsoft.VisualBasic.ChrW(34)) Then
containsQuote = True
ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
containsComma = True
End If
i = (i + 1)
Loop
If (containsQuote AndAlso containsComma) Then
input = input.Replace("""", """""")
End If
If (containsComma) Then
Return """" & input & """"
Else
Return input
End If
Catch ex As Exception
Throw
End Try
End Function
Private Sub ExtoCsv(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As StringBuilder = New StringBuilder
Using db As Database.RecordSet = admin.Database.OpenRecordsetReadOnly("select USERID, NAME1 from usertable WHERE I_ID=2")
Dim userid As String = db("USERID").Value
Dim name1 As String = db("NAME1").Value
For i As Integer = 1 To db.RecordCount
sb.Append(WriteCSV(userid + "," + name1 + ","))
sb.AppendLine()
db.MoveNext()
Next
End Using
File.WriteAllText("C:\Users\user1\Desktop\ex1.csv", sb.ToString)
If (Not System.IO.Directory.Exists("C:\Users\user1\Desktop\ex1")) Then
System.IO.Directory.CreateDirectory("C:\Users\user1\Desktop\ex1")
End If
End Sub
#End Region

Latebinding issue for object

Following code causes an error at oDataObject.lastError and oDataObject.clearerror() of object ,while setting the option strict On a late binding issue persists.
Before option strict set to on the oDataObject.lastError and oDataObject.clearerror() showing as inbuild function and supports all class.
If Not trySettingValue(moProp, oDataObject, oTB.Text, sError) Then
oTB.BackColor = System.Drawing.Color.Red
bOk = False
Else
oTB.BackColor = System.Drawing.Color.White
End If
Public Shared Function trySettingValue(ByRef oProp As
System.Reflection.PropertyInfo, _
ByRef oDataObject As Object, _
ByVal oValue As Object, _
ByRef sError As String) As Boolean
Try
oDataObject.clearerror()
Select Case oProp.PropertyType.FullName
Case "System.String"
Dim str As String
str = CType(oValue, String)
oProp.SetValue(oDataObject, str, Nothing)
Case Else
End Select
' errorhandling
If oDataObject.lastError <> "" Then
sError = sError & oDataObject.lastError
Return False
Else
Return True
End If
Catch e As System.Exception
Trace.WriteLine(e.Message)
Trace.Flush()
sError = sError & "De ingevoerde waarde voor '" & oProp.Name & "' is foutief." & vbCrLf
Return False
End Try
End Function

Recursive Function Not Returning

I am hopeing someone can help me here with a recursive function I have that is not returning either true or false as I would have espected it to. The function loops through a Active Directory group for its members and then calls itself if it encounters any groups within the membership in order to gets its members as well. I am trying to return either true or false based on if any errors were encountered but not haveing any luck at all. It appears to just hang and never return back to the primary calling sub that starts the recursive function. Below is my code I am using:
Private Sub StartAnalysis(ByVal grp As String, ByVal grpdn As String, ByVal reqid As String)
Dim searchedGroups As New Hashtable
'prior work before calling sub
searchedGroups.Add(grp, 1)
Dim iserror As Boolean = GetGroupMembers(grpdn, searchedGroups, reqid)
If iserror = False Then
'do stuff
Else
'do stuff
End If
'cleanup
End Sub
Public Function GetGroupMembers(ByVal groupSearch As String, ByVal searchedGroups As Hashtable, ByVal requestID As String) As Boolean
Dim iserror As Boolean = False
Try
Dim lastQuery As Boolean = False
Dim endLoop As Boolean = False
Dim rangeStep As Integer = 999
Dim rangeLow As Integer = 0
Dim rangeHigh As Integer = rangeLow + rangeStep
Do
Dim range As String = "member"
If lastQuery = False Then
range = String.Format("member;range={0}-{1}", rangeLow, rangeHigh)
Else
range = String.Format("member;range={0}-*", rangeLow)
endLoop = True
End If
Dim group As SearchResult = QueryObject(groupSearch, range)
Dim groupCN As String = group.Properties("cn")(0).ToString
If group.Properties.Contains(range) Then
For Each member As Object In group.Properties(range)
Dim user As SearchResult = QueryObject(member.ToString, "member")
Dim userCN = user.Properties("cn")(0).ToString
If Not user.Properties.Contains("member") Then
Dim userMail = String.Empty
If user.Properties.Contains("mail") Then
userMail = user.Properties("mail")(0).ToString
End If
userCN = userCN.Replace("'", "''")
Dim qry As String = _
"INSERT INTO group_analysis_details (request_id, member_name, member_email, member_group) " & _
"values ('" & requestID & "', '" & userCN & "', '" & userMail & "', '" & groupCN & "')"
Dim sqlConn As SqlConnection = New SqlConnection(cs)
Dim sqlCmd As SqlCommand = New SqlCommand(qry, sqlConn)
sqlConn.Open()
sqlCmd.ExecuteNonQuery()
sqlConn.Close()
sqlCmd.Dispose()
sqlConn.Dispose()
Else
If Not searchedGroups.ContainsKey(userCN) Then
searchedGroups.Add(userCN, 1)
iserror = GetGroupMembers(user.Properties("distinguishedname")(0).ToString, searchedGroups, requestID)
If iserror = True Then Return iserror
Else
searchedGroups(userCN) += 1
End If
End If
Next
Else
lastQuery = True
End If
If lastQuery = False Then
rangeLow = rangeHigh + 1
rangeHigh = rangeLow + rangeStep
End If
Loop While endLoop = False
Return iserror
Catch ex As Exception
myEvents.WriteEntry("Error while analyzing the following group: " & groupSearch & vbCrLf & vbCrLf & _
"Details of the error are as follows: " & ex.Message, EventLogEntryType.Error)
Return True
End Try
End Function
Hopefully someone can point out where I might be making my error is this.
Thanks,
Ron
Generally if you're using a 'Do...Loop While' and manually setting the exit condition inside the loop it's very easy to get stuck in an infinite loop which is what causes the program to hang.
It looks like you're not setting endloop = True in all circumstances. Try changing it to an Exit Do and adding one to each of the various conditions you have. A bit of trial and error will be required to get it just right.
Also to make your life easier extract the database insert code into a seperate function and call it when needed.

DataTable.Select with AND conditions doesn't give expected results

I'm trying to compare two datatables and I'm doing some tests using DataTable.Select on two identical datatables:
Using DT_NewData As DataTable = DT_DBData.Copy
For x As Short = 0 To DT_NewData.Rows.Count - 1
Dim SelRows As DataRow() = DT_DBData.Select( _
"Type='" & DT_NewData.Rows(x)("Type") & "'" & _
" AND In_Date='" & DT_NewData.Rows(x)("In_Date") & "'" & _
" AND Out_Date='" & DT_NewData.Rows(x)("Out_Date") & "'")
Next
But SelRows.Length is always 0. What's wrong in my code?
Although is a little strange the copy of the table, try this:
Suppose that Type is String
Imports Microsoft.VisualBasic
Imports System.Linq
Module StartupModule
Sub Main()
' Declare the table.
Dim originalDataTable As New DataTable
' Declare the table columns.
With originalDataTable.Columns
.Add("Type", GetType(String))
.Add("InDate", GetType(DateTime))
.Add("OutDate", GetType(DateTime))
End With
' Delegate to add rows.
Dim addRow As Action(Of String, DateTime?, DateTime?) = Sub(text, inDate, outDate)
Dim newRow As DataRow = originalDataTable.NewRow()
With newRow
If (Not String.IsNullOrEmpty(text)) Then
.SetField(Of String)("Type", text)
End If
If (inDate.HasValue) Then
.SetField(Of DateTime?)("InDate", inDate.Value)
End If
If (outDate.HasValue) Then
.SetField(Of DateTime?)("OutDate", outDate.Value)
End If
End With
originalDataTable.Rows.Add (newRow)
End Sub
' Adding rows to the table.
addRow("type1", #2/2/2017#, Nothing)
addRow(Nothing, #1/25/2016#, Nothing)
addRow(Nothing, Nothing, #1/30/2016#)
' Copy the table
Dim copiedDataTable As DataTable = originalDataTable.Copy
' Loop through copied table rows.
For i As Integer = 0 To copiedDataTable.Rows.Count - 1
Dim type As String = copiedDataTable.Rows(i).Field(Of String)("Type")
Dim inDate As DateTime? = copiedDataTable.Rows(i).Field(Of DateTime?)("InDate")
Dim outDate As DateTime? = copiedDataTable.Rows(i).Field(Of DateTime?)("OutDate")
' Using DataTable Select.
Dim filter As String = String.Format("{0} {1} {2}",
If(type Is Nothing, "( Type Is Null )", String.Format("( Type = '{0}' )", type)),
If(Not inDate.HasValue, "And ( InDate Is Null )", String.Format("And ( InDate = '{0}' )", inDate.Value.ToString())),
If(Not outDate.HasValue, "And ( OutDate Is Null )", String.Format("And ( OutDate = '{0}' )", outDate.Value.ToString())))
Dim usingSelectRows As DataRow() = originalDataTable.Select(filter)
Console.WriteLine("usingSelectRows.Count = {0}", usingSelectRows.Count)
' Using Linq.
Dim typeSelector As Func(Of DataRow, Boolean) = Function(r)
If (IsNothing(type)) Then
Return IsNothing(r.Field(Of String)("Type"))
Else
Return r.Field(Of String)("Type") = type
End If
End Function
Dim inDateSelector As Func(Of DataRow, Boolean) = Function(r)
If (Not inDate.HasValue) Then
Return Not r.Field(Of DateTime?)("InDate").HasValue
Else
Return r.Field(Of DateTime?)("InDate").GetValueOrDefault.CompareTo(inDate.GetValueOrDefault) = 0
End If
End Function
Dim outDateSelector As Func(Of DataRow, Boolean) = Function(r)
If (Not outDate.HasValue) Then
Return Not r.Field(Of DateTime?)("OutDate").HasValue
Else
Return r.Field(Of DateTime?)("OutDate").GetValueOrDefault.CompareTo(outDate.GetValueOrDefault) = 0
End If
End Function
Dim usingLinqRows = From r In originalDataTable.AsEnumerable
Where
(typeSelector(r)) AndAlso
(inDateSelector(r)) AndAlso
(outDateSelector(r))
Select r
Console.WriteLine("usingLinqRows.Count = {0}", usingLinqRows.Count)
Console.WriteLine()
Next
Console.ReadLine()
End Sub
End Module
Always use the Field extension of DataRow to retrieve data.