Getting multiple results from one select query - c#

So I am stuck with my code and have thoroughly tried looking for an answer.
I have 1 select statement that brings about 52806 results.
I put the result of the query I run in variables and then put it into a PDF file i make. After the first result it doesn't work. I want to make it so that it puts the results in my pdf file and then goes to the next result.
if anyone can help me id appreciate it a lot.
Here is my code. Sorry for the bad practice in advance.
private void CreateBtn_Click(object sender, EventArgs e)
{
try
{
make_pdf();
}
catch (Exception exe )
{
MessageBox.Show("failed");
}
}
public static void make_pdf()
{
string Contact = "";
string emailAddress = "";
string Tel = "";
string InvoiceDate = "";
string address = "";
string Reference = "";
string AccountNo = "";
string Debit = "";
string Credit = "";
string refnum = "";
string connetionString = null;
MySqlConnection cnn;
connetionString = "server=********;user id=web_support;database=users;password=!w3b_supp0rt~;persistsecurityinfo=True";
cnn = new MySqlConnection(connetionString);
try
{
cnn.Open();
// MessageBox.Show("Connection Open ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
try
{
MySqlDataReader reader = null;
string selectCmd = "SELECT accounting.code,users.curr_email , users.physicaddr ,accounting.date , accounting.refnum , users.telephone , accounting.debit , accounting.acc_pdf, accounting.credit, accounting.reference, users.contact, accounting.transnum FROM accounting INNER JOIN users ON accounting.code = users.code WHERE(accounting.transtype = 1)";
MySqlCommand command = new MySqlCommand(selectCmd, cnn);
reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.HasRows)
{
//get account number
AccountNo = reader["code"].ToString();
//get emailaddress
emailAddress = reader["curr_email"].ToString();
//get Contact Name
Contact = reader["contact"].ToString();
//get telephone number
Tel = reader["telephone"].ToString();
//Get Date
InvoiceDate = reader["date"].ToString();
//Get reference
Reference = reader["reference"].ToString();
//Get Address
address = reader["physicaddr"].ToString();
//Get Debit
Debit = reader["debit"].ToString();
//Get Credit
Credit = reader["credit"].ToString();
//Get Refnum
refnum = reader["refnum"].ToString();
// MessageBox.Show(address+" "+Reference+" "+InvoiceDate+" "+emailAddress+" "+AccountNo+" "+Contact);
// Make The PDF File
Document NewDoc = new Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
PdfWriter pdfwri = PdfWriter.GetInstance(NewDoc, new FileStream("text.pdf", FileMode.Create));
NewDoc.Open();
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("intsa_header_small.jpg");
// Paragraph par = new Paragraph("Everything is working");
//Account List
List AccountNolist = new List(List.UNORDERED);
AccountNolist.SetListSymbol("");
AccountNolist.IndentationLeft = 300f;
AccountNolist.Add(new ListItem("AccountNo " + AccountNo));
// AddressList
List AddressList = new List(List.UNORDERED);
AddressList.SetListSymbol("");
AddressList.IndentationLeft = 300f;
AddressList.Add(new ListItem("Address: " + address));
#region Emailaddresslist
//EmailAddressList
List emailAddresslist = new List(List.UNORDERED);
emailAddresslist.SetListSymbol("");
emailAddresslist.IndentationLeft = 300f;
emailAddresslist.Add(new ListItem("Email address: " + emailAddress));
#endregion
//ContactList
List Contactlist = new List(List.UNORDERED);
Contactlist.SetListSymbol("");
Contactlist.IndentationLeft = 300f;
Contactlist.Add(new ListItem("Contact: " + Contact));
//TelephoneList
List Telephonelist = new List(List.UNORDERED);
Telephonelist.SetListSymbol("");
Telephonelist.IndentationLeft = 300f;
Telephonelist.Add(new ListItem("Tel: " + Tel));
// Make a Table
PdfPTable General_Table = new PdfPTable(1);
General_Table.SpacingBefore = 50f;
General_Table.SpacingAfter = 50f;
PdfPCell Caption = new PdfPCell(new Phrase("Description"));
PdfPCell Body = new PdfPCell(new Phrase(" " + refnum + " " + Reference + " Debit: " + Debit + " Credit: " + Credit));
Body.HorizontalAlignment = Element.ALIGN_RIGHT;
Caption.Colspan = 0;
Caption.HorizontalAlignment = 1;
General_Table.AddCell(Caption);
General_Table.AddCell(Body);
// NewDoc.Add(par);
//add Image to pdf
NewDoc.Add(img);
//add accountNo to pdf
NewDoc.Add(AccountNolist);
//add Contact to pdf
NewDoc.Add(Contactlist);
//add emailaddress to pdf
NewDoc.Add(emailAddresslist);
//add Telephone Number to pdf
NewDoc.Add(Telephonelist);
//add address to pdf
NewDoc.Add(AddressList);
NewDoc.Add(General_Table);
//save Pdf
NewDoc.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

The problem is you are creating the PDF file in the while loop, I don't think you want 52k PDF files, so you should create the PDF file first, then loop through all of the results and paste them into the file.
EDIT: I would suggest adding line to insert/update PDF to database after
NewDoc.Close();
Then deleting the local file (text.pdf) before running loop again.

Related

c# - How to call/link a workflow on a web application from a c# program?

I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.

reader stopping after first result c#

Ok, so i have written code to make a PDF file using Itextsharp and variables from a select statement. and updates into a database. the reader has to return multiple results with the query that i have made. for some reason it stops after the first result.
can anyone tell me what i need to change to make it iterate through each row that has been returned and update it to the database within in the while loop.
here is my code.
public Form1()
{
InitializeComponent();
}
private void CreateBtn_Click(object sender, EventArgs e)
{
try
{
make_pdf();
MessageBox.Show("completed");
}
catch (Exception exe )
{
MessageBox.Show("failed");
}
}
public void vaiabless()
{
}
public static void make_pdf()
{
string Contact = "";
string emailAddress = "";
string Tel = "";
string InvoiceDate = "";
string address = "";
string Reference = "";
string AccountNo = "";
string Debit = "";
string Credit = "";
string refnum = "";
string transtype = "";
string breaker = "|";
string connetionString = null;
MySqlConnection cnn;
connetionString = "*************";
cnn = new MySqlConnection(connetionString);
try
{
cnn.Open();
// MessageBox.Show("Connection Open ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
try
{
MySqlDataReader reader = null;
string selectCmd = "SELECT accounting.code,users.curr_email , users.physicaddr ,accounting.date , accounting.refnum , accounting.transtype, users.telephone , accounting.debit , accounting.acc_pdf, accounting.credit, accounting.reference, users.contact, accounting.transnum FROM accounting INNER JOIN users ON accounting.code = users.code WHERE(accounting.transtype = 1)";
MySqlCommand createcommand = new MySqlCommand(selectCmd, cnn);
reader = createcommand.ExecuteReader();
while (reader.Read())
{
if (reader.HasRows)
{
//get account number
AccountNo = reader["code"].ToString();
//get emailaddress
emailAddress = reader["curr_email"].ToString();
transtype = reader["transtype"].ToString();
//get Contact Name
Contact = reader["contact"].ToString();
//get telephone number
Tel = reader["telephone"].ToString();
//Get Date
InvoiceDate = reader["date"].ToString();
//Get reference
Reference = reader["reference"].ToString();
//Get Address
address = reader["physicaddr"].ToString();
//Get Debit
Debit = reader["debit"].ToString();
//Get Credit
Credit = reader["credit"].ToString();
//Get Refnum
refnum = reader["refnum"].ToString();
MemoryStream ms = new MemoryStream();
byte[] bits = new byte[0];
// Make The PDF File
Document NewDoc = new Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
PdfWriter pdfwri = PdfWriter.GetInstance(NewDoc,ms);
NewDoc.Open();
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("intsa-header.jpg");
img.ScaleAbsolute(596f, 100f);
//Account List
List AccountNolist = new List(List.UNORDERED);
AccountNolist.SetListSymbol("");
AccountNolist.IndentationLeft = 300f;
AccountNolist.Add(new ListItem("AccountNo " + AccountNo));
// AddressList
List AddressList = new List(List.UNORDERED);
AddressList.SetListSymbol("");
AddressList.IndentationLeft = 300f;
AddressList.Add(new ListItem("Address: " + address));
#region Emailaddresslist
//EmailAddressList
List emailAddresslist = new List(List.UNORDERED);
emailAddresslist.SetListSymbol("");
emailAddresslist.IndentationLeft = 300f;
emailAddresslist.Add(new ListItem("Email address: " + emailAddress));
#endregion
//ContactList
List Contactlist = new List(List.UNORDERED);
Contactlist.SetListSymbol("");
Contactlist.IndentationLeft = 300f;
Contactlist.Add(new ListItem("Contact: " + Contact));
//TelephoneList
List Telephonelist = new List(List.UNORDERED);
Telephonelist.SetListSymbol("");
Telephonelist.IndentationLeft = 300f;
Telephonelist.Add(new ListItem("Tel: " + Tel));
// Make a Table
#region pdftable
//PdfPTable General_Table = new PdfPTable(1);
//General_Table.SpacingBefore = 50f;
//General_Table.SpacingAfter = 50f;
//PdfPCell Caption = new PdfPCell(new Phrase("Description"));
//PdfPCell Body = new PdfPCell(new Phrase(" " + refnum + " "+ Reference + " Total Due: " + Debit ));
//Body.HorizontalAlignment = Element.ALIGN_RIGHT;
//Caption.Colspan = 0;
//Caption.HorizontalAlignment = 1;
//General_Table.AddCell(Caption);
//General_Table.AddCell(Body);
PdfPTable mytable = new PdfPTable(3);
mytable.SpacingBefore = 40f;
Paragraph accountpar = new Paragraph("Description");
accountpar.IndentationLeft = 200f;
accountpar.SpacingBefore = 30f;
accountpar.SpacingAfter = 10f;
Paragraph Referencepar = new Paragraph( Reference);
Referencepar.IndentationLeft = 200f;
Referencepar.SpacingBefore = 30f;
Referencepar.SpacingAfter = 10f;
Paragraph Totalpar = new Paragraph("Total Due:" + "R" + Debit);
Totalpar.IndentationLeft = 200f;
Totalpar.SpacingBefore = 30f;
Totalpar.SpacingAfter = 10f;
Paragraph Refnumpar = new Paragraph("Reference Num: "+refnum);
Refnumpar.IndentationLeft = 150f;
Refnumpar.SpacingBefore = 10f;
Refnumpar.SpacingAfter = 30f;
mytable.AddCell(Refnumpar);
mytable.AddCell(Referencepar);
mytable.AddCell(Totalpar);
#endregion
//add Image to pdf
NewDoc.Add(img);
//add accountNo to pdf
NewDoc.Add(AccountNolist);
//add Contact to pdf
NewDoc.Add(Contactlist);
//add emailaddress to pdf
NewDoc.Add(emailAddresslist);
//add Telephone Number to pdf
NewDoc.Add(Telephonelist);
//add address to pdf
NewDoc.Add(AddressList);
//NewDoc.Add(accountpar);
//NewDoc.Add(Supscriptionpar);
NewDoc.Add(mytable);
//save Pdf
NewDoc.Close();
bits = ms.ToArray();
string updateCmd = "UPDATE users.accounting SET acc_pdf = #acc_pdf WHERE refnum =" + refnum;
MySqlConnection cnnx;
connetionString = "****************";
cnnx = new MySqlConnection(connetionString);
MySqlCommand Updatecommand = new MySqlCommand(updateCmd, cnnx);
Updatecommand.Parameters.AddWithValue("#acc_pdf", bits);
cnnx.Open();
Updatecommand.ExecuteNonQuery();
cnnx.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Try to change the order of your statements like given on msdn's example for the MySqlDataReader:
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
Also check what #Cameron Tinker asked:
Does the query return more than one result if you run it on the
database directly?
And to avoid resource leaks, don't forget to close the reader with reader.Close(); and also the connections. (or better use the using keyword)

c# Retrieve multiple XML child nodes

I've managed to link up a single XElement successfully into my program though I'm not having any luck with the other two I have in place, I've tried using;
IEnumerable query = from booking in doc.Descendants("Booking")
Though I've haven't had much luck placing the values into list box.
Here's the code for function:
private void btnimport_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.CheckFileExists = true;
open.InitialDirectory = "#C:\\";
open.Filter = "XML Files (*.xml)|*.xml|All Files(*.*)|*.*";
open.Multiselect = false;
if (open.ShowDialog() == DialogResult.OK)
{
try
{
XDocument doc = XDocument.Load(open.FileName);
//Grabs the customer elements
var query = from booking in doc.Descendants("Booking")
select new
{
//Customer Elements
CustomerId = booking.Element("CustomerId").Value,
Title = booking.Element("Title").Value,
Firstname = booking.Element("FirstName").Value,
Lastname = booking.Element("LastName").Value,
DateofBirth = booking.Element("DateofBirth").Value,
Email = booking.Element("Email").Value,
HouseNo = booking.Element("HouseNo").Value,
Street = booking.Element("Street").Value,
Postcode = booking.Element("Postcode").Value,
Town = booking.Element("Town").Value,
County = booking.Element("County").Value,
ContactNo = booking.Element("ContactNo").Value,
//Holiday Elements
HolidayId = booking.Element("HolidayId").Value,
HotelName = booking.Element("HotelName").Value,
Location = booking.Element("Location").Value,
BookFrom = booking.Element("BookFrom").Value,
BookTo = booking.Element("BookTo").Value,
CheckInTime = booking.Element("CheckInTime").Value,
CheckOutTime = booking.Element("CheckOutTime").Value,
NoOfRoomsBooked = booking.Element("NoOfRoomsBooked").Value,
RoomType = booking.Element("RoomType").Value,
RoomServices = booking.Element("RoomServices").Value,
Parking = booking.Element("Parking").Value,
Pet = booking.Element("Pet").Value,
//TravelInfo Elements
TravelInfoId = booking.Element("TravelInfoId").Value,
TravellingFrom = booking.Element("TravellingFrom").Value,
Destination = booking.Element("Destination").Value,
Fare = booking.Element("Fare").Value,
TravelInsurance = booking.Element("TravelInsurance").Value,
InFlightMeals = booking.Element("In-FlightMeals").Value,
LuggageAllowance = booking.Element("LuggageAllowance").Value,
ExtraLuggage = booking.Element("ExtraLuggage").Value,
CarHire = booking.Element("CarHire").Value,
ReturnTransfer = booking.Element("ReturnTransfer").Value,
};
//Inputs all of the values in bookings
foreach (var booking in query)
{
//Customer values
txtCustomerId.Text = txtCustomerId.Text + booking.CustomerId;
txttitle.Text = txttitle.Text + booking.Title;
txtfname.Text = txtfname.Text + booking.Firstname;
txtlname.Text = txtlname.Text + booking.Lastname;
txtdob.Text = txtdob.Text + booking.DateofBirth;
txtemail.Text = txtemail.Text + booking.Email;
txthouseno.Text = txthouseno.Text + booking.HouseNo;
txtstreet.Text = txtstreet.Text + booking.Street;
txtpostcode.Text = txtpostcode.Text + booking.Postcode;
txttown.Text = txttown.Text + booking.Town;
txtcounty.Text = txtcounty.Text + booking.County;
txtcontactno.Text = txtcontactno.Text + booking.ContactNo;
//Holiday Values
txtHolidayId.Text = txtHolidayId.Text + booking.HolidayId;
txthname.Text = txthname.Text + booking.HotelName;
txtl.Text = txtl.Text + booking.Location;
txtbf.Text = txtbf.Text + booking.BookFrom;
txtbt.Text = txtbt.Text + booking.BookTo;
txtcit.Text = txtcit.Text + booking.CheckInTime;
txtcot.Text = txtcot.Text + booking.CheckOutTime;
txtnorb.Text = txtnorb.Text + booking.NoOfRoomsBooked;
txtrt.Text = txtrt.Text + booking.RoomType;
txtrs.Text = txtrs.Text + booking.RoomServices;
txtpark.Text = txtpark.Text + booking.Parking;
txtpet.Text = txtpet.Text + booking.Pet;
//TravelInfo Values
txtTravelInfoId.Text = txtTravelInfoId.Text + booking.TravelInfoId;
txttf.Text = txttf.Text + booking.TravellingFrom;
txtd.Text = txtd.Text + booking.Destination;
txtf.Text = txtf.Text + booking.Fare;
txtti.Text = txtti.Text + booking.TravelInsurance;
txtifi.Text = txtifi.Text + booking.InFlightMeals;
txtla.Text = txtla.Text + booking.LuggageAllowance;
txtel.Text = txtel.Text + booking.ExtraLuggage;
txtch.Text = txtch.Text + booking.CarHire;
txtrtrans.Text = txtrtrans.Text + booking.ReturnTransfer;
}
MessageBox.Show("XML has been imported");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
If anyone knows where I've gone wrong or what I need to add / change please let me know :)
Many thanks,
10gez10
You have several problems:
Firstly, your data elements are not immediate children of the booking element, there are intermediate elements <Customer>, <Holiday> and <TravelInfo>. Thus you need to do something like
var query = from booking in doc.Descendants("Booking")
let customer = booking.Element("Customer")
let holiday = booking.Element("Holiday")
let travelInfo = booking.Element("TravelInfo")
select new
{
//Customer Elements
CustomerId = customer.Element("CustomerId").Value,
Title = customer.Element("Title").Value,
HolidayId = holiday.Element("HolidayId").Value,
TravelInfoId = travelInfo.Element("TravelInfoId").Value,
}
Secondly, several elements are misspelled:
CheckOutTime should be CheckoutTime
In-FlightMeals should be InFlightMeals.
CarHire should be CareHire (yes "CareHire" is what's in the XML.)
Thus, when you do (e.g.) Element("In-FlightMeals").Value, Element() is returning null so you get a null reference exception and your code is aborted.
Thirdly, the element BookTo is completely missing, so BookTo = holiday.Element("BookTo").Value generates a null reference exception.
More generally, I do not recommend this coding approach. If any of your XML elements are missing, your query will throw an exception because element.Element("name") will be null. What's worse, Visual Studio doesn't seem to report an accurate line number on which the null reference occurs, instead giving the line number of the select new statement. And (on my version at least), it's not possible to step into the constructor for an anonymous type either. This makes debugging well-nigh impossible.
Instead, skip the intermediate anonymous type and do things in a more direct, traditional manner:
foreach (var booking in doc.Descendants("Booking"))
{
var customer = booking.Element("Customer");
var holiday = booking.Element("Holiday");
var travelInfo = booking.Element("TravelInfo");
XElement element;
if (customer != null)
{
if ((element = customer.Element("CustomerId")) != null)
txtCustomerId.Text = txtCustomerId.Text + element.Value;
}
// And so on.
}

How do I use lucene.net for searching file content?

I am currently using lucene.net to search the content of files for keyword search. I am able to get the results correctly but I have a scenario where I need to display the keywords found in a particular file.
There are two different files containing "karthik" and "steven", and if I search for "karthik and steven" I am able to get both the files displayed. If I search only for "karthik" and "steven" separately, only the respective files are getting displayed.
When I search for "karthik and steven" simultaneously I get both the files in the result as I am displaying the filename alone, and now I need to display the particular keyword found in that particular file as a record in the listview.
Public bool StartSearch()
{
bool bResult = false;
Searcher objSearcher = new IndexSearcher(mstrIndexLocation);
Analyzer objAnalyzer = new StandardAnalyzer();
try
{
//Perform Search
DateTime dteStart = DateTime.Now;
Query objQuery = QueryParser.Parse(mstrSearchFor, "contents", objAnalyzer);
Hits objHits = objSearcher.Search(objQuery, objFilter);
DateTime dteEnd = DateTime.Now;
mlngTotalTime = (Date.GetTime(dteEnd) - Date.GetTime(dteStart));
mlngNumHitsFound = objHits.Length();
//GeneratePreviewText(objQuery, mstrSearchFor,objHits);
//Generate results - convert to XML
mstrResultsXML = "";
if (mlngNumHitsFound > 0)
{
mstrResultsXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Results>";
//Loop through results
for (int i = 0; i < objHits.Length(); i++)
{
try
{
//Get the next result
Document objDocument = objHits.Doc(i);
//Extract the data
string strPath = objDocument.Get("path");
string strFileName = objDocument.Get("name");
if (strPath == null) { strPath = ""; }
string strLastWrite = objDocument.Get("last_write_time");
if (strLastWrite == null)
strLastWrite = "unavailable";
else
{
strLastWrite = DateField.StringToDate(strLastWrite).ToShortDateString();
}
double dblScore = objHits.Score(i) * 100;
string strScore = String.Format("{0:00.00}", dblScore);
//Add results as an XML row
mstrResultsXML += "<Row>";
//mstrResultsXML += "<Sequence>" + (i + 1).ToString() + "</Sequence>";
mstrResultsXML += "<Path>" + strPath + "</Path>";
mstrResultsXML += "<FileName>" + strFileName + "</FileName>";
//mstrResultsXML += "<Score>" + strScore + "%" + "</Score>";
mstrResultsXML += "</Row>";
}
catch
{
break;
}
}
//Finish off XML
mstrResultsXML += "</Results>";
//Build Dataview (to bind to datagrid
DataSet objDS = new DataSet();
StringReader objSR = new StringReader(mstrResultsXML);
objDS.ReadXml(objSR);
objSR = null;
mobjResultsDataView = new DataView();
mobjResultsDataView = objDS.Tables[0].DefaultView;
}
//Finish up
objSearcher.Close();
bResult = true;
}
catch (Exception e)
{
mstrError = "Exception: " + e.Message;
}
finally
{
objSearcher = null;
objAnalyzer = null;
}
return bResult;
}
Above is the code i am using for search and the xml i am binding to the listview, now i need to tag the particular keywords found in the respective document and display it in the listview as recordsss,simlar to the below listview
No FileName KeyWord(s)Found
1 Test.Doc karthik
2 Test2.Doc steven
i hope u guys undesrtood the question,
This depends on how your documents were indexed. You'll need to extract the original content, pass it through the analyzer to get the indexed tokens, and check which matches the generated query.
Just go with the Highlighter.Net package, part of contrib, which does this and more.

How can I insert an Blank Line using a Open XML SDK class

I want format my .doc file, because when I retrive information and save in a .doc format using Open XML SDK, the document with all information is just in one line, and I need some information in other lines, just to format.
How can I do that?
This is my method that build an .doc
private static void BuildDocument(string fileName, string id, string conteudo)
{
Utilidade.QuebraToken tk2 = new Utilidade.QuebraToken();
////id = id.Remove(id.Length - 1);
string select3 = "SELECT San_Imovel.TextoAnuncio, San_Imovel.Filial_Id, San_Imovel.NomeBairro,San_Imovel.TipoDsc1,San_Imovel.Imovel_Id,San_Filial.NomeFantasia ,San_ContatoFilial.Contato " +
"FROM San_Imovel " +
"JOIN San_Filial ON San_Imovel.Filial_Id = San_Filial.Filial_id " +
"JOIN San_ContatoFilial ON San_Filial.Filial_Id = San_ContatoFilial.Filial_Id " +
"WHERE Imovel_Id IN (" + id + ") " +
" AND San_ContatoFilial.TipoContatoFilial_Id = 1";
using (WordprocessingDocument w = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
MainDocumentPart mp = w.AddMainDocumentPart();
DocumentFormat.OpenXml.Wordprocessing.Document d = new DocumentFormat.OpenXml.Wordprocessing.Document();
Body b = new Body();
DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
Run r = new Run();
Text t = new Text();
t.Text = conteudo;
r.Append(t);
p.Append(r);
b.Append(p);
HeaderPart hp = mp.AddNewPart<HeaderPart>();
string headerRelationshipID = mp.GetIdOfPart(hp);
SectionProperties sectPr = new SectionProperties();
HeaderReference headerReference = new HeaderReference();
headerReference.Id = headerRelationshipID;
headerReference.Type = HeaderFooterValues.Default;
sectPr.Append(headerReference);
b.Append(sectPr);
d.Append(b);
hp.Header = BuildHeader(hp, "Anuncio");
hp.Header.Save();
mp.Document = d;
mp.Document.Save();
w.Close();
}
}
And here, I call this method
public static object GerarDoc(string id, string email, string veiculo)
{
try
{
id = id.Remove(id.Length - 1);
string conteudo = string.Empty;
string select3 = "SELECT San_Imovel.TextoAnuncio, San_Imovel.Filial_Id, San_Imovel.NomeBairro,San_Imovel.TipoDsc1,San_Imovel.Imovel_Id,San_Filial.NomeFantasia ,San_ContatoFilial.Contato " +
"FROM San_Imovel " +
"INNER JOIN San_Filial ON San_Imovel.Filial_Id = San_Filial.Filial_id " +
"INNER JOIN San_ContatoFilial ON San_Filial.Filial_Id = San_ContatoFilial.Filial_Id " +
"WHERE Imovel_Id IN (" + id + ") " +
"AND San_ContatoFilial.TipoContatoFilial_Id = 1 ";
Utilidade.Conexao c3 = new Utilidade.Conexao();
SqlConnection con3 = new SqlConnection(c3.Con);
SqlCommand cmd3 = new SqlCommand(select3, con3);
con3.Open();
SqlDataReader r3 = cmd3.ExecuteReader();
while (r3.Read())
{
conteudo = conteudo + "" + (r3["Contato"]) + "";
conteudo = conteudo + "\n"+ (r3["NomeBairro"]);
conteudo = conteudo + "\n" + (r3["TipoDsc1"]) ;
conteudo = conteudo + "\n" + (r3["NomeFantasia"]) + " (" + (r3["Imovel_Id"]) + ") " + (r3["TextoAnuncio"]) + "\n\n";
}
con3.Close();
Random rnd = new Random (DateTime.Now.Millisecond);
string NomeArquivo = "Anuncio_" + Credenciada + "_" + Usuario + "_" + rnd.Next().ToString();
rng.Font.Name = "Arial";
rng.Text = conteudo;
BuildDocument(#"C:\inetpub\wwwroot\galileu.redenetimoveis.com\Anuncios\" + NomeArquivo + ".doc", id, rng.Text);
retorno = "1";
}
}
You can simply create a run with a break object in it and insert this run in your code everytime a page break is required, please see below for an example:
using (WordprocessingDocument package = WordprocessingDocument.Create("D:\\LineBreaks.docx", WordprocessingDocumentType.Document))
{
package.AddMainDocumentPart();
Run run1 = new Run();
Text text1 = new Text("The quick brown fox");
run1.Append(text1);
Run lineBreak = new Run(new Break());
Run run2 = new Run();
Text text2 = new Text("jumps over a lazy dog");
run2.Append(text2);
Paragraph paragraph = new Paragraph();
paragraph.Append(new OpenXmlElement[] { run1, lineBreak, run2 });
Body body = new Body();
body.Append(paragraph);
package.MainDocumentPart.Document = new Document(new Body(body));
}
Create your desired document manually and then reflect it Using Open XML productivity tool. so you can find what you need to do.

Categories