reader stopping after first result c# - 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)

Related

iTextSharp edit PDF's based on SQL Query

I need to edit merging PDF's to have a colored bar on each PDF page based on a value in an SQL database where the PDF filename is also stored. I am not great with C# lists but thought perhaps I could build a supplemental list to the iTextSharp "PDFReader" list then when iterating through the PDFReader list write a conditional statement that says "if list 2 value = "Utilities" then create green square" during the PDF merge process.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if ((Session["AccessLevel"].ToString() == "admin") || (Session["AccessLevel"].ToString() == "worker") || (Session["AccessLevel"].ToString() == "client"))
{
if (Request.QueryString["type"] == "QC")
{
//SqlDataSource2.Update();
}
else
{
}
string checkID = Request.QueryString["id"];
SqlDataReader rdr = null;
SqlConnection con2 = new SqlConnection(sqlConnection);
con2.Open();
//string sqlRowCount = "SELECT COUNT(*) FROM [Attachment] WHERE RequestId = '" + checkID + "' AND AttachType != 'Invoice' AND AttachType != 'Cover Sheet' ORDER BY AttachOrder ASC";
sqlUserName2 = "SELECT AttachmentName,AttachType FROM [Attachment] WHERE RequestId = '" + checkID + "' AND AttachType != 'Invoice' AND AttachType != 'Cover Sheet' ORDER BY AttachOrder ASC";
//SqlCommand cmd = new SqlCommand(sqlRowCount, con2);
//string count = cmd.ExecuteScalar().ToString();
SqlCommand cmd2 = new SqlCommand(sqlUserName2, con2);
rdr = cmd2.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
List<PdfReader> readerList = new List<PdfReader>();
List<string> pdfName = new List<string>();
foreach (DataRow row in dt.Rows)
{
PdfReader pdfReader = new PdfReader(Server.MapPath(HttpContext.Current.Request.ApplicationPath + "/uploads/reports/" +
Convert.ToString(row[0])));
readerList.Add(pdfReader);
pdfName.Add(Convert.ToString(row[1]));
//pdfName.Add(rdr["AttachType"].ToString());
}
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Pdf;
Document document = new Document(PageSize.A4, 0, 0, 40, 0);
//Get instance response output stream to write output file.
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
// document.Header = new HeaderFooter(new Phrase("Header Text"), false);
// Parameters passed on to the function that creates the PDF
String headerText = "";
String footerText = "PAGE";
// Define a font and font-size in points (plus f for float) and pick a color
// This one is for both header and footer but you can also create seperate ones
Font fontHeaderFooter = FontFactory.GetFont("arial", 12f);
fontHeaderFooter.Color = Color.BLACK;
// Apply the font to the headerText and create a Phrase with the result
Chunk chkHeader = new Chunk(headerText, fontHeaderFooter);
Phrase p1 = new Phrase(chkHeader);
// create a HeaderFooter element for the header using the Phrase
// The boolean turns numbering on or off
HeaderFooter header = new HeaderFooter(p1, false);
// Remove the border that is set by default
header.Border = Rectangle.NO_BORDER;
// Align the text: 0 is left, 1 center and 2 right.
header.Alignment = 1;
// add the header to the document
document.Header = header;
// The footer is created in an similar way
// If you want to use numbering like in this example, add a whitespace to the
// text because by default there's no space in between them
if (footerText.Substring(footerText.Length - 1) != " ") footerText += " ";
//string newFooter = footerText + pageCount;
Chunk chkFooter = new Chunk(footerText, fontHeaderFooter);
Phrase p2 = new Phrase(chkFooter);
// Turn on numbering by setting the boolean to true
HeaderFooter footer = new HeaderFooter(p2, true);
footer.Border = Rectangle.NO_BORDER;
footer.Alignment = 1;
document.Footer = footer;
Response.Write(pdfName);
Response.Write("test");
// Open the Document for writing and continue creating its content
document.Open();
foreach (PdfReader reader in readerList)
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
if ("if list 2 value = "Utilities" then create green square")
{
PdfContentByte cb = writer.DirectContent;
var rect = new iTextSharp.text.Rectangle(200, 200, 100, 100);
rect.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER;
rect.BorderWidth = 5; rect.BorderColor = new BaseColor(2, 3, 0);
cb.Rectangle(rect);
}
document.Add(iTextSharp.text.Image.GetInstance(page));
}
}
document.Close();
Response.AppendHeader("content-disposition", "inline; filename=" + Request.QueryString["id"] + "-Final");
Response.ContentType = "application/pdf";
con2.Close();
Response.Write(pdfName);
}
}
catch
{
// Response.Redirect("~/PDFProblem.aspx", false);
}
}
This is a bit clunky but it works until I refactor it. I simply iterated the second list (pdfName) within the first iTextSharp one (pdfReader) using an incrementing integer to move the second list forward when the first list did:
foreach (PdfReader reader in readerList)
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
string totalValue = pdfName[nextOne].ToString();
PdfImportedPage page = writer.GetImportedPage(reader, i);
if (totalValue == "Permit")
{
PdfContentByte cb = writer.DirectContent;
var rect = new iTextSharp.text.Rectangle(200, 200, 100, 100);
rect.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER;
rect.BorderWidth = 5; rect.BorderColor = new BaseColor(2, 3, 0);
cb.Rectangle(rect);
}
if (totalValue == "TaxBill")
{
PdfContentByte cb = writer.DirectContent;
var rect = new iTextSharp.text.Rectangle(200, 200, 100, 100);
rect.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER;
rect.BorderWidth = 15; rect.BorderColor = new BaseColor(3, 2, 0);
cb.Rectangle(rect);
}
nextOne = nextOne + 1;
document.Add(iTextSharp.text.Image.GetInstance(page));
}
}

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.

