Lucene Update not working Index Writer - vb.net

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

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.

upload files to dropbox using dropbox api

i'm working in a console app that is going to be executed in a server every week, basically it generates a report in excel and then it has to upload it to a folder in dropbox, i've trying a lot of stuff for that last part i finally got this code that does not work but doesn't throw any exception (before i had one that throw and invalid folder format)
Dim _path As String
_path = "/Pruebas/" & Path.GetFileName(FilePath)
Try
Dim rawData = File.ReadAllBytes(FilePath)
Dim str = System.Text.Encoding.Default.GetString(rawData)
Using mem = New MemoryStream(Encoding.UTF8.GetBytes(str))
Dim Up = I.Files.UploadAsync(_path, body:=mem)
MsgBox("Successfully Uploaded")
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
it doesn't throw exception but also doens't work, any help i'll be thankfull.
try this.
Dim Up = I.Files.UploadAsync(_path, WriteMode.Overwrite.Instance, body:=mem)
Link to documentation: http://dropbox.github.io/dropbox-sdk-dotnet/html/M_Dropbox_Api_Files_Routes_FilesUserRoutes_UploadAsync_1.htm

File.Copy not working - no error

Please take a look at this code. For some reason that I can't figure out, the File.Delete() line isn't getting fired and I'm not getting an error.
' hard-coded for testing
Dim path As String = "C:\Program Files (x86)\Test\Program\Program.exe"
Dim appDir As String = My.Application.Info.DirectoryPath
Dim iniPath As String = appDir & "\config.ini"
Dim outputPath As String = appDir & "\output.ini"
Dim textLine As String = ""
Dim reader = File.OpenText(iniPath)
Dim writer = New StreamWriter(outputPath)
' Read the lines in the ini file until the pathToExecutable line is found and write the path to that line
While (InlineAssignHelper(textLine, reader.ReadLine())) IsNot Nothing
If textLine.StartsWith("pathToExecutable=") Then
writer.WriteLine("pathToExecutable=" & path)
Else
writer.WriteLine(textLine)
End If
End While
reader.Dispose()
reader.Close()
writer.Dispose()
writer.Close()
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Return path
You stated that you are not getting an error, but if you don't implement exception handling, you're most probably getting errors and throwing them away (pun intended).
Use a try/catch around any of your System.IO.File operations, and even more, you can implement specific handles and catch specific exceptions.
Try
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Catch ioException As IOException
'The specified file is in use.
MessageBox.Show(ioException.Message)
Catch ex As Exception
'Some other error apart for file in use.
MessageBox.Show(ex.Message)
End Try
Ericosg's suggestion about using a try/catch lead me to the issue: I had the file open in a streamreader earlier in my code, but never closed it there.

FileExist not working vb.net

I really can not understand why the exception is triggered.
I created this code that performs some checks for the correctness of the license.
The function isittrial occurs if the trial software is creating a hidden file, this file is then checked with File.exist.
The problem is the following:
the file is created by isittrial but for some strange reason you enable the exception of file.exist, what can I do to fix it?
I really can not understand why it does not work.
isittrial() 'this function make the file to check
Dim percorsoCompleto As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
Try
If My.Computer.FileSystem.FileExists(directory) Then
Dim fileReader As String
Dim dire As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
fileReader = My.Computer.FileSystem.ReadAllText(directory,
System.Text.Encoding.UTF32)
Dim check = DeCryptIt(fileReader, "aspanet")
Dim datadecripted As String = DeCryptIt(Registry.GetValue("HKEY_CURRENT_USER\Software\cc", "end", ""), "aspanet")
If Date.Now < check And check <> datadecripted Then
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
Else
End If
Else
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
End If
Catch ex As Exception
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
'DeActivate()
'ForceActivation()
End Try
This line
If My.Computer.FileSystem.FileExists(directory) Then
seems to test for the existence of a file passing the name of a directory (or an empty string or whatever, we can see how this variable is initialized). In every case the result will be false.
Then your code jumps to an else block with the same error message of the exception fooling your perception of the error.
Try instead
Dim percorsoCompleto As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
percorsoCompleto = Path.Combine(percorsoCompleto, "Software", "cc.txt")
Try
If My.Computer.FileSystem.FileExists(percorsoCompleto) Then
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(percorsoCompleto,
System.Text.Encoding.UTF32)
.....
Notice that I have removed the path concatenation with a more fail safe call to Path.Combine

Getting a list of users on a network domain

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