Getting a list of users on a network domain - vb.net

I want to get back to get a list of users on a network domain using VB.Net.
I will have the domain name available to me for use.
Thanks in advance.

It might throw an error in the select query.
Please check this:
Did you add a reference to the System.Management assembly to your project? If you haven't, do this:
In VS, click on Project menu > add reference.
On the .Net tab, scroll down until you see System.Management. Click on it to select, then click OK.
Now back in your code, at the very top of your class, put in "Imports System.Management", and you should be all set.
Source:
http://www.vbforums.com/showthread.php?t=560422
It worked for me without any issues. I am able to get all user names for the domain.

Something like this might point you in the right direction, using System.DirectoryServices and System.DirectoryServices.ActiveDirectory:
Private Function GetDomainUsers(ByVal domainDirectoryEntry As DirectoryEntry, ByRef userList As IList) As Integer
Try
userList = New ArrayList()
Using domainDirectoryEntry
Dim ds As New DirectorySearcher(domainDirectoryEntry, "(&(objectCategory=person)(objectClass=user))", New String() {"distinguishedName"})
Using src As SearchResultCollection = ds.FindAll()
For Each sr As SearchResult In src
userList.Add(sr.Properties("distinguishedName")(0))
Next
End Using
End Using
Return userList.Count
Catch generatedExceptionName As Exception
userList = Nothing
Return -1
Finally
domainDirectoryEntry = Nothing
End Try
End Function

Imports System.Management
Imports System.Management.Instrumentation
Sub PrintDomainUsers()
Dim domainName As String = System.Environment.UserDomainName.ToString
Dim userQuery As SelectQuery = New SelectQuery("Win32_UserAccount", "Domain='" & domainName & "'")
Try
Dim userSearch As ManagementObjectSearcher = New ManagementObjectSearcher(userQuery)
For Each domainUser In userSearch.Get
Console.WriteLine(domainUser("Name"))
Next
Catch ex As Exception
Throw ex
End Try
End Sub
This works but how do i filter by a certain group. Im getting THOUSANDS of resutls

Another option would be exploring System.Management and System.Management.Instrumentation.Here is a short snippet of how you pull the users of a particular domain using these namespaces.
Imports System.Management
Imports System.Management.Instrumentation
Sub PrintDomainUsers()
Dim domainName As String = System.Environment.UserDomainName.ToString
Dim userQuery As SelectQuery = New SelectQuery("Win32_UserAccount", "Domain='" & domainName & "'")
Try
Dim userSearch As ManagementObjectSearcher = New ManagementObjectSearcher(userQuery)
For Each domainUser In userSearch.Get
Console.WriteLine(domainUser("Name"))
Next
Catch ex As Exception
Throw ex
End Try
End Sub

Related

Log Writer not creating new line for each entry

I get the feeling this is something really simple, but I've tried I don't know how many permutations of vbNewLine, Environment.NewLine, sMessage & vbNewLine (or Environment.Newline) I've tried, or how many pages on this site, or through Google I've looked at but nothing has worked.
I even tried getting help from a VB.Net discord channel I'm a part of and they suggested to do the same things that I've done and the procedure is still writing each new log entry at the end of the previous one in a continuous string. My writer is below. Am I missing something simple?
Edit: The code that worked is below in case anyone else comes along with the same issue. If you want to see the original code it's in the edit log.
Option Explicit On
Imports System.IO
Public Class WriteroLog
Public Shared Sub LogPrint(sMessage As String)
Dim AppPath As String = My.Application.Info.DirectoryPath
If File.Exists($"{AppPath}\Log.txt") = True Then
Try
Using objWriter As StreamWriter = File.AppendText($"{AppPath}\Log.Txt")
objWriter.WriteLine($"{Format(Now, "dd-MMM-yyyy HH:mm:ss")} – {sMessage}")
objWriter.Close()
End Using
Catch ex As Exception
MsgBox(ex)
Return
End Try
Else
Try
Using objWriter As StreamWriter = File.CreateText($"{AppPath}\Log.Txt")
objWriter.WriteLine($"{Format(Now, "dd-MMM-yyyy HH:mm:ss")} – {sMessage}")
objWriter.Close()
End Using
Catch ex As Exception
MsgBox(ex)
Return
End Try
End If
End Sub
End Class
The File.AppendText() method creates a new StreamWriter that is then used to append Text to the specified File.
Note, reading the Docs about this method, that you don't need to verify whether the File already exists: if it doesn't, the File is automatically created.
As a side note, when creating a Path, it's a good thing to use the Path.Combine method: it can prevent errors in the path definition and handles platform-specific formats.
Your code could be simplified as follows:
Public Shared Sub LogPrint(sMessage As String)
Dim filePath As String = Path.Combine(Application.StartupPath, "Log.Txt")
Try
Using writer As StreamWriter = File.AppendText(filePath)
writer.WriteLine($"{Date.Now.ToString("dd-MMM-yyyy HH:mm:ss")} – {sMessage}")
End Using
Catch ex As IOException
MsgBox(ex)
End Try
End Sub
The File.CreateText does not assign result to "objWrite", should be:
objWriter = File.CreateText($"{AppPath}\Log.Txt")
Not really sure if this is the root of your problem, but it is an issue.
In essences, your logic is re-opening or creating the stream "objWriter" for every call to this method. I would recommend you initialize "objWriter" to Nothing and only define if it is Nothing.
Set to Nothing as below.
Shared objWriter As IO.StreamWriter = Nothing
Then add check for Nothing in logic.