Why my code can't locate the data table?

I have this code below to generate a report. My problem is why one of the content of my data table can't locate by my code? The ds.dt_ProposedSeminars is the table.
public JsonResult ReportProposal(int year)
{
string Userkey = "gHeOai6bFzWskyUxX2ivq4+pJ7ALwbzwF55dZvy/23BrHAfvDVj7mg ";
string PassKey = "lLAHwegN8zdS7mIZyZZj+EmzlkUXkvEYxLvgAYjuBVtU8sw6wKXy2g ";
JsonResult result = new JsonResult();
MemoryStream oStream;
PCSO_ProposedSeminars rpt = new PCSO_ProposedSeminars();
dsPCSO_TrainingProgram ds = new dsPCSO_TrainingProgram();
//-----------------------------------------------------
var seminars = db.Certificates
.Where(x => x.Year.Value.Year == year && !x.IsApproved.HasValue)
.Select(z => z).Distinct();
foreach (var train in seminars)
{
string trainingProgram = train.CertificateName;
string resourcePerson = train.ResourceSpeaker;
string target = "";
var classifications = db.CertificateTrainingClassifications.Where(a => a.CertificateId == train.CertificateId).Select(b=>b.TrainingClassification.Classification);
int x = 1;
foreach (var classification in classifications)
{
if (classifications.Count() > 1)
{
if (x == 1) target += classification;
else target += ", " + classification;
}
else target += classification;
x++;
}
if (train.TargetParticipants.HasValue)
{
target += "/" + train.TargetParticipants.Value + ((train.TargetParticipants != null) ? " pax" : "");
}
if (train.IsPerBatch.Value)
{
target += "/batch";
}
string duration = train.Duration.Value + " days";
decimal estimatedExpenses = new decimal();
estimatedExpenses = train.EstimatedExpenses.Value;
ds.dt_ProposedSeminars.Adddt_ProposedSeminarsRow(
trainingProgram,
resourcePerson,
target,
duration,
estimatedExpenses);
}
DataTable dtable = new DataTable();
dtable = ds.dt_ProposedSeminars;
rpt.SetDataSource(dtable);
rpt.Refresh();
rpt.SetParameterValue(0, year);
rpt.SetParameterValue(1, "");
rpt.SetParameterValue(2, "Head, Training Unit, Admin Department");
oStream = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
string filename = Convert.ToString((DateTime.Now.Month) + Convert.ToString(DateTime.Now.Day) + Convert.ToString(DateTime.Now.Year) + Convert.ToString(DateTime.Now.Hour) + Convert.ToString(DateTime.Now.Minute) + Convert.ToString(DateTime.Now.Second) + Convert.ToString(DateTime.Now.Millisecond)) + "RequestApplication";
var len = oStream.Length;
FileTransferServiceClient client2 = new FileTransferServiceClient();
RemoteFileInfo rmi = new RemoteFileInfo();
DateTime dt = DateTime.Now;
DownloadRequest dr = new DownloadRequest();
string fId = client2.UploadFileGetId("", filename, len, PassKey, Userkey, oStream);
result.Data = new
{
fileId = fId,
filename = filename
};
rpt.Close();
rpt.Dispose();
oStream.Close();
oStream.Dispose();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}
Here is the screenshot:
Here is the error.
'PIMS_Reports.TrainingProgram.dsPCSO_TrainingProgram' does not contain a definition for 'dt_ProposedSeminars' and no extension method 'dt_ProposedSeminars' accepting a first arguement of type
'PIMS_Reports.TrainingProgram.dsPCSO_TrainingProgram' could not be found (are you missing a using directive assembly reference?)
The error message states that your dsPCSO_TrainingProgram class does not contain a method or property named dt_PropsedSeminars.
What does that class look like?

Getting multiple results from one select query

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.

Retrieving elements from the data of type datatable from asp.net webservice in android application

