How to pass two MySQL id's to c#.exe? - c#

I am trying to make a PDF form filling program. The program should get 2 id's from the PHP script, search the MySQL database, and fill the forms with info based of those two id's, but i cant make the PHP script pass arguments to the c# executable. Maybe u can help me out :)
PHP script :
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("documente", $con);
$idfirma;
$idagent;
$sql="SELECT * FROM `agenti` WHERE `Nume Agent` = '$_GET[numea]'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo "Date agent"."<br>";
echo $row['Nume Agent'];echo " | ";echo $row['Sigiliu'];echo " | ";echo $row['Legitimatie']."<br>"."<br>"."<br>"."<br>"."<br>";
$idagent=$row['ID'];
}
$sql1="SELECT * FROM `dateclienti` WHERE `Cod Fiscal` = '$_GET[codf]'";
$result = mysql_query($sql1);
while($row = mysql_fetch_array($result)) {
echo "Date Firma"."<br>";
echo $row['Nume Societate'];echo " | ";echo $row['Adresa Sediu'];echo " | ";echo $row['Cod Fiscal']."<br>";
$idfirma=$row['ID'];
}
exec("pdfgen\PdfGenerator\bin\Debug\PdfGenerator.exe $idfirma, $idagent 2>&1");
echo $idfirma."<br>"."<br>";
echo $idagent;
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con)
?>
c# scipt :
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using System.IO;
using MySql.Data.MySqlClient;
namespace PdfGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FillForm();
ListFieldNames();
}
/// <summary>
/// List all of the form fields into a textbox. The
/// form fields identified can be used to map each of the
/// fields in a PDF.
/// </summary>
private void ListFieldNames()
{
string pdfTemplate = #"C:\xampp\htdocs\site\pdfgen\PdfGenerator\form.pdf";
// title the form
this.Text += " - " + pdfTemplate;
// create a new PDF reader based on the PDF template document
PdfReader pdfReader = new PdfReader(pdfTemplate);
// create and populate a string builder with each of the
// field names available in the subject PDF
StringBuilder sb = new StringBuilder();
foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)
{
sb.Append(de.Key.ToString() + Environment.NewLine);
}
// Write the string builder's content to the form's textbox
textBox1.Text = sb.ToString();
textBox1.SelectionStart = 0;
}
private void FillForm()
{
string idagent1 = null;
string idfirma1 = null;
string[] args = System.Environment.GetCommandLineArgs();
if(args.Length !=0)
{
idfirma1 = args[1];
idagent1 = args[2];
}
using (var connection = new MySqlConnection("server = localhost; User Id = root; password = ; database = documente;"))
{
connection.Open();
string agenti = "SELECT `Nume Agent` FROM `agenti` WHERE `ID` = #id";
string name1 = null;
using (var cmd = new MySqlCommand(agenti, connection))
{
cmd.Parameters.AddWithValue("#id", idagent1);
MySqlDataReader rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow row in dt.Rows)
{
string name = row["Nume Agent"].ToString();
name1 = name;
}
string pdfTemplate = #"C:\xampp\htdocs\site\pdfgen\PdfGenerator\form.pdf";
string newFile = #"C:\xampp\htdocs\site\pdfgen\PdfGenerator\completed_form.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(
newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
// set form pdfFormFields
// The first worksheet and W-4 form
pdfFormFields.SetField("topmostSubform[0].Page1[0].regcomert[0]", name1);
// flatten the form to remove editting options, set it to false
// to leave the form open to subsequent manual edits
pdfStamper.FormFlattening = true;
// close the pdf
pdfStamper.Close();
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace PdfGenerator
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

Related

I'm trying to import an excel file to SQL via visual Studio. How do I make it read the data starting from the second row?

I'm trying to import an excel file to SQL server via visual Studio. How do I make it read the data starting from the second row and not the first row of the excel file? My code works perfectly as it is, but I want it to start reading the data from the 2nd row. Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using ExcelDataReader;
namespace ImportDB2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ope = new OpenFileDialog();
ope.Filter = "Excel Files|*.xls; *.xlsx; *.xlsm";
if (ope.ShowDialog() == DialogResult.Cancel)
return;
FileStream stream = new FileStream(ope.FileName, FileMode.Open);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
DataClasses1DataContext conn = new DataClasses1DataContext();
foreach (DataTable table in result.Tables)
{
foreach (DataRow dr in table.Rows)
{
Employee addtable = new Employee()
{
Serial = Convert.ToInt32(dr[0]),
Name = Convert.ToString(dr[1]),
Class = Convert.ToString(dr[2]),
Department = Convert.ToString(dr[3]),
Status = Convert.ToString(dr[4]),
Position = Convert.ToString(dr[5]),
Email = Convert.ToString(dr[6])
};
conn.Employees.InsertOnSubmit(addtable);
}
}
conn.SubmitChanges();
excelReader.Close();
stream.Close();
MessageBox.Show("YEEESSSS FINALLY");
}
}
}
What line of code should I put for it to start reading on the second row, and where inside my code should I put it in? Hope someone can help, thank you. ^_^
bool skip = true;
foreach (DataRow dr in table.Rows)
{
if(skip)
{
skip = false;
continue;
}
If you just want to skip a row in your for loop for each table, do this:
foreach (DataTable table in result.Tables)
{
bool skippedRow = false;
foreach (DataRow dr in table.Rows)
{
if (!skippedRow)
{
skippedRow = true;
continue;
}
Employee addtable = new Employee()
{
Serial = Convert.ToInt32(dr[0]),
Name = Convert.ToString(dr[1]),
Class = Convert.ToString(dr[2]),
Department = Convert.ToString(dr[3]),
Status = Convert.ToString(dr[4]),
Position = Convert.ToString(dr[5]),
Email = Convert.ToString(dr[6])
};
conn.Employees.InsertOnSubmit(addtable);
}
}

Removing a row from a csv file when it is selected from a comboBox and a button pressed

I recently asked about a piece of code to hold data for my trading cards. I have a file that contains the overall list of the cards in a CSV file. I was wondering if there was any way to remove a row from the CSV file when the card number is selected and the submit button pressed. The code I currently have is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace YuGiOh_Card_List
{
public partial class frmAddLOB : Form
{
List<string> cardNo = new List<string>();
List<string> cardName = new List<string>();
List<string> cardRarity = new List<string>();
List<string> cardType = new List<string>();
public frmAddLOB()
{
InitializeComponent();
StreamReader reader = File.OpenText("..\\Debug\\lobList.csv");
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
cardNo.Add(values[0]);
cardName.Add(values[1]);
cardRarity.Add(values[2]);
cardType.Add(values[3]);
cboCardNo.Items.Add(values[0]);
}
reader.Close();
}
private void cboCardNo_SelectedIndexChanged(object sender, EventArgs e)
{
lblCardNoFinal.Text = cardNo[cboCardNo.SelectedIndex];
lblCardNameFinal.Text = cardName[cboCardNo.SelectedIndex];
lblCardRarityFinal.Text = cardRarity[cboCardNo.SelectedIndex];
lblCardTypeFinal.Text = cardType[cboCardNo.SelectedIndex];
}
private void btnAdd_Click(object sender, EventArgs e)
{
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text);
Global.card.Add(card);
File.AppendAllLines(file, new[] { card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter + card.CardType });
MessageBox.Show("Card Added");
}
}
}
So I want the row to be removed from the 'loblist.csv' and added to the LOB file (which it is currently doing). Thanks
This should work (untested). Unfortunately, there's no classes/methods available in .Net (AFAIK) for in-place editing of text files (it makes sense when you think about it I guess). Disclaimer - there are much cleaner ways to do what you're aiming for here functionality-wise, including the approach described by Plutonix above:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace YuGiOh_Card_List
{
public partial class frmAddLOB : Form
{
List<string> cardNo = new List<string>();
List<string> cardName = new List<string>();
List<string> cardRarity = new List<string>();
List<string> cardType = new List<string>();
List<string> Lines = new List<string>();
public frmAddLOB()
{
InitializeComponent();
StreamReader reader = File.OpenText("..\\Debug\\lobList.csv");
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
Lines.Add(line);
cardNo.Add(values[0]);
cardName.Add(values[1]);
cardRarity.Add(values[2]);
cardType.Add(values[3]);
cboCardNo.Items.Add(values[0]);
}
reader.Close();
}
private void cboCardNo_SelectedIndexChanged(object sender, EventArgs e)
{
lblCardNoFinal.Text = cardNo[cboCardNo.SelectedIndex];
lblCardNameFinal.Text = cardName[cboCardNo.SelectedIndex];
lblCardRarityFinal.Text = cardRarity[cboCardNo.SelectedIndex];
lblCardTypeFinal.Text = cardType[cboCardNo.SelectedIndex];
}
private void btnAdd_Click(object sender, EventArgs e)
{
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text,
lblCardTypeFinal.Text);
Global.card.Add(card);
var newLine = card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter +
card.CardType;
File.AppendAllLines(file,
new string [] {newLine});
if (Lines.Contains(newLine))
{
Lines.Remove(newLine);
File.WriteAllLines("..\\Debug\\lobList.csv", Lines);
}
MessageBox.Show("Card Added");
}
}
}

