How to use a Name rather than OID in vb.net - vb.net

Good day,
I am trying to figure out this code from sharp-snmp samples.
https://github.com/lextudio/sharpsnmplib-samples/blob/master/Samples/VB.NET/snmpset/Program.vb
I am using the vb.net SET sample.
Public Sub New(id As Lextm.SharpSnmpLib.ObjectIdentifier, data As Lextm.SharpSnmpLib.ISnmpData)
Member of Lextm.SharpSnmpLib.Variable
Public Sub New(id As UInteger(), data As Lextm.SharpSnmpLib.ISnmpData)
Member of Lextm.SharpSnmpLib.Variable
Is my Name syntax just wrong, or is it that it must be an OID integer? When I use the OID it runs, when I use the name it dies.
System_Operation_Mode.0 'name
1.3.6.1.4.1.21703.100.1.1.0 'oid
This is the part of the SET sample where it dies at the asterix ** at the bottom of the code.
Extra(i) is filled out with the above Name instead of the OID.
ReDim args(3)
args(0) = "192.168.45.5" 'IP Address
args(1) = NetworkConfig.addrModeStringCommand 'command string name System_Operation_Mode.0
args(2) = "i" 'tell it what data type you are sending
args(3) = NetworkConfig.StaticMode 'mode you want from the IPNetwork, in this case static
Dim p As OptionSet = New OptionSet().Add("c:", "Community name, (default is public)", Sub(v As String)
If v IsNot Nothing Then
community = v
End If
End Sub) _
.Add("l:", "Security level, (default is noAuthNoPriv)", Sub(v As String)
If v.ToUpperInvariant() = "NOAUTHNOPRIV" Then
level = Levels.Reportable
ElseIf v.ToUpperInvariant() = "AUTHNOPRIV" Then
level = Levels.Authentication Or Levels.Reportable
ElseIf v.ToUpperInvariant() = "AUTHPRIV" Then
level = Levels.Authentication Or Levels.Privacy Or Levels.Reportable
Else
Throw New ArgumentException("no such security mode: " & v)
End If
End Sub) _
.Add("a:", "Authentication method (MD5 or SHA)", Sub(v As String)
authentication = v
End Sub) _
.Add("A:", "Authentication passphrase", Sub(v As String)
authPhrase = v
End Sub) _
.Add("x:", "Privacy method", Sub(v As String)
privacy = v
End Sub) _
.Add("X:", "Privacy passphrase", Sub(v As String)
privPhrase = v
End Sub) _
.Add("u:", "Security name", Sub(v As String)
user = v
End Sub) _
.Add("C:", "Context name", Sub(v As String)
contextName = v
End Sub) _
.Add("h|?|help", "Print this help information.", Sub(v As String)
showHelp__1 = v IsNot Nothing
End Sub) _
.Add("V", "Display version number of this application.", Sub(v As String)
showVersion = v IsNot Nothing
End Sub) _
.Add("d", "Display message dump", Sub(v As String)
dump = True
End Sub) _
.Add("t:", "Timeout value (unit is second).", Sub(v As String)
timeout = Integer.Parse(v) * 1000
End Sub) _
.Add("r:", "Retry count (default is 0)", Sub(v As String)
retry = Integer.Parse(v)
End Sub) _
.Add("v:", "SNMP version (1, 2, and 3 are currently supported)", Sub(v As String)
Select Case Integer.Parse(v)
Case 1
version = VersionCode.V1
Exit Select
Case 2
version = VersionCode.V2
Exit Select
Case 3
version = VersionCode.V3
Exit Select
Case Else
Throw New ArgumentException("no such version: " & v)
End Select
End Sub)
If args.Length = 0 Then
ShowHelp(p)
Return
End If
Dim extra As List(Of String)
Try
extra = p.Parse(args)
Catch ex As OptionException
Console.WriteLine(ex.Message)
Return
End Try
If showHelp__1 Then
ShowHelp(p)
Return
End If
If (extra.Count - 1) Mod 3 <> 0 Then
Console.WriteLine("invalid variable number: " & extra.Count)
Return
End If
If showVersion Then
Console.WriteLine(Reflection.Assembly.GetExecutingAssembly().GetName().Version)
Return
End If
Dim ip As IPAddress
Dim parsed As Boolean = IPAddress.TryParse(extra(0), ip)
If Not parsed Then
For Each address As IPAddress In Dns.GetHostAddresses(extra(0))
If address.AddressFamily <> AddressFamily.InterNetwork Then
Continue For
End If
ip = address
Exit For
Next
If ip Is Nothing Then
Console.WriteLine("invalid host or wrong IP address found: " & extra(0))
Return
End If
End If
Try
Dim vList As New List(Of Variable)()
Dim i As Integer = 1
While i < extra.Count
Dim type As String = extra(i + 1)
If type.Length <> 1 Then
Console.WriteLine("invalid type string: " & type)
Return
End If
Dim data As ISnmpData
Select Case type(0)
Case "i"c
data = New Integer32(Integer.Parse(extra(i + 2)))
Exit Select
Case "u"c
data = New Gauge32(UInteger.Parse(extra(i + 2)))
Exit Select
Case "t"c
data = New TimeTicks(UInteger.Parse(extra(i + 2)))
Exit Select
Case "a"c
data = New IP(IPAddress.Parse(extra(i + 2)).GetAddressBytes())
Exit Select
Case "o"c
data = New ObjectIdentifier(extra(i + 2))
Exit Select
Case "x"c
data = New OctetString(ByteTool.Convert(extra(i + 2)))
Exit Select
Case "s"c
data = New OctetString(extra(i + 2))
Exit Select
Case "d"c
data = New OctetString(ByteTool.ConvertDecimal(extra(i + 2)))
Exit Select
Case "n"c
data = New Null()
Exit Select
Case Else
Console.WriteLine("unknown type string: " & type(0))
Return
End Select
Dim test As New Variable(*New ObjectIdentifier(extra(i))*, data)
vList.Add(test)
i = i + 3
End While
I have been using using the "Name" instead of the "OID" is there a way to change so it can read either, or have them converted? Or will I have to go back use the OIDs?

