iText7 Align cut of a product description - c#

I am trying to print a bill of sale, it works fine for me. But I have a problem, I don't know how to make the product description appear aligned, under the cut I make to print the rest of the description on a new line.
The full description is: "Aloe Vera Coco 12 x 1500 ml"
I leave the image and the code that prints the detail.
Someone who knows iText well and tell me how to solve this detail.
Thank you all
private void SetDetalles()
{
// 1 2 3 4 5
// 12345678901234567890123456789012345678901234567890
// "Cant Descripcion 000000000 000000000"
// --------------------------------------------------
SetLineaDivisora();
string linea = "Cant Descripcion Precio Total";
SetTextoNormal(linea);
SetLineaDivisora();
int maxLenLine = 25;
string descpart = "";
foreach (DetallesPDF det in detalles)
{
string descripcion = det.Descripcion;
if (maxLenLine > descripcion.Length)
{
descpart = descripcion.PadRight(25);
descripcion = "";
linea = det.Cantidad.ToString().PadRight(4) + " " +
descpart + " " +
det.Precio.ToString("N0").PadLeft(9) + " " +
det.TotalItem.ToString("N0").PadLeft(9);
SetTextoNormal(linea);
}
else
{
bool lflag = true;
descpart = descripcion.Substring(0, maxLenLine);
do
{
if (lflag)
{
linea = det.Cantidad.ToString().PadRight(4) + " " +
descpart + " " +
det.Precio.ToString("N0").PadLeft(9) + " " +
det.TotalItem.ToString("N0").PadLeft(9);
descripcion = descripcion.Substring(maxLenLine);
lflag = false;
}
else
{
descpart = descripcion.Substring(0);
linea = $" {descpart}"; // --> Add 5 blanks so it will be aligned, but the line break shows it on the left side.
descripcion = descripcion.Replace(descpart, "");
}
SetTextoNormal(linea);
}
while (descripcion.Trim().Length > 0);
}
}
SetLineaDivisora();
}
Function that generates the sale detail item
private void SetTextoNormal(string linea, float separacion = 0.2f, bool centrado = false)
{
Paragraph header = new Paragraph(linea)
//.SetTextAlignment(TextAlignment.LEFT)
.SetMultipliedLeading(separacion)
.SetFontSize(7)
.SetFont(currierNew);
if (centrado)
header.SetTextAlignment(TextAlignment.CENTER);
miDocumento.Add(header);
}

Related

Can I incorporate error handling into my API?