Lucene Update not working Index Writer

I have updated a large application from .Net 4.0 to .Net 4.52 and it has broken some indexing and search functions that I have that use Lucene. I updated to the latest NuGet Packages for Lucene and I keep getting the following errors.
Type 'Lucene.Net.Index.IndexWriter' is not defined.
Type 'Lucene.Net.Documents.Document' is not defined.
Type 'IndexWriter' is not defined.
To name a few. The search functions were originally written by another developer so I am not completely familiar with it but it looks like they may have moved some namespaces when they updated Lucene to 3.0.3 but I can't find what they updated to.
Any help would be greatly appreciated!
Thanks
Code Example Below
References:
Imports Microsoft.WindowsAzure.Storage.Blob
Imports Microsoft.WindowsAzure.Storage
Imports Lucene.Net
Imports Lucene.Net.Documents
Imports Lucene.Net.Store
Imports Lucene.Net.Index
Imports Lucene.Net.Analysis
The Lucene.Net.Store says it doesn't contain any public members.
Example function that says Lucene.Net.Index.IndexWriter is not defined
Private Function IndexNewDocument(id As String, savePath As String, targetContainer As String, indexer As Lucene.Net.Index.IndexWriter, b As CloudBlockBlob) As Boolean
Dim sw As Stopwatch = Stopwatch.StartNew
Dim filename As String = ""
Dim dt As DateTime = Now
Try
' Retrieve the document and pull the metadata for reindexing
Dim docReturn As DocumentReturn = DocumentDownloadAdapter.GetDocument(_StorageEndpoint, _NewDocumentContainerName, id)
filename = docReturn.Filename
dt = docReturn.DateAdded
' Get the blob reader for indexing
Dim docReader As IBlobDocumentReader = FileProcessor.GetBlobDocumentReader(docReturn.FileBytes, docReturn.Filename, savePath)
' push the index to the blob storage database
pushIndexDocument(id, filename, dt, docReader, indexer)
sw.Stop()
OnDocumentIndexSuccessful(id, filename, sw.Elapsed)
Return True
Catch ex As EmptyPDFException
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument", ex, "")
' DELETE FILE FROM NEW BLOB INDEX
Try
b.Delete()
Catch exDelete As Exception
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument: Problem Deleting blob", exDelete, "")
End Try
Try
Dim username As String = getDocumentUsername(targetContainer, id)
EmailAdapter.SendExceptionEmail(ex, GetEmailList(ConfigurationHelper.IndexEmailToList), GetEmailList(ConfigurationHelper.IndexEmailCCList), username)
Catch exEmail As Exception
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument: Problem Emailing Exception", exEmail, "")
End Try
Return False
Catch ex As InvalidDocumentTypeException
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument", ex, "")
' DELETE FILE FROM NEW BLOB INDEX
Try
b.Delete()
Catch exDelete As Exception
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument: Problem Deleting blob", exDelete, "")
End Try
Try
Dim username As String = getDocumentUsername(targetContainer, id)
EmailAdapter.SendExceptionEmail(ex, GetEmailList(ConfigurationHelper.IndexEmailToList), GetEmailList(ConfigurationHelper.IndexEmailCCList), username)
Catch exEmail As Exception
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument: Problem Emailing Exception", exEmail, "")
End Try
Return False
Catch ex As Exception
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument", ex.ToString, "")
sw.Stop()
OnDocumentIndexFailed(id, filename, sw.Elapsed, ex)
Return False
End Try
End Function