Related

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

String comparison not working for array of strings

cfg file to start, this is the file:
http://pastebin.com/mE3Y3wiq
What I am doing is looking for a class, once found I store the data for THAT class in a listbox, so ex: if I'm looking for "Fixing", I will store each line in a listbox that is after "{Fixing}" until we hit the next class OR the end of the file (for Fixing we would stop at "{Pillars}")
Here is my code:
Private Sub tvList_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles tvList.AfterSelect
Dim cfgData() As String
' Dim lstData As New ListBox()
lstData.Items.Clear()
If rbnInch.Checked Then
cfgData = File.ReadAllLines("C:\Library\Common\PARAM-NG\Dbs\Mould\Dme_I\Dme_I.cfg")
Else
cfgData = File.ReadAllLines("C:\Library\Common\PARAM-NG\Dbs\Mould\Dme\Dme.cfg")
End If
Dim classID As Short = tvList.SelectedNode.Index
Dim classType As String = tvList.Nodes.Item(classID).Text
Try
For i As Short = 0 To cfgData.Count - 1
If cfgData(i).Contains("{" & classType & "}") Or cfgData(i).Contains("{" & classType.Replace(" ", "") & "}") Then
i += 1
Do
lstData.Items.Add(cfgData(i))
i += 1
If cfgData(i).Contains(tvList.Nodes.Item(tvList.SelectedNode.Index + 1).Text.Replace(" ", "")) Or cfgData(i).Contains(tvList.Nodes.Item(tvList.SelectedNode.Index + 1).Text) Or cfgData(i).ToString() Is vbNullString Then
Exit Do
End If
Loop
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Right now I am only getting the first line in my listbox and that's it. Need help on collecting the data I need and then stopping at the next class or end of file (end of file for the last class since there is no class after it that will mark my exit)
This has been extracted from the question and posted on the OP's behalf.
I solved it myself.
Private Sub tvList_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles tvList.AfterSelect
Dim cfgData() As String
' Dim lstData As New ListBox()
lstData.Items.Clear()
If rbnInch.Checked Then
cfgData = File.ReadAllLines("C:\Library\Common\PARAM-NG\Dbs\Mould\Dme_I\Dme_I.cfg")
Else
cfgData = File.ReadAllLines("C:\Library\Common\PARAM-NG\Dbs\Mould\Dme\Dme.cfg")
End If
Dim classID As Short = tvList.SelectedNode.Index
Dim classType As String = tvList.Nodes.Item(classID).Text
Try
For i As Short = 0 To cfgData.Count - 1
If cfgData(i).Contains("{" & classType) Or cfgData(i).Contains("{" & classType.Replace(" ", "")) Then
i += 1
Do
If tvList.SelectedNode.Index + 1 >= tvList.Nodes.Count Then
If i >= cfgData.Count - 1 Then
lstData.Items.Add(cfgData(i))
Exit Do
ElseIf cfgData(i) = vbNullString Then
lstData.Items.Add(cfgData(i))
i += 1
ElseIf cfgData(i).Substring(0, 1).Contains("{") Then
Exit Do
Else
lstData.Items.Add(cfgData(i))
i += 1
End If
ElseIf i >= cfgData.Count - 1 Then
lstData.Items.Add(cfgData(i))
Exit Do
ElseIf cfgData(i) = vbNullString Then
lstData.Items.Add(cfgData(i))
i += 1
ElseIf cfgData(i).Substring(0, 1).Contains("{") Then
Exit Do
Else
lstData.Items.Add(cfgData(i))
i += 1
End If
Loop
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Update multi table access db using vb.net

