Lucene.net: Separate building Index from Searching the Index - asp.net

I created a website but i have a problem.
i want to build once an index und use it.
at the moment i have two functions "create a document an store it into the directory" and "searching"
when the user submit:
sub submit ()
create_doc()
search(text)
end sub
this works, but when i try this:
create_doc()
sub submit()
search(text)
end sub
it's like the directory has been deleted.
global:
Dim analyzer As StandardAnalyzer = New StandardAnalyzer()Dim directory As Directory = FSDirectory.GetDirectory("C:\[...]luceneindex", True)
Dim indexwriter As IndexWriter = New IndexWriter(directory, analyzer, True)
Sub create_doc()
Dim meindoc As New Document()
im feldbodytext As Field = New Field("bodytext", textstring[...]
meindoc.Add(feldbodytext)
indexwriter.AddDocument(meindoc)
indexwriter.Close()
end sub
Sub lucene_search(ByVal strSuchbegriff As String)
Dim parser As QueryParser = New QueryParser("bodytext", analyzer)
Dim query As Query = parser.Parse(strSuchbegriff)
Dim hits As Hits = searcher.Search(query)
[...]
end sub
Is there a possibility to store the index permanently?
could there be a problem init. the index writer gloabel, but close it local?

I think your problem is that each time you declare your IndexWriter, the index is being re-created and the contents of the index erased - this is because of the 3rd parameter being passed into the constructor (True):
Dim indexwriter As IndexWriter = New IndexWriter(directory, analyzer, True)
You should instead use False, to indicate that the existing contents of the index should remain unchanged:
Dim indexwriter As IndexWriter = New IndexWriter(directory, analyzer, False)

ahh, i think i've got it ;-)
the first time i create a index i have to use
Dim directory As Directory = FSDirectory.GetDirectory("C:\[...]\luceneindex", True)
Dim indexwriter As IndexWriter = New IndexWriter("C:\[...]luceneindex", analyzer, True)
and after indexing i have to use both with "False".
True everytimes creates an index?
thanks =)

Related

Open XML SDK Open and Save not working

I am having trouble with the Open XML SDK opening and saving word documents.
I am using the following code (VB.Net):
Try
'Set Path
Dim openPath As String = "../Documents/" & worddoc
Dim savePath As String = "\\web-dev-1\HR_Documents\" & worddoc
Using doc As WordprocessingDocument = WordprocessingDocument.Open("/Documents/" & worddoc, True)
'Employee Name Insert
'Find first table in document
Dim tbl1 As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table).First()
'First Row in tbl
Dim row As TableRow = tbl1.Elements(Of TableRow)().ElementAt(0)
'Find first cell in row
Dim cell As TableCell = row.Elements(Of TableCell)().ElementAt(0)
'Insert selected Employee Name
Dim p As Paragraph = cell.Elements(Of Paragraph)().First()
Dim r As Run = p.Elements(Of Run)().First()
Dim txt As Text = r.Elements(Of Text)().First()
txt.Text = ddlEmployeeList.SelectedItem.Text
'Save File
'Supervisor Name Insert
'Find second table in document
Dim tbl2 As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table).First()
'First Row in tbl
Dim row2 As TableRow = tbl2.Elements(Of TableRow)().ElementAt(0)
'Find first cell in row
Dim cell2 As TableCell = row2.Elements(Of TableCell)().ElementAt(0)
'Insert selected Employee Name
Dim p2 As Paragraph = cell2.Elements(Of Paragraph)().First()
Dim r2 As Run = p2.Elements(Of Run)().First()
Dim txt2 As Text = r2.Elements(Of Text)().First()
txt2.Text = ddlSupervisorList.SelectedItem.Text
End Using
Return 1
Catch ex As Exception
Return Nothing
End Try
The trouble starts on the first using statement. It throws the following error:
Could not find a part of the path 'C:\Documents\Hourly_Employee_Performance_Review .docx
I have placed the word documents in a folder of the ASP.NET site called Documents. I also have created a public share on the dev server to see if maybe that would help.
The problem is that it doesn't use the supplied path variable. I have gone through the documentation for OPEN XMl SDK but all it talks about is the Using Statement and its need and use for it.
Can anyone tell me, show me, or point to a site that has examples of how to set both the open path and save path?
You need a path to the file which is based on the filesytem, not a URL. You can do that with
Dim openPath As String = Path.Combine(Server.MapPath("~/Documents"), worddoc)
And then to open the file:
Using doc As WordprocessingDocument = WordprocessingDocument.Open(openPath, True)
It appears that you will need to do the same for the location to save to, but you didn't say if "\\web-dev-1" is a different server; if it were that would need other considerations.
(Not tested, some typos may exist. You will need an Imports System.IO.)