C# Second text box filling out with random names

this is my code and I also have a snippet in the link below of what my program looks like when run. My problem is with the second text box and that it is filling out with random gibberish. My first text box is working perfectly it is picking a random first name from my text file and putting it into the text box. I dont understand what my second text file isnt doing the same'?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
{
Random r = new Random();
int currentLinefirst = 1;
string pick = null;
foreach (string line in File.ReadLines("C:\\Users\\Admin\\Desktop\\C# Programs\\WindowsFormsApplication5\\WindowsFormsApplication5\\First Names.txt"))
{
if (r.Next(currentLinefirst) == 0)
{
pick = line;
}
++currentLinefirst;
}
textBox1.Text = pick;
}
Random n = new Random();
int currentLinelast = 1;
string pick2 = null;
foreach (string line1 in File.ReadLines("C:\\Users\\Admin\\Desktop\\C# Programs\\WindowsFormsApplication5\\WindowsFormsApplication5\\Last Names.txt"))
{
if (n.Next(currentLinelast) == 0)
{
pick2 = line1;
}
++currentLinelast;
}
textBox2.Text = pick2;
}
}
}
i am getting this output of random numbers in textbox
It is probably because your second file contains a line with multiple names. When you call File.ReadLines, it will return an array of string on each line
Try separating you last names with line feeds.
To save the text to a text file use
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\Admin\Desktop\test.txt", true))
{
file.WriteLine("First Name: {0} Last Name: {1}", textBox1.Text, textBox2.Text);
}
{0} and {1} are placeholders
if the file is does not exist it will create a new file to the given path and if the file already exists then it will add new entry to the file.
You can try this:
string firstname = textBox1.Text;
string lastname = textBox2.Text;
Byte[] info = new UTF8Encoding(true).GetBytes(firstname + lastname);
string FilePath = yourpath + DateTime.Now.ToString("dd-MMM-yyyy") + ".txt";
using (FileStream fs = File.Create(FilePath))
{fs.Write(info, 0, info.Length);}