How to check if sub-folder text file exists

I am trying to search if a text file in a sub-folder exists.
This is the code I am using:
'Checks the program's root folder to see if the root folder exists.
Dim FolderName = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Cake Orders\" & TextBox1.Text))
Dim McKnwoll As String = Path.Combine(FolderName.FullName, Trim(TextBox2.Text) & (" ") & Trim(TextBox3.Text) + ".RTO")
If Not McKnwoll.Exists Then
‘Message to user that file does not exist in sub-folder
Else
‘Message to user that file does exists in sub-folder
End If
I am getting an error that 'Exists' is not a member of 'String'. How can I re-work my code to check if the text file whose name is in the format of "TextBox2.Text & (" ") & TextBox3.Text + ".RTO"; exists.
I am using Visual Basic 2010 Express. Thank you.
File.Exists returns a Boolean indicating whether a file at a certain path exists:
If File.Exists(pathToFile) Then
...
End If
Be sure to include Imports System.IO at the top of your source code file.
You seem quite new in programming. Welcome.
That error message you got ('Exists' is not a member of 'String') tells you exactely what is wrong: You try to ask a string (some text) whether it exists, but what you like to do is to ask a file whether it exists.
The class that provides information about a file is called "FileInfo", and FileInfo has an "Exists" property that you can call:
Dim myFileInfo As New FileInfo(McKnwoll)
If myFileInfo.Exists Then
'do something
End If
That's the object oriented answer, Heinzi's more service oriented one but works, of course, too.
There have been several other small issues I noticed with your code, e.g.
"Cake Orders\" & TextBox1.Text
does not use Path.Combine but makes a string concatenation using fix a "\" as directory separater. Or that the DirectoryInfo is not really used here, the string to the folder is enough.
You also try to handle 3 different issues (reading the values from the user interface, constructing the fullname of the file, checking whether the file exists) in one single code block. I would split them into 3 different ones (actually 4, I would add another one for displaying error messages).
Your simple few lines of codes could be complicated like this ;-)
Imports System.IO
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ReadFileIfPossible(TextBox1.Text, TextBox2.Text, TextBox3.Text)
End Sub
Private Sub ReadFileIfPossible(subfolder As String, part1 As String, part2 As String)
'Get the path to the RTO file
Dim myFilePath As String = Nothing
Try
myFilePath = GetRtoFilePath(subfolder, part1, part2)
Catch ex As Exception
DisplayErrorMessage("Error constructing file name! Please check the values of TextBox1, TextBox2 and TextBox3.")
Return
End Try
'Get the file info
Dim myFile As FileInfo = Nothing
Try
myFile = New FileInfo(myFilePath)
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Check whether it exists
Dim myExists As Boolean = False
Try
myExists = myFile.Exists 'it's IO, everything might throw an exception...
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Display message if not found
If (Not myExists) Then
DisplayErrorMessage("File ""{0}"" could not be found!", myFilePath)
Return
End If
'Read the file
Dim myLines As String() = Nothing
Try
myLines = File.ReadAllLines(myFile.FullName, New UTF8Encoding(True))
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Do something with it...
End Sub
Private Shared Function GetRtoFilePath(subfolder As String, part1 As String, part2 As String) As String
'Check args
If (subfolder Is Nothing) Then Throw New ArgumentNullException("subfolder")
If (part1 Is Nothing) Then Throw New ArgumentNullException("part1")
If (part2 Is Nothing) Then Throw New ArgumentNullException("part2")
'Normalize args
part1 = part1.Trim()
part2 = part2.Trim()
'Build path
Dim myDesktopPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim myFolderPath As String = Path.Combine(myDesktopPath, "Cake Orders")
myFolderPath = Path.Combine(myFolderPath, subfolder)
Dim myFileName As String = String.Format("{0} {1}.RTO", part1, part2)
Dim myResult As String = Path.Combine(myFolderPath, myFileName)
myResult = Path.GetFullPath(myResult)
'Return result
Return myResult
End Function
Private Sub DisplayErrorMessage(message As String, ParamArray args As Object())
Dim myMsg As String = String.Format(message, CType(args, Object()))
MsgBox(myMsg, MsgBoxStyle.OkOnly, "Error")
End Sub
End Class
Have fun.

Coderush plugin not generating correct try catch end try block