Search files based on the date modified entered by user in console application VB.NET

i been given a assignment to create one console application using VB.NET. The assignment will able to open the file that based on the date modified entered by user. can anyone help me to solve my problem. I'm new in vb.net and most of the tutorial are using C# . together i put the latest code i has already done but still if i put the date modified the error file will display .
Thank you in advance
Imports System.IO
Module Module3
Sub Main()
While True
' Read value.
Dim s As DateTime = Console.ReadLine()
' Test the value.
If s = File.GetLastWriteTime("path") Then
Dim p As New Process()
p.StartInfo = New ProcessStartInfo("notepad.exe", "path")
p.Start()
Else
Dim p As New Process()
p.StartInfo = New ProcessStartInfo("notepad.exe", "path2")
p.Start()
End If
' Write the value.
Console.WriteLine("You typed " + s)
End While
End Sub
End Module
in the code snippet you are not searching for a file you are setting the time last modified which isn't what you want to do.
you will need to search through each file until you find the date modified information which is inputted by the user:-
dim s as datetime = console.readline()
'Target Directory
Dim directory = "C:\Users\Peter\Desktop\TestFolder\"
For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
Dim fName As String = IO.Path.GetExtension(filename)
dim datemod as string = File.GetLastWriteTime(directory & fname)
If s = datemod Then
Dim p As New Process()
p.StartInfo = New ProcessStartInfo("notepad.exe", directory & fname)
p.Start()
Else
'do something else
endif
next
things that you will need to add are, what to do when it doesn't find a file with that variable.
hope this gets you a little further.

Rename Sharepoint folder using ClientContext

been stuck for this for a while. I need to rename a SharePoint folder using ClientContext. I created a function like so:
Public Function renameFolder(_folders As ListItemCollection, _newFolderName As String) As Boolean
Try
Using _clientContext As New ClientContext(vSharepointSite)
AddHandler _clientContext.ExecutingWebRequest, AddressOf vClaimsHelper.clientContext_ExecutingWebRequest
Dim _folder = _folders(0)
_folder.Item("Title") = _newFolderName
_folder.Item("FileLeafRef") = _newFolderName
_folder.Item("DisplayName") = _newFolderName
_folder.Update()
_clientContext.ExecuteQuery()
End Using
Return True
Catch ex As Exception
Return False
End Try
End Function
This function takes a folder collection (actually I pass a collection of only 1 folder) and the new folder name. The function executes well. Inspecting the _folder after the ExecuteQuery, everything looks as expected. However nothing happens in SharePoint, meaning that the folder name remains the original name.
Any suggestions?
Best regards and....HAPPY NEW YEAR!!!!
Ariel
Make sure List Item ( _folder variable in your example) is associated with Folder object.
How to determine whether List Item is associated with a Folder object
Using ctx As New ClientContext(webUrl)
Dim list = ctx.Web.Lists.GetByTitle(listTitle)
Dim item = list.GetItemById(itemId)
ctx.Load(item.Folder)
ctx.ExecuteQuery()
Dim isFolderItem = Not item.Folder.ServerObjectIsNull.Value
End Using
How to rename Folder using SharePoint CSOM
The following example demonstrates how to rename a Folder:
Public Sub RenameFolder(folder As Folder, folderName As String)
Dim ctx = folder.Context
Dim folderItem = folder.ListItemAllFields
folderItem("FileLeafRef") = folderName
folderItem("Title") = folderName
folderItem.Update()
ctx.ExecuteQuery()
End Sub
Usage
Using ctx As New ClientContext(webUrl)
Dim folder = ctx.Web.GetFolderByServerRelativeUrl(folderUrl)
RenameFolder(folder, "Orders")
End Using
Use the BaseName field to rename the folder.
_folder.Item("BaseName") = _newFolderName