c# Oledb excel to txt, how to also recognize letters?

I have an application which uses open file dialog to open an excel file and then convert it to .txt and it works fine, almost. Currently it can only read tables with only numbers in them but I need to add a function so that it could also read letters. What should I change to make it able to read letters/words as well as numbers?
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
}
private void BtnFileOpen_Click(object sender, RoutedEventArgs e)
{
var fileDialog = new System.Windows.Forms.OpenFileDialog();
var result = fileDialog.ShowDialog();
switch (result)
{
case System.Windows.Forms.DialogResult.OK:
var file = fileDialog.FileName;
TxtFile.Text = file;
TxtFile.ToolTip = file;
break;
case System.Windows.Forms.DialogResult.Cancel:
default:
TxtFile.Text = null;
TxtFile.ToolTip = null;
break;
}
}
public void convert_Click(object sender, RoutedEventArgs e)
{
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
exportExcelToTxt(TxtFile.Text, filename);
}
}
static void exportExcelToTxt(string excelFilePath, string outputTxtPath)
{
Dictionary<string, List<long>> values = new Dictionary<string, List<long>>();
using (OleDbConnection excelConnection = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 XML;HDR=YES\"", excelFilePath)))
{
excelConnection.Open();
string firstSheet = getFirstSheetName(excelConnection);
using (OleDbCommand cmd = excelConnection.CreateCommand())
{
cmd.CommandText = string.Format("SELECT * FROM [{0}]", firstSheet);
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt); // Getting all the data in the sheet
foreach (DataRow item in dt.Rows)
{
List<long> toAdd = new List<long>();
string key = item[0] as string;
for (int i = 1; i < dt.Columns.Count; i++)
{
toAdd.Add(Convert.ToInt64(item[i]));
}
values.Add(key, toAdd); // Associating all the "numbers" to the "Name"
}
}
}
}
}
StringBuilder toWriteToTxt = new StringBuilder();
foreach (KeyValuePair<string, List<long>> item in values)
{
// Formatting the output
toWriteToTxt.Append(string.Format("{0}:", item.Key));
foreach (long val in item.Value.Distinct())
{
toWriteToTxt.AppendFormat("\t{0} * {1}\r\n", item.Value.Where(f => f == val).Count(), // Amount of occurrencies of each number
val);
}
}
// Writing the TXT
using (FileStream fs = new FileStream(outputTxtPath, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(toWriteToTxt.ToString());
}
}
}
static string getFirstSheetName(OleDbConnection excelConnection)
{
using (DataTable ExcelTables = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" }))
{
return ExcelTables.Rows[0]["TABLE_NAME"].ToString();
}
}
}
}
You should not convert the values to long in this line:
toAdd.Add(Convert.ToInt64(item[i]));
Also replace all List<long> with List<string>, this should cover pretty much the issue.

Printing rdlc report without preview in web application in IIS mode