I have a webservice in c# which returns the data in the form of datatable and I want to access the elements of the datatable dt which has 110 rows and 8 columns how can I retrieve each and every row value in my android appliation and display it in the table. Help me Please:
this is my webservice:
[WebMethod(Description = "Webservice for generating category wise report")]
public DataTable getCategoryWiseReport(string district)
{
var con = new SqlConnection("data source=(local);initial catalog=xxxx;integrated security=true");
con.Open();
var cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "ReportSummery";
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt= new DataTable();
SqlDataAdapter ad = new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("#district", district);
cmd.ExecuteNonQuery();
ad.Fill(dt);
//string ofc_code=dt.Rows[0][0].ToString();
//string ofc_desg = dt.Rows[0][1].ToString();
//string ofc_name = dt.Rows[0][2].ToString();
//string dep_name = dt.Rows[0][3].ToString();
//string total_comp = dt.Rows[0][4].ToString();
//string pending = dt.Rows[0][5].ToString();
//string desposed = dt.Rows[0][6].ToString();
//string interim = dt.Rows[0][7].ToString();
//string defaulter = dt.Rows[0][8].ToString();
for (int i = 0; i <= (dt.Rows.Count-1); i++)
{
for (int j = 0; j <= 8; j++)
{
dt.Rows[i][j].ToString();
}
}
con.Close();
return dt;
//string s=ofc_code+","+ofc_desg+","+ofc_name+","+dep_name+","+total_comp+","+pending+","+desposed+","+interim+","+defaulter;
//return s;
}
StringBuilder JSON = new StringBuilder();
JSON.append("{");
JSON.append("\"Customers\":[");
for (int i = 0; i <= (dt.Rows.Count-1); i++)
{
//dt.Rows[i][j].ToString();
JSON.append("{");
JSON.append("\"ofc_code\":\"" +dt.Rows[i].ofc_code.tostring() + "\", ");
JSON.append("\"ofc_desg \":\"" + dt.Rows[i].ofc_desg.tostring() + "\" ");
JSON.append("\"ofc_name \":\"" +dt.Rows[i].ofc_name.tostring() + "\", ");
JSON.append("\"dep_name \":\"" + dt.Rows[i].dep_name.tostring() + "\" ");
JSON.append("\"total_comp \":\"" +dt.Rows[i].total_comp.tostring() + "\", ");
JSON.append("\"pending \":\"" + dt.Rows[i].pending.tostring() + "\" ");
JSON.append("\"desposed \":\"" +dt.Rows[i].desposed.tostring() + "\", ");
JSON.append("\"interim \":\"" + dt.Rows[i].interim.tostring() + "\" ");
JSON.append("\"defaulter \":\"" + dt.Rows[i].defaulter.tostring() + "\" ");
JSON.append("},");
}
if (JSON.ToString().EndsWith(","))
JSON = JSON.Remove(JSON.Length - 1, 1);
JSON.append("]}");
In Android part
private static final String METHOD_NAME = "sayHello";// give the method name
private static final String NAMESPACE = "http://ws.android.com/";// give ur namespace
private static final String URL = "http://175.157.229.119:8080/ wsdl";// provide URL
private static final String SOAP_ACTION = METHOD_NAME+ NAMESPACE ;
private static final String Customers= "Customers";
private static final String ofc_code= "ofc_code";
private static final String ofc_desg = "ofc_desg ";
private static final String ofc_name = "ofc_name ";
private static final String dep_name = "dep_name ";
private static final String total_comp = "total_comp ";
private static final String pending = "pending ";
private static final String desposed = "desposed ";
private static final String interim = "interim ";
private static final String defaulter = "defaulter ";
ArrayList<HashMap<String, String>> contactList;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
final String JSON= response.toString();
try {
JSONObject jsonObj = new JSONObject(JSON);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray(Customers);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// tmp hashmap for single contact
HashMap<String, String> contactdata = new HashMap<String, String>();
// adding each child node to HashMap key => value
contactdata.put(ofc_code, c.getString(ofc_code));
contactdata.put(ofc_desg , c.getString(ofc_desg));
contactdata.put(ofc_name , c.getString(ofc_name));
contactdata.put(dep_name , c.getString(dep_name));
contactdata.put(total_comp , c.getString(total_comp));
contactdata.put(pending , c.getString(pending));
contactdata.put(desposed , c.getString(desposed));
contactdata.put(interim, c.getString(interim));
contactdata.put(defaulter , c.getString(defaulter ));
// adding contact to contact list
contactList.add(contactdata);
}
} catch (JSONException e) {
e.printStackTrace();
}
Download ksoap ( download ksoap2 jar file).
1st you need to customize ur webservice, u need to make it as JSON string, following is the code u can use in android part
private static final String METHOD_NAME = "sayHello";// give the method name
private static final String NAMESPACE = "http://ws.android.com/";// give ur namespace
private static final String URL = "http://175.157.229.119:8080/ wsdl";// provide URL
private static final String SOAP_ACTION = METHOD_NAME+ NAMESPACE ;
private static final String ofc_code= "ofc_code";
private static final String ofc_desg = "ofc_desg ";
private static final String ofc_name = "ofc_name ";
private static final String dep_name = "dep_name ";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
final String str = response.toString();
try {
JSONObject jsonObj = new JSONObject(str);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(ofc_code);
String name = c.getString(ofc_desg );
String email = c.getString(ofc_name );
String address = c.getString(dep_name );
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}

Categories