cannot convert string to date

Hello stack overflow residents! this is my first post and i'm hoping to receive some help.
I've searched but because I'm still very new, i was not able to full find/understand my answer.
I keep encountering this error:
Message: Conversion from string "" to type 'Date' is not valid. File:
~/reports/pendingshipments.aspx Function: btnExportXls_Click Stack
Trace: at
Microsoft.VisualBasic.CompilerServices.Conversions.ToDate(String
Value) at reports_default.btnExportXls_Click(Object sender, EventArgs
e) in C:\Users\jet.jones\Documents\ERIRoot\ERITitan\ERITitan.ssa\Web
Application\reports\pendingshipments.aspx.vb:line 75
Here is my code:
on App_code
**Public Function Reports_PendingShipments(ByVal intClientID As Integer, ByVal strMinDate As Date?, ByVal strMaxDate As Date?, ByVal xmlSiteID As String) As DataTable
'=================================================================================
' Author: Jet Jones
' Create date: 2013.05.28
' Description: Returns a data table with pending shipments for the sites specified
'=================================================================================
Dim objConn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("Titan").ToString)
Dim cmdGet As New SqlCommand("spReports_PendingShipments", objConn)
Dim parClientID As New SqlParameter("#ClientID", SqlDbType.Int)
Dim parMinDate As New SqlParameter("#MaxDate", IIf(Not strMinDate.HasValue, DBNull.Value, strMinDate))
Dim parMaxDate As New SqlParameter("#MaxDate", IIf(Not strMaxDate.HasValue, DBNull.Value, strMaxDate))
Dim parSiteID As New SqlParameter("#Sites", SqlDbType.Xml)
Dim objAdapter As New SqlDataAdapter(cmdGet)
Dim objTable As New DataTable
parClientID.Value = intClientID
parMinDate.Value = strMinDate
parMaxDate.Value = strMaxDate
parSiteID.Value = xmlSiteID
'set up the command object
cmdGet.Connection = objConn
cmdGet.CommandType = CommandType.StoredProcedure
'add the parameters
cmdGet.Parameters.Add(parClientID)
cmdGet.Parameters.Add(parMinDate)
cmdGet.Parameters.Add(parMaxDate)
cmdGet.Parameters.Add(parSiteID)
'open the connection
objConn.Open()
'execute the query and fill the data table
objAdapter.Fill(objTable)
'return the data table
Reports_PendingShipments = objTable
'clean up
objConn.Close()
objConn = Nothing
End Function**
my aspx.vb page calls this function this way (Get the values from the query):
objTable = Reports_PendingShipments(ucClientSearch.Value,
txtMinDate.Text, txtMaxDate.Text, strSites)
I'm passing the variable strSites because the website permissions allow for users to have access to one or more site locations, and if a report is run and the user selects "All Sites" from the dropdown, I only want to send the sites they have permissions to via XML.
If I'm missing any information please let me know!
anyone's prompt response is so greatly appreciated.
The problem is that your code is expecting empty dates to be NULL, it doesn't check for empty strings. You need something like this:
if len(strMinDate)=0 then
strMinDate = "01/01/1980"
end
Not sure what you want to default the minimum date to, but you need to add code similar to the IF statement above
Be sure to add this code prior to using the variable a few lines later...
First of all, you adding MaxDate parameter twice:
Dim parMinDate As New SqlParameter("#MaxDate", IIf(Not strMinDate.HasValue, DBNull.Value, strMinDate))
Dim parMaxDate As New SqlParameter("#MaxDate", IIf(Not strMaxDate.HasValue, DBNull.Value, strMaxDate))
And moreover, then you setting parameters values wuthout check for HasValue:
parMinDate.Value = strMinDate
parMaxDate.Value = strMaxDate
Remove these lines and fix min date parameter name