There is code in MSDN for printing rdlc without preview in web application but it does not work when i implement in IIS...is there any solution for this ....or any code which work in on print of rdlc without preview
here is the link http://msdn.microsoft.com/en-us/library/ms252091.aspx
It does not give any exception but also does not print the report
on MSDN they said create a console application but I need it in asp.net web application which run in IIS.
using System;
using System.IO;
using System.Data;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Collections.Generic;
using Microsoft.Reporting.WebForms;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Windows.Forms;
///<summary>
/// Summary description for Printing
/// this is the cool code found on MSDN site to print labels out without preview
/// abhay maini
///</summary>
publicclassPrinting : IDisposable
{
public Printing()
{
//
// TODO: Add constructor logic here
//
}
publicint m_currentPageIndex;
publicIList<Stream> m_streams;
// Routine to provide to the report renderer, in order to
// save an image for each page of the report.
publicStream CreateStream(string name,string fileNameExtension, Encoding encoding,string mimeType, bool willSeek)
{
string CurrentDrive;
CurrentDrive = Application.StartupPath.ToString();Stream stream = newFileStream("C:\\Labels\\" + name + "." + fileNameExtension, FileMode.Create);
m_streams.Add(stream);
return stream;
}
publicvoid Export(LocalReport report)
{
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>EMF</OutputFormat>" +
" <PageWidth>4.0in</PageWidth>" +
" <PageHeight>2.0in</PageHeight>" +
" <MarginTop>0.00in</MarginTop>" +
" <MarginLeft>0.00in</MarginLeft>" +
" <MarginRight>0.00in</MarginRight>" +
" <MarginBottom>0.00in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;m_streams = newList<Stream>();
report.Render("Image", deviceInfo, CreateStream, out warnings);
foreach (Stream stream in m_streams)
stream.Position = 0;
}
// Handler for PrintPageEvents
publicvoid PrintPage(object sender, PrintPageEventArgs ev)
{
Metafile pageImage = newMetafile(m_streams[m_currentPageIndex]);
ev.Graphics.DrawImage(pageImage, ev.PageBounds);
m_currentPageIndex++;
ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
}
publicvoid Print(string PrinterName)
{
// const string printerName = PrinterName;
if (m_streams == null || m_streams.Count == 0)
return;
PrintDocument printDoc = newPrintDocument();
printDoc.PrinterSettings.PrinterName = PrinterName;
if (!printDoc.PrinterSettings.IsValid)
{
string msg = String.Format(
"Can't find printer \"{0}\".", PrinterName);
MessageBox.Show(msg, "Print Error");return;
}
printDoc.PrintPage += newPrintPageEventHandler(PrintPage);
printDoc.Print();
}
// Create a local report for Report.rdlc, load the data,
// export the report to an .emf file, and print it.
publicvoid Run(string ReportName, string PrinterName, DataTable MyDataTable,string DSstring)
{
LocalReport report = newLocalReport();
report.ReportPath = ReportName;
report.DataSources.Clear();
report.DataSources.Add(newReportDataSource(DSstring, MyDataTable));
Export(report);
m_currentPageIndex = 0;
Print(PrinterName);
}
publicvoid Dispose()
{
if (m_streams != null)
{
foreach (Stream stream in m_streams)
stream.Close();
m_streams = null;
}
}
}
The above class can be called as below behind text change event:
protectedvoid TxtScanId_TextChanged(object sender, EventArgs e)
{
string sqlPrintScanID = "SELECT [ScanID], [LoadID], [tempVRMA], [CustPalletID], [TypeOfAsset] FROM [SerialScanDetail] WHERE [ScanID]=" + TxtScanId.Text + "";
string strConnection = ConfigurationManager.ConnectionStrings["RevisionConnectionString"].ToString();
SqlConnection conn = newSqlConnection(strConnection);
SqlDataAdapter da = newSqlDataAdapter();
da.SelectCommand = newSqlCommand(sqlPrintScanID, conn);
DataSet ds = newDataSet();
da.Fill(ds, "RevisionDataSet_SerialScanDetail");
//ReportViewer1.LocalReport.Refresh();
NewPrinting.Run(#"Reports\Report_ScanID.rdlc", "Eltron 2442", ds.Tables[0], "RevisionDataSet_SerialScanDetail");
}
I would suggest making use of the ReportViewer class.
ReportViewer reportViewer = new ReportViewer();
reportViewer.LocalReport.ReportPath = "ReportPath";
reportViewer.LocalReport.DataSources.Add(new ReportDataSource("data", data));
byte[] byteInfo;
byteInfo = reportViewer.LocalReport.Render("Image", deviceInfo, CreateStream, out warnings);
MemoryStream ms = new MemoryStream(byteInfo);
Image returnImage = Image.FromStream(ms);
returnImage is then an image data type that you can display/print.
I see you making a call to render but not assigning the value to use, this combined with not using a report viewer could be the problem.
The reason MSDN suggest making a console application is that it is a good idea to do a proof of concept in a basic program such as a console, get the result you want, then port that code into your desired environment.

Categories