We've created a little plugin to add a block of xml comment and create a try-catch to a function. (we simply add this to each and every function we write)
But with the latest devexpress update I'm having a problem with the following code.
Private Sub cpAddComment_Apply(ByVal sender As System.Object, ByVal ea As DevExpress.CodeRush.Core.ApplyContentEventArgs) Handles cpAddXMLCommentAndTryCatch.Apply
' create elementbuilder and add current code to it
Dim objMethod As New Method
objMethod = objOldMethod.Clone()
objElementBuilder.AddStatement(Nothing, objMethod)
' add try
Dim objTry As DevExpress.CodeRush.StructuralParser.Try = objElementBuilder.AddTry(objMethod)
Dim objCatch As DevExpress.CodeRush.StructuralParser.Catch = objElementBuilder.AddCatch(objMethod, "Exception", "ex")
' add exception
Dim strErrorString As String = """Error in " + objMethod.Location + """, ex"
Dim objThrow As New DevExpress.CodeRush.StructuralParser.Throw
Dim objException As New DevExpress.CodeRush.StructuralParser.TypeReferenceExpression("Exception")
Dim objExceptionString As New DevExpress.CodeRush.StructuralParser.PrimitiveExpression(strErrorString)
Dim objNewException As New DevExpress.CodeRush.StructuralParser.ObjectCreationExpression(objException)
objNewException.AddArgument(objExceptionString)
objThrow.Expression = objNewException
'objThrow.AddFooter(" ") 'This isnt working either
objElementBuilder.AddThrow(objCatch, objThrow)
' substitute code
Dim newCode As String = objElementBuilder.GenerateCode()
ea.TextDocument.Replace(objOldMethod.Range, newCode, "Update Method", True)
end sub
Instead of generating a correct Try-catch block it generates the following incorrect code:
Try
Catch ex As Exception
Throw New Exception("Error in test", ex)End Try
Strangely enough the following code seems to work(its about the same code but then for event handlers to show a messagebox instead of an exception)
If not CodeRush.Language.ActiveExtension.DotNetLanguageType = DotNetLanguageType.CSharp Then
Dim objExceptionString As New DevExpress.CodeRush.StructuralParser.PrimitiveExpression("Messagebox.Show(" + strErrorString + ")" + vbCrLf)
objElementBuilder.AddStatement(objCatch, objExceptionString)
Else
This problem exists in Vb.Net but in C# the brackets are correctly placed.
I have reproduced your issue and registered it in DevExpress Support Center. You are welcome to track its status here. Once it is fixed, you can request a build containing the fix from the Support Team at support # devexpress.com. For now, as a work-around, you can replace this line of code:
objThrow.Expression = objNewException
into this:
objThrow.Expression = New SnippetExpression(CodeRush.Language.GenerateExpressionCode(objNewException) + vbCrLf)
This will generate the try/catch block correctly in Visual Basic.

Creating a general SQL module in VB.NET

Hey everyone. I'm fairly new to VB.NET and I'm looking to create a module that will contain all general SQL functionality like connect, disconnect and execute a sql query etc.
I think I'm almost there but the code keeps bombing in one place.
Can anyone see what is wrong with the following code?
It bombs here, setting the command object to a connection object. The opening and closing of the connection works fine.
cmdSystem.Connection = cnSystem
Or maybe I'm just thinking old VB and am going about this all wrong.
Public Module modGeneral
Private cnSystem As New SqlClient.SqlConnection
Private cmdSystem As SqlClient.SqlCommand
Public Sub ConnectToSQL()
Dim sConnectionString As String = "Data Source=SQL;Initial Catalog=XXXX;User ID=XXXX;Password=XXXX"
Try
cnSystem.ConnectionString = sConnectionString
cnSystem.Open()
Catch ex As Exception
End Try
End Sub
Public Sub DisconnectFromSQL()
Try
cnSystem.Close()
cnSystem.Dispose()
Catch ex As Exception
End Try
End Sub
Public Function lExecuteSQL(ByVal sSQL As String) As Long
Dim lRecordsAffected As Long = 0
Try
cmdSystem.Connection = cnSystem
cmdSystem.CommandText = sSQL
lRecordsAffected = cmdSystem.ExecuteNonQuery()
cmdSystem.Dispose()
Catch ex As Exception
End Try
Return lRecordsAffected
End Function
End Module
Thanks in advance.
at some point, you need to instantiate your command object like you did the connection.
have you considered having these functions in a class instead of a module?