Can't find file

I'm working on a custom menu system in asp.net that populates a horizontal menu on the fly based on which menu item is selected from the website's main menu.
This 2nd menu is populated from a custom XML file in the website's root directory.
(See http://loganyoung.wordpress.com/2010/06/03/asp-net-horizontal-submenu-from-xml/ for details).
At the time I'd written that post, it did work, but my development environment has changed and now I'm getting an error saying that the XML file can't be found.
Here's my code:
Imports System.Xml
Partial Class Site
Inherits System.Web.UI.MasterPage
Protected Sub Menu1_MenuItemClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MenuEventArgs) Handles Menu1.MenuItemClick
Select Case e.Item.Value.ToString
Case "Team"
Dim doc As New XmlDocument
doc.Load("~/Submenus.xml")
Dim NameNodes As XmlNodeList = doc.SelectNodes("/TeamMenu/item/name")
Dim URLNodes As XmlNodeList = doc.SelectNodes("/TeamMenu/item/url")
If NameNodes.Count = URLNodes.Count Then
For i As Integer = 0 To NameNodes.Count - 1
Dim m As New MenuItem
m.Text = NameNodes.Item(i).FirstChild.InnerText
m.NavigateUrl = URLNodes.Item(i).FirstChild.InnerText
Menu2.Items.Add(m)
Next
End If
Case "Investments"
Dim doc As New XmlDocument
doc.Load("~/Submenus.xml")
Dim NameNodes As XmlNodeList = doc.SelectNodes("/InvestmentsMenu/item/name")
Dim URLNodes As XmlNodeList = doc.SelectNodes("/InvestmentsMenu/item/url")
If NameNodes.Count = URLNodes.Count Then
For i As Integer = 0 To NameNodes.Count - 1
Dim m As New MenuItem
m.Text = NameNodes.Item(i).FirstChild.InnerText
m.NavigateUrl = URLNodes.Item(i).FirstChild.InnerText
Menu2.Items.Add(m)
Next
End If
Case "Social Responsibility"
Dim doc As New XmlDocument
doc.Load("~/Submenus.xml")
Dim NameNodes As XmlNodeList = doc.SelectNodes("/InvestmentsMenu/item/name")
Dim URLNodes As XmlNodeList = doc.SelectNodes("/InvestmentsMenu/item/url")
If NameNodes.Count = URLNodes.Count Then
For i As Integer = 0 To NameNodes.Count - 1
Dim m As New MenuItem
m.Text = NameNodes.Item(i).FirstChild.InnerText
m.NavigateUrl = URLNodes.Item(i).FirstChild.InnerText
Menu2.Items.Add(m)
Next
End If
End Select
End Sub
End Class
And here's the error I'm getting:
Could not find a part of the path 'c:\windows\system32\inetsrc\~\Submenus.xml'.
Menu2 is just a completely empty <asp:Menu> control directly under the main menu on the page.
Can someone tell me what I'm doing wrong please?
Thanks in advance.
XmlDocument.Load is expecting a file path where you are providing a virtual path. Try changing it to this:
doc.Load(Page.MapPath("~/Submenus.xml"))
If you use doc.Load("~/Submenus.xml") this xml must be in your project. Otherwise you have to use server.mappath.

Resources