I have an API that loops through addresses and cleanses them. I am testing it with about 40k addresses, and it takes several hours to loop through thousands of them. Sometimes it throws an error and closes out the application and I have to start it over. Is there a way that I can write in error handling into the catch, that if there is an error, it will just log it, but continue running the app?
I am using VS 2019, C#, Windows Forms.
public class Elements
{
public string streetaddress1 { get; set; }
public string streetaddress2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public string country { get; set; }
}
void Output(string strDebugText)
{
try
{
System.Diagnostics.Debug.Write(strDebugText + Environment.NewLine);
txtResponse.Text = txtResponse.Text + strDebugText + Environment.NewLine;
txtResponse.SelectionStart = txtResponse.TextLength;
txtResponse.ScrollToCaret();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
}
private void btnMultiple_Click(object sender, EventArgs e)
{
//Loads address that need to be cleansed
string filePath = #"C:data.csv";
List<Elements> addresses = new List<Elements>();
List<string> lines = File.ReadAllLines(filePath).ToList();
foreach (var line in lines)
{
string[] entries = line.Split(',');
Elements newElement = new Elements();
newElement.streetaddress1 = entries[0];
newElement.streetaddress2 = entries[1];
newElement.city = entries[2];
newElement.state = entries[3];
newElement.zip = entries[4];
addresses.Add(newElement);
}
foreach (var Element in addresses)
{
Output($"{ Element.streetaddress1 } { Element.city} { Element.state } { Element.zip } " +
$"{ Element.country }");
var venvMulti = new AreaLookup.VertexEnvelope();
var clientMulti = new AreaLookup.LookupTaxAreasWS90Client();
var reqMulti = new AreaLookup.TaxAreaRequestType();
var reqresMulti = new AreaLookup.TaxAreaResultType();
var resMulti = new AreaLookup.TaxAreaResponseType();
string inputXMLMulti;
string outputXMLMulti;
var TALMulti = new AreaLookup.TaxAreaLookupType();
var TALasofDateMulti = new DateTime();
var resTypeMulti = new AreaLookup.TaxAreaLookupResultType();
var postalMulti = new AreaLookup.PostalAddressType();
string StrNoteMulti = "";
int i, y;
var x = default(int);
postalMulti.MainDivision = Element.state;
postalMulti.City = Element.city;
postalMulti.PostalCode = Element.zip;
postalMulti.StreetAddress1 = Element.streetaddress1;
TALasofDateMulti = Conversions.ToDate("2020-12-11");
TALMulti.asOfDate = TALasofDateMulti;
TALMulti.Item = postalMulti;
reqMulti.TaxAreaLookup = TALMulti;
var LITMulti = new AreaLookup.LoginType();
venvMulti.Login = new AreaLookup.LoginType();
venvMulti.Login.UserName = "****";
venvMulti.Login.Password = "****";
venvMulti.Item = reqMulti;
inputXMLMulti = (string)SerializeObjectToString(venvMulti);
Output(inputXMLMulti);
try
{
clientMulti.LookupTaxAreas90(ref venvMulti);
resMulti = (AreaLookup.TaxAreaResponseType)venvMulti.Item;
outputXMLMulti = (string)SerializeObjectToString(venvMulti);
Output(outputXMLMulti);
var loopTo = resMulti.TaxAreaResult.Length - 1;
}
catch (NullReferenceException)
{
Console.WriteLine("Null");
}
reqMulti = default;
reqresMulti = default;
resMulti = default;
void debugOutputCleansedMulti(string strDebugTextCleansedMulti)
{
try
{
System.Diagnostics.Debug.Write(strDebugTextCleansedMulti + Environment.NewLine);
txtCleansed.Text = txtCleansed.Text + strDebugTextCleansedMulti + Environment.NewLine;
txtCleansed.SelectionStart = txtCleansed.TextLength;
txtCleansed.ScrollToCaret();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
}
debugOutputCleansedMulti("Address Cleanse Started: ");
var venvCleansedMulti = new AreaLookup.VertexEnvelope();
var clientCleansedMulti = new AreaLookup.LookupTaxAreasWS90Client();
var reqCleansedMulti = new AreaLookup.TaxAreaRequestType();
var reqresCleansedMulti = new AreaLookup.TaxAreaResultType();
var resCleansedMulti = new AreaLookup.TaxAreaResponseType();
string inputXMLCleansedMulti;
string outputXMLCleansedMulti;
var TALCleansedMulti = new AreaLookup.TaxAreaLookupType();
var TALasofDateCleansedMulti = new DateTime();
var resTypeCleansedMulti = new AreaLookup.TaxAreaLookupResultType();
var postalCleansedMulti = new AreaLookup.PostalAddressType();
string StrNoteCleansedMulti = "";
int a, b;
var c = default(int);
postalCleansedMulti.MainDivision = Element.state;
postalCleansedMulti.City = Element.city;
postalCleansedMulti.PostalCode = Element.zip;
postalCleansedMulti.StreetAddress1 = Element.streetaddress1;
TALasofDateCleansedMulti = Conversions.ToDate("2020-12-11");
TALCleansedMulti.asOfDate = TALasofDateCleansedMulti;
TALCleansedMulti.Item = postalCleansedMulti;
reqCleansedMulti.TaxAreaLookup = TALCleansedMulti;
var LITCleansedMulti = new AreaLookup.LoginType();
venvCleansedMulti.Login = new AreaLookup.LoginType();
venvCleansedMulti.Login.UserName = "****";
venvCleansedMulti.Login.Password = "****";
venvCleansedMulti.Item = reqCleansedMulti;
int j = 1;
//inputXMLCleansed = resCleansed.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + " - " + resCleansed.TaxAreaResult[0].PostalAddress[0].PostalCode + " - " + resCleansed.TaxAreaResult[0].confidenceIndicator;
//debugOutputCleansed(inputXMLCleansed);
try
{
clientCleansedMulti.LookupTaxAreas90(ref venvCleansedMulti);
resCleansedMulti = (AreaLookup.TaxAreaResponseType)venvCleansedMulti.Item;
debugOutputCleansedMulti(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + " | Street Address 1" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2 + " | Street Address 2" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision + " | County" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City + " | City" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode + " | Zip Code" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision + " | State" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].confidenceIndicator + " | Confidence Indicator");
string pathCleansed = #"C:\dev\data\data.csv";
string[] createText = {
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].Country + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision + "," +
resCleansedMulti.TaxAreaResult[0].confidenceIndicator
};
File.AppendAllLines(pathCleansed, createText, System.Text.Encoding.UTF8);
txtCounter.Text = j.ToString();
j++;
var loopTo = resCleansedMulti.TaxAreaResult.Length - 1;
for (b = 0; b <= loopTo; b++)
{
if (c == 0)
{
StrNoteCleansedMulti = resCleansedMulti.TaxAreaResult[b].PostalAddress[0].StreetAddress1 + " - " + resCleansedMulti.TaxAreaResult[b].confidenceIndicator; c = 1;
}
else
{
StrNoteCleansedMulti += ", " + resCleansedMulti.TaxAreaResult[b].taxAreaId + " - " + resMulti.TaxAreaResult[b].confidenceIndicator;
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
reqCleansedMulti = default;
reqresCleansedMulti = default;
resCleansedMulti = default;
}
}
Essentially you need a way to save your work in progress. One pattern would be to load the file and store it in a database, then as you process each line you mark off which item you have processed. If you did this I would split the code into different modules, importing file, processing file, and exporting results.
Another simpler approach might be to write the results out as you process them, and record the line number from the input file. Then if you have to restart, find the last line you output and use that to skip reprocessing the items in your input file

The process cannot access the file "XXX.txt" because it is being used by another process

I would like to write to and read from the same text file. However, I faced the issue of "The process cannot access "XXX.txt" because it is being used by another process".
I created two classes, A & B and define two objects for each of the classes in the main form.
Class A will be writing data into the text file while Class B will reading data from the text file at the same time.
I had put Class B in a timer while Class A will start when I click a button.
Class A :-
private void Processdata(string indata)
{
//======================================[TCP/IP]=====================================================//
using (StreamWriter sw = new StreamWriter(TCPfilename, true))
{
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
sw.WriteLine(formattedTime + "\t" + indata);
}
// Regular Expression for WIFI Drone & Phantom 3 Drone
Regex regexp3_1 = new Regex(#"^AH(60601F740D70)(-\d{0,2})");
Regex regexp3_2 = new Regex(#"^AH(60601F415CAF)(-\d{0,2})");
Regex regexp3_3 = new Regex(#"^AH(60601F078D3E)(-\d{0,2})");
Regex regexp3 = new Regex(#"^AH(60601F(\S{0,6}))(-\d{0,2})");
Regex regexP3 = new Regex(#"^GGP3(\S{0,8})");
Regex regexPA = new Regex(#"^AH(A0143D\S{0,6})(-\d{0,2})");
Regex regex3D = new Regex(#"^AH(8ADC96\S{0,6})(-\d{0,2})");
Regex regexMA = new Regex(#"^AH(60601F93F3FB)(-\d{0,2})");
Regex regexMP = new Regex(#"^AH(60601F33729E)(-\d{0,2})");
Regex regexTL = new Regex(#"^AH(60601FD8A1EF)(-\d{0,2})");
// Regular Expression for WIFI
Regex regexAH = new Regex(#"^AH(\S{0,12})(-\d{0,2})");
Regex regexAH2 = new Regex(#"^AH(\S{0,12})(-\d{0,2})\S{0,6}(\S{0,74})");
// Match WIFI Drone & Phantom 3 Drone Data with Regular Expression
Match matchp3_1 = regexp3_1.Match(indata);
Match matchp3_2 = regexp3_2.Match(indata);
Match matchp3_3 = regexp3_3.Match(indata);
Match matchp3 = regexp3.Match(indata);
Match matchP3 = regexP3.Match(indata);
Match matchPA = regexPA.Match(indata);
Match match3D = regex3D.Match(indata);
Match matchMA = regexMA.Match(indata);
Match matchMP = regexMP.Match(indata);
Match matchTL = regexTL.Match(indata);
// Match WIFI Data with Regular Expression
Match matchAH = regexAH.Match(indata);
Match matchAH2 = regexAH2.Match(indata);
using (StreamWriter rssi = new StreamWriter(TCPRSSIfilename, true))
{
var time = DateTime.Now;
// Parrot
if (matchPA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Parrot" + "; " + matchPA.Groups[1].Value.ToString() + "; " + matchPA.Groups[0].Value.ToString() + "; " + matchPA.Groups[2].Value.ToString());
rssi.Flush();
}
// 3DR
else if (match3D.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-3DR_Solo" + "; " + match3D.Groups[1].Value.ToString() + "; " + match3D.Groups[0].Value.ToString() + "; " + match3D.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Air
else if (matchMA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Air" + "; " + matchMA.Groups[1].Value.ToString() + "; " + matchMA.Groups[0].Value.ToString() + "; " + matchMA.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Pro
else if (matchMP.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Pro" + "; " + matchMP.Groups[1].Value.ToString() + "; " + matchMP.Groups[0].Value.ToString() + "; " + matchMP.Groups[2].Value.ToString());
rssi.Flush();
}
// Tello
else if (matchTL.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Tello" + "; " + matchTL.Groups[1].Value.ToString() + "; " + matchTL.Groups[0].Value.ToString() + "; " + matchTL.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 740D70)
else if (matchp3_1.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_1.Groups[1].Value.ToString() + "; " + matchp3_1.Groups[0].Value.ToString() + "; " + matchp3_1.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 415CAF)
else if (matchp3_2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_2.Groups[1].Value.ToString() + "; " + matchp3_2.Groups[0].Value.ToString() + "; " + matchp3_2.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 078D3E)
else if (matchp3_3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_3.Groups[1].Value.ToString() + "; " + matchp3_3.Groups[0].Value.ToString() + "; " + matchp3_3.Groups[2].Value.ToString());
rssi.Flush();
}
// General Phantom 3
else if (matchp3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3.Groups[1].Value.ToString() + "; " + matchp3.Groups[0].Value.ToString() + "; " + matchp3.Groups[2].Value.ToString());
rssi.Flush();
}
// WIFI
else if (matchAH.Success && matchAH2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Wifi -" + matchAH2.Groups[3].Value.ToString() + "; " + matchAH.Groups[1].Value.ToString() + "; " + matchAH.Groups[0].Value.ToString() + "; " + matchAH.Groups[2].Value.ToString());
rssi.Flush();
}
}
}
Class B :-
public void DisplayOnDataGridView(DataGridView dl, GMapControl gmap, string TCPRSSIfile, string UDPRSSIfile)
{
//================================[TCP/IP]==================================================//
using (StreamReader streamReader = new StreamReader(TCPRSSIfile, true))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+ -)(\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
StringBuilder sb = new StringBuilder();
if (matchSearch.Groups[3].Value.ToString() != null)
{
for (int i = 0; i <= matchSearch.Groups[3].Value.ToString().Length - 2; i += 2)
{
//Convert Hex format to standard ASCII string
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(matchSearch.Groups[3].Value.ToString().Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
}
StringBuilder sbwifi = new StringBuilder(sb.Length);
foreach (char c in sb.ToString())
{
if ((int)c > 127) // 127 = Delete
continue;
if ((int)c < 32) // 1-31 = Control Character
continue;
if (c == ',')
continue;
if (c == '"')
continue;
sbwifi.Append(c);
}
Regex wifi = new Regex(#"^(\S+)\$");
Match matchwifi = wifi.Match(sbwifi.ToString());
if (matchwifi.Success)
{
sbwifi.Clear();
sbwifi.Append(matchwifi.Groups[1].Value.ToString());
}
if (matchSearch.Success)
{
try
{
if (dl.Rows.Count == 0)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
else
{
for (int row = 0; row < dl.Rows.Count; row++)
{
if (dl.Rows[row].Cells["DroneID"].Value.ToString() == matchSearch.Groups[4].Value.ToString())
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi") == false)
{
Image img1 = Image.FromFile(#"D:\Image\alert.PNG");
if (dl.Rows[row].Cells["DroneStatus"].Value != img1)
{
dl.Rows[row].Cells["DroneStatus"].Value = img1;
}
}
dl.Rows[row].Cells["TimeDetected"].Value = matchSearch.Groups[1].Value.ToString();
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
duplicate = true;
}
}
if (!duplicate)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
//========================================[UDP]===================================================//
using (StreamReader streamReader = new StreamReader(UDPRSSIfile))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
if (matchSearch.Success)
{
try
{
//if (matchSearch.Groups[4].Value.ToString() != "0.000000")
//{
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString(), matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
//}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
if (dl.Rows[rownumber].Cells["DroneType"].Value.ToString().Contains("Wifi"))
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
DetectedZone(gmap, false);
}
else
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
DetectedZone(gmap, true);
}
Image img = Image.FromFile(#"D:\Image\arrow.jpg");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
RSSI_Signal(dl, matchSearch.Groups[5].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
// Add Number for Each DataGridView Row
if (null != dl)
{
foreach (DataGridViewRow r in dl.Rows)
{
dl.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();
}
}
}
Main Form :-
//========Call Class A Object==============//
private void button2_Click(object sender, EventArgs e)
{
// TCP/IP Address - Debug TCP Text File - Debug UDP Text File - UDP Port Number - TCP/IP RSSI Text File - UDP RSSI Text File
ListeningPole lp1 = new ListeningPole();
lp1.PortConnect("192.168.1.133", #"D:\Skydroner\SkyDroner_DebugTCP_1.txt", #"D:\Skydroner\SkyDroner_DebugUDP_1.txt", 61557, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
//========Timer to Run Class B Object==============//
private void MainForm_Load(object sender, EventArgs e)
{
// Start Timer for Display Scroll Mouse Message
RowCountTimer.Interval = 1000;
RowCountTimer.Start();
}
private void RowCountTimer_Tick(object sender, EventArgs e)
{
Display dp1 = new Display();
dp1.DisplayOnDataGridView(DroneList, gmap, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
Anyone have any solution for this error.
Please help.
Thanks.
Make sure to call Close() on the writer to close it before reading. I've seen instances where utilizing a using block with the writer may not close it in time for the reader to be able to read it.

Textfiles with Forms and Multiple Outputs

I have a code that needs to take input for the weather of certain day (and certain city) from the user and store that input into a textfile and then display that input for the specific cities from the textfile. I made use of FORMS.
How do I change my code to read the textfile correctly and NOT display each input 3 times each?
I added the relevant methods I made use of textfiles in:
private void btnCapture_Click(object sender, EventArgs e)
{
string city = cbCity.SelectedItem.ToString();
DateTime date = dtp.Value;
int minTemp = Convert.ToInt32(nudMinTemp.Value);
int maxTemp = Convert.ToInt32(nudMaxTemp.Value);
int precipitation = Convert.ToInt32(nudPrecip.Value);
int humidity = Convert.ToInt32(nudHumid.Value);
int windSpeed = Convert.ToInt32(nudWindSpeed.Value);
using (StreamWriter sw = new StreamWriter("myFile.txt"))
{
sw.WriteLine(city + Environment.NewLine + date +
maxTemp + Environment.NewLine + precipitation...);
sw.Close();
}
WeatherDetails w = new WeatherDetails(city, date, minTemp...)
w.ReadData();
MessageBox.Show("Your data has been Captured");
}
//Read data in WeatherDetails Class:
public void ReadData()
{
StreamReader SR = new StreamReader("myFile.txt");
while (!SR.EndOfStream)
{
city = SR.ReadLine();
date = DateTime.Parse(SR.ReadLine());
minTemp = int.Parse(SR.ReadLine());
maxTemp = int.Parse(SR.ReadLine());
precipitation = int.Parse(SR.ReadLine());
humidity = int.Parse(SR.ReadLine());
windSpeed = int.Parse(SR.ReadLine());
WeatherDetails newOne = new WeatherD...
ci.Add(newOne);
}
SR.Close();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
city = cbCity.SelectedItem.ToString();
DateStart = dtpStart.Value;
DateEnd = dtpEnd.Value;
//Displaying data to RTB
private void btnDisplay_Click(object sender, EventArgs e)
{
city = cbCity.SelectedItem.ToString();
DateStart = dtpStart.Value;
DateEnd = dtpEnd.Value;
//Displaying data to RTB
foreach (WeatherDetails wd in WeatherDetails.ci)
{
rtbDisplay.Text += ("The Weather Report for " + cbCity.SelectedItem.ToString() + " , accesssed on " + wd.date.ToString() + "\n" +
"\n" +
"Maximum Temperature: " + wd.maxTemp + "\n" +
"Minimum Temperature: " + wd.minTemp + "\n" +
"Precipitation: " + wd.precipitation + "\n" +
"Humidity: " + wd.humidity + "\n" +
"Wind Speed: " + wd.windSpeed + "\n" +
"-------------------End OF Report---------------------");
The issue is that it is displaying the entered data 3 TIMES each.So if i enter data for one city on the 12th and the 14th of May, it will display the 12th 3 times and display the 14th 3 times.

How to get specific character in listbox

I have a listbox in which my selected products are stored like this ...
'Product name'.padright(30) 'price' 'quantity'
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
but when I read price of a product it selects price and quantity
string currentPriceString = foundItem.Replace(details.Name.PadRight(30), "");
string quantityString = foundItem.Replace(details.Name.PadRight(33), "");
I only want price in currentPriceString and quantity in quantityString
here is complete code of this method
private void ProductButton_Click(object sender, EventArgs e)
{
Button ProductButton = sender as Button;
DataAccess dataAccess = new DataAccess();
int ProductID = Convert.ToInt32(ProductButton.Tag);
Details details = dataAccess.ReadProductDetails(ProductID);
decimal price = details.Price;
string foundItem = CheckProductInListBox(details.Name);
if (!String.IsNullOrEmpty(foundItem))
{
string currentPriceString = foundItem.Replace(details.Name.PadRight(30), "");
decimal currentPriceValue;
string quantityString = foundItem.Replace(details.Name.PadRight(33), "");
int quantiy;
MessageBox.Show(currentPriceString);
if (Decimal.TryParse(currentPriceString, out currentPriceValue))
{
quantiy = Convert.ToInt16(quantityString);
currentPriceValue += price;
quantiy++;
string newItem = details.Name.PadRight(30) + currentPriceValue.ToString() + quantiy.ToString();
int index = listBox1.Items.IndexOf(foundItem);
listBox1.Items[index] = newItem;
}
else
{
MessageBox.Show("Error");
}
}
else
{
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
}
}
private string CheckProductInListBox(string name)
{
foreach (string item in listBox1.Items)
{
if (item.Contains(name))
{
return item;
}
}
return String.Empty;
}
On replacing (foundItem.Replace(details.Name.PadRight(33), "");), you are just removing the name part from the string, so the price and quantity will be there for sure.
You should can try this code,
// suppose your found text is like this,
//foundItem = "AMIT".PadRight(30) + "200" + " " + "1";
You can get price and quantity separately like below:
string currentPriceQuantityString = foundItem.Replace(details.Name.PadRight(30), "");
//currentPriceQuantityString => "200 1"
string[] strArray = currentPriceQuantityString.Split();
string currentPriceString = strArray[0]; //currentPriceString => "200"
string quantityString = strArray[1]; //quantityString => "1"
Side note:
I guess your line:
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
..should be:
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + "1" );

Efficient method to increase "code" by 1 - HtmlAgilityPack

I'm working on an app that extracts content from a game page (example), displays it to the user in a textbox and if the user wishes to do so, he/she can save it as a .txt file or .xsl (excel spreadsheet format).
But the main problem I'm facing right now is that you have to manually change the code to "extract" data about another in-game unit.
If you open the link you'll see that I'm currently extracting the "Weapons", "Used", "Survived" and "Casualties" from the Defender side (as for now), but only 1 type of unit (more like only 1 row of that table) is being "extracted", I'm looking for a way to search "tr[1]/td[2]/span[1]" through "tr[45]/td[2]/span[1]" (even if the example page only goes until tr[16]), or maybe a way to automate it to search until it finds no data (nothing) then it would stop.
Sorry for any text mistakes, I'm not a native speaker
private void btnStart_Click(object sender, RoutedEventArgs e)
{
HtmlDocument brPage = new HtmlWeb().Load("http://us.desert-operations.com/world2/battleReport.php?code=f8d77b1328c8ce09ec398a78505fc465");
HtmlNodeCollection nodes = brPage.DocumentNode.SelectNodes("/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[2]/table[2]");
string result = "";
List<brContentSaver> ContentList = new List<brContentSaver>();
foreach (var item in nodes)
{
brContentSaver cL = new brContentSaver();
/* Here comes the junk handler, replaces all junk for nothing, essentially deleting it
I wish I knew a way to do this efficiently */
cL.Weapons = item.SelectSingleNode("tr[16]/td[1]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Used = item.SelectSingleNode("tr[16]/td[2]/span[1]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Survived = item.SelectSingleNode("tr[16]/td[3]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (cL.Survived == "0")
{
cL.Casualties = cL.Used;
} else
{
/* int Casualties = int.Parse(cL.Casualties);
* int Used = int.Parse(cL.Used);
* int Survived = int.Parse(cL.Survived);
* Casualties = Used - Survived; */
cL.Casualties = item.SelectSingleNode("tr[16]/td[4]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
}
ContentList.Add(cL);
}
foreach (var item in ContentList)
{
result += item.Weapons + " " + item.Used + " " + item.Survived + " " + item.Casualties + Environment.NewLine;
}
brContent.Text = result;
}
Sorry if this sounds silly, but I'm new to programming, especially in C#.
Edit 1: I noticed that "if (cL.Survived == "0")", I was just testing stuff some stuff way earlier and I forgot to change it, but hey, it works
Edit 2: If you are wondering I'm also using this:
public class brContentSaver
{
public string Weapons
{
get;
set;
}
public string Used
{
get;
set;
}
public string Survived
{
get;
set;
}
public string Casualties
{
get;
set;
}
}
I don't have much time to write this but hope it will help if you still need. I find Linq is more handy:
private static void Run()
{
HtmlDocument brPage = new HtmlWeb().Load("http://us.desert-operations.com/world2/battleReport.php?code=f8d77b1328c8ce09ec398a78505fc465");
var nodes = brPage.DocumentNode.Descendants("table").Where(_ => _.Attributes["class"] != null && _.Attributes["class"].Value != null && _.Attributes["class"].Value.Contains("battleReport"));
string result = "";
List<brContentSaver> ContentList = new List<brContentSaver>();
foreach (var item in nodes)
{
if (item.Descendants("th").Any(_ => _.InnerText.Equals("Weapons")))
{
//get all tr nodes except first one (header)
var trNodes = item.Descendants("tr").Skip(1);
foreach (var node in trNodes)
{
brContentSaver cL = new brContentSaver();
var tds = node.Descendants("td").ToArray();
/* Here comes the junk handler, replaces all junk for nothing, essentially deleting it
I wish I knew a way to do this efficiently */
cL.Weapons = tds[0].InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Used = tds[1].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Used))
{
cL.Used = tds[1].InnerText;
}
cL.Survived = tds[2].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Survived))
{
cL.Casualties = cL.Used;
}
else
{
/* int Casualties = int.Parse(cL.Casualties);
* int Used = int.Parse(cL.Used);
* int Survived = int.Parse(cL.Survived);
* Casualties = Used - Survived; */
cL.Casualties = tds[3].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Casualties))
{
cL.Casualties = tds[3].InnerText;
}
}
ContentList.Add(cL);
}
}
}
foreach (var item in ContentList)
{
result += item.Weapons + " " + item.Used + " " + item.Survived + " " + item.Casualties + Environment.NewLine;
}
var text = result;
}

Categories

Resources