Can someone please help me with that?
My prob is that When i use dataAdapter.Update in this next construction i get a return value of zero (no line was updated but no reason or errors return).
The update sentense works when i run it using Access and other update requests works fine when i work on a single table.
Im Using:
vb.net \ visual studio 2012 \ access 2010 DB
I update the Data on my DataGridView and call the update function:
update command:
Private Function createGeneralUpdateStatement() As String
Return "UPDATE EntitysDataTbl INNER JOIN ManagersExtraDataTbl ON EntitysDataTbl.entityID = ManagersExtraDataTbl.managerID " + _
"SET EntitysDataTbl.entityUserName = [#EntitysDataTbl].entityUserName, " + _
"EntitysDataTbl.entityLastEntry = [#EntitysDataTbl].entityLastEntry, " + _
"ManagersExtraDataTbl.mPassword = [#ManagersExtraDataTbl].mPassword, " + _
"ManagersExtraDataTbl.workGroup = [#ManagersExtraDataTbl].workGroup, " + _
"ManagersExtraDataTbl.entityAccessType = [#ManagersExtraDataTbl].entityAccessType, " + _
"ManagersExtraDataTbl.mActive = [#ManagersExtraDataTbl].mActive" + _
"WHERE EntitysDataTbl.entityID= [#EntitysDataTbl].entityID"
End Function
The parameters are:
Dim parmList(2) As String
parmList(0) = "mPassword"
parmList(1) = "entityUserName"
and the update function is:
Public Function updateDB(ByVal updateCommand As String, ByVal parmList() As String, Optional ByVal insertCommand As String = "") As Boolean
Dim res As Boolean = False
SyncLock Me
Try
mainDataSet.EndInit()
mUpdateCommand = New OleDb.OleDbCommand(updateCommand, MyBase.getConnector)
For Each Str As String In parmList
If Not Str Is Nothing Then
If (Str.StartsWith("%")) Then
mUpdateCommand.Parameters.Add("#" & Str.Trim("%"), OleDb.OleDbType.Boolean, MAX_COL_LEN, Str.Trim("%"))
Else
mUpdateCommand.Parameters.Add("[#" & Str & "]", OleDb.OleDbType.VarChar, MAX_COL_LEN, Str)
End If
End If
Next
mDataAdapter.UpdateCommand = mUpdateCommand
If (Not insertCommand.Equals("")) Then
mInsertCommand = New OleDb.OleDbCommand(insertCommand, MyBase.getConnector)
For Each Str As String In parmList
If Not Str Is Nothing Then
'If Str.Equals("RuleIDNum") Then
' Continue For
'End If
If (Str.StartsWith("%")) Then
mInsertCommand.Parameters.Add("#" & Str.Trim("%"), OleDb.OleDbType.Boolean, MAX_COL_LEN, Str.Trim("%"))
Else
mInsertCommand.Parameters.Add("[#" & Str & "]", OleDb.OleDbType.VarChar, MAX_COL_LEN, Str)
End If
End If
Next
mDataAdapter.InsertCommand = mInsertCommand
End If
Dim i As Integer = mDataAdapter.Update(mainDataSet)
'ERROR - i = 0 => NO LINE WAS UPDATED!!!!
res = True
Catch ex As Exception
res = False
End Try
mDBWasUpdated = res
End SyncLock
Return res
End Function

sending bulk sms to group using vb.net

I connected recently to SMS provider API using vb.net
I have created a group table and inserted all numbers in this group and then reach each row and send trigger the API to process sending.
The sms is not reached to all group members, its only delivered successfully to the first mobile number in the group.
How to solve this problem ? I think I have to set a delay between each sending and i did with no use. my code is below :
Function GetGroupsMobileNumbers() As ArrayList
Dim MobileNumbersArrayList As New ArrayList
For Each Contact As FilsPayComponent.ContactAddress In FilsPayComponent.ContactAddress.GetAllContactAddressByGroupId(ddlGroup.SelectedValue)
MobileNumbersArrayList.Add(Contact.Mobile)
Next
Return MobileNumbersArrayList
End Function
Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.Click
If ddlGroup.SelectedValue = 0 Then
lbResult.Text = "No groups selected"
Exit Sub
End If
Dim MobileNumbersArrayList As ArrayList
MobileNumbersArrayList = GetGroupsMobileNumbers()
If MobileNumbersArrayList.Count = 0 Then
lbResult.Text = "Group doesnt contain numbers"
Exit Sub
End If
Dim TotalNo As Integer = FilsPayComponent.ContactAddress.AddressContactsCount(ddlGroup.SelectedValue)
If MobileNumbersArrayList.Count * messagecount.Value <= FilsPayComponent.SmSUser.GetSmSUserByUserId(Context.User.Identity.Name).Balance Then
Dim txtMsg As String
Dim smstype As Integer
If hidUnicode.Value <> "1" Then
txtMsg = txtMessage.Text
smstype = 1
Else
txtMsg = ConvertTextToUnicode(txtMessage.Text)
smstype = 2
End If
Dim x As Integer
'For Each Contact As FilsPayComponent.ContactAddress In FilsPayComponent.ContactAddress.GetAllContactAddressByGroupId(ddlGroup.SelectedValue)
For Each Contact In MobileNumbersArrayList.ToArray
Dim toMobile As String = Contact.Mobile
If toMobile.Length > 10 Then
Dim ExecArrayList As ArrayList
ExecArrayList = SendSMS(toMobile, txtMsg, smstype)
'-- give the excution more time
If ExecArrayList.Count < 1 Then
Threading.Thread.Sleep(1000)
End If
'-- give the excution more time
If ExecArrayList.Count < 1 Then
Threading.Thread.Sleep(1000)
End If
'-- give the excution more time
If ExecArrayList.Count < 1 Then
Threading.Thread.Sleep(1000)
End If
x = x + 1
' lbresult.Text = "Sent Successfully"
End If
Next
FilsPayComponent.SmSUser.RemoveSmsCredit(Context.User.Identity.Name, messagecount.Value * x)
Dim NewsmsarchiveItem As New FilsPayComponent.smsarchive
NewsmsarchiveItem.FromMobile = txtSenderID.Text
NewsmsarchiveItem.ToMobile = "0"
NewsmsarchiveItem.GroupId = ddlGroup.SelectedValue
NewsmsarchiveItem.DateSent = DateTime.Now
NewsmsarchiveItem.Msg = txtMessage.Text
NewsmsarchiveItem.GroupCount = x
NewsmsarchiveItem.Optional1 = Context.User.Identity.Name
NewsmsarchiveItem.Optional2 = "1"
NewsmsarchiveItem.MessageNo = messagecount.Value
Try
NewsmsarchiveItem.Addsmsarchive()
lbResult.Text = "Message sent successfully"
btnSend.Visible = False
Catch ex As Exception
lbResult.Text = ex.Message
End Try
Else
lbResult.Text = "Not enough credit, please refill "
End If
End Sub
Sub SendSMS(ByVal toMobile As String, ByVal txtMsg As String, ByVal smstype As Integer)
Dim hwReq As HttpWebRequest
Dim hwRes As HttpWebResponse
Dim smsUser As String = "xxxxxx"
Dim smsPassword As String = "xxxxxx"
Dim smsSender As String = "xxxxxx"
Dim strPostData As String = String.Format("username={0}&password={1}&destination={2}&message={3}&type={4}&dlr=1&source={5}", Server.UrlEncode(smsUser), Server.UrlEncode(smsPassword), Server.UrlEncode(toMobile), Server.UrlEncode(txtMsg), Server.UrlEncode(smstype), Server.UrlEncode(smsSender))
Dim strResult As String = ""
Try
hwReq = DirectCast(WebRequest.Create("http://xxxxx:8080/bulksms/bulksms?"), HttpWebRequest)
hwReq.Method = "POST"
hwReq.ContentType = "application/x-www-form-urlencoded"
hwReq.ContentLength = strPostData.Length
Dim arrByteData As Byte() = ASCIIEncoding.ASCII.GetBytes(strPostData)
hwReq.GetRequestStream().Write(arrByteData, 0, arrByteData.Length)
hwRes = DirectCast(hwReq.GetResponse(), HttpWebResponse)
If hwRes.StatusCode = HttpStatusCode.OK Then
Dim srdrResponse As New StreamReader(hwRes.GetResponseStream(), Encoding.UTF8)
Dim strResponse As String = srdrResponse.ReadToEnd().Trim()
Select Case strResponse
Case "01"
strResult = "success"
Exit Select
Case Else
strResult = "Error: " + strResponse
Exit Select
End Select
End If
Catch wex As WebException
strResult = "Error, " + wex.Message
Catch ex As Exception
strResult = "Error, " + ex.Message
Finally
hwReq = Nothing
hwRes = Nothing
End Try
End Sub
If function GetGroupsMobileNumbers() does not return an array list of numbers (as Strings)
then comment out. MobileNumbersArrayList = GetGroupsMobileNumbers()
then use the commented out code below (with three of your own tel. numbers) to set it for testing.
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
If ddlGroup.SelectedValue = 0 Then
lbResult.Text = "No groups selected"
Exit Sub
End If
Dim MobileNumbersArrayList As New ArrayList
MobileNumbersArrayList = GetGroupsMobileNumbers()
'MobileNumbersArrayList.Add("07702123456")
'MobileNumbersArrayList.Add("07702123457")
'MobileNumbersArrayList.Add("07702123458")
If MobileNumbersArrayList.Count = 0 Then
lbResult.Text = "Group doesnt contain numbers"
Exit Sub
End If
Dim TotalNo As Integer = FilsPayComponent.ContactAddress.AddressContactsCount(ddlGroup.SelectedValue)
If MobileNumbersArrayList.Count * messagecount.Value <= FilsPayComponent.SmSUser.GetSmSUserByUserId(Context.User.Identity.Name).Balance Then
Dim txtMsg As String
Dim smstype As Integer
If hidUnicode.Value <> "1" Then
txtMsg = txtMessage.Text
smstype = 1
Else
txtMsg = ConvertTextToUnicode(txtMessage.Text)
smstype = 2
End If
Dim x As Integer
For Each Contact In MobileNumbersArrayList
If Contact.Length > 10 Then
SendSMS(Contact, txtMsg, smstype)
x = x + 1
End If
Next
FilsPayComponent.SmSUser.RemoveSmsCredit(Context.User.Identity.Name, messagecount.Value * x)
Dim NewsmsarchiveItem As New FilsPayComponent.smsarchive
NewsmsarchiveItem.FromMobile = txtSenderID.Text
NewsmsarchiveItem.ToMobile = "0"
NewsmsarchiveItem.GroupId = ddlGroup.SelectedValue
NewsmsarchiveItem.DateSent = DateTime.Now
NewsmsarchiveItem.Msg = txtMessage.Text
NewsmsarchiveItem.GroupCount = x
NewsmsarchiveItem.Optional1 = Context.User.Identity.Name
NewsmsarchiveItem.Optional2 = "1"
NewsmsarchiveItem.MessageNo = messagecount.Value
Try
NewsmsarchiveItem.Addsmsarchive()
lbResult.Text = "Message sent successfully"
btnSend.Visible = False
Catch ex As Exception
lbResult.Text = ex.Message
End Try
Else
lbResult.Text = "Not enough credit, please refill "
End If
End Sub
This btnSend sub should work if the rest of your code is okay. Note your line.
Dim TotalNo As Integer = FilsPayComponent.ContactAddress.AddressContactsCount(ddlGroup.SelectedValue)
Doesn't appear to do anything.
If you need to set a delay you would be better off turning SendSMS into a function that returns a sent confirmation to your btnSend loop. Most texting APIs can handle lists of numbers rather than waiting for a response for each text message. Afterall they only get added to a queue at their end.

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.