Format Exception Unhandled while debugging - c#

When debugging the code, Visual Studio gives me a "format exception was unhandled" while highlighting this line of code: 'CustObj.d_CustDiscount = Convert.ToDecimal(gs_InPutBuffer.Substring(000, 004));'
I have been googling correct formats and have not come up with any fixes. So my main question is, how do I rewrite this code in order for it to work?
Thanks for any help!
Below is the full program if you need to reference it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using CustFile_DLL;
namespace FileConvertorPA03
{
class Program
{
//add these to handle I/O
//instatiate streamreader
private static StreamReader TextfileIn = new StreamReader("customers.txt");
//instantiate the dll
private static CustFileClass CustObj = new CustFileClass();
//a few vars
private static string gs_InPutBuffer = "";
private static Int32 gi_TotalRec = 0, gi_FirstRecNo = 0;
private static bool gb_FirstRec = true;
static void Main(string[] args)
{
while ((gs_InPutBuffer = TextfileIn.ReadLine()) != null)
{
ParsetoAttributes();
CustObj.AddObject();
}//end while
PopMessageBox();
TextfileIn.Close();
}//end main
//method to parse input buffer to class attributes
private static void ParsetoAttributes()
{
CustObj.s_CustName = gs_InPutBuffer.Substring(000, 033).Trim();
CustObj.s_CustAddress = gs_InPutBuffer.Substring(033, 032).Trim();
CustObj.s_CustZip = gs_InPutBuffer.Substring(065, 005);
CustObj.s_CustPhone = gs_InPutBuffer.Substring(070, 010);
CustObj.d_CustDiscount = Convert.ToDecimal(gs_InPutBuffer.Substring(000, 004));
}//end parse attributes
//method to count records added
static void CountRecs()
{
if (gb_FirstRec == true)
{
gi_FirstRecNo = CustObj.i_CustNumber;
gb_FirstRec = false;
}//end if
gi_TotalRec++;
}//end count recs
public static void PopMessageBox()
{
MessageBox.Show(String.Format("Message: \n\tRecords Added \t{0,6}n\tFirst Rec Added\t {1,6}\n\tLast Rec Added\t{2,6}",
gi_TotalRec, gi_FirstRecNo, CustObj.i_CustNumber),"File Conversion Message:",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}//end class
}
}//end namespace

Replace the ToDecimal call with the following to find out what the issue is:
try
{
CustObj.d_CustDiscount = Convert.ToDecimal(gs_InPutBuffer.Substring(0, 4));
}
catch (FormatException e)
{
Console.WriteLine(gs_InPutBuffer.Substring(0, 4));
Console.WriteLine(e.Message);
}
If this isn't a console application, you can change the code in the catch block to write out to a MessageBox. You can also leave out the leading zeros in the arguments to the calls to Substring.

Related

Is there a way to read and validate specified PDF text using ITextSharp?

I am trying to create a concept program where I can read a PDF, and have it validate that a specific string or sentence exists using ITextSharp. The following code snippet is what I have so far:
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System;
using System.Text;
namespace PDFReader
{
internal class Class1
{
private static void Main(string[] args)
{
try
{
StringBuilder text = new StringBuilder();
using (PdfReader reader = new PdfReader(#"C:\Users\Me\Downloads\TestPDF.pdf"))
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
}
}
Console.WriteLine(text.ToString());
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.Read();
}
}
}
So far, this works wonderfully for reading the full PDF contents, but I need it to return the specified string, if it exists. I was thinking something like this:
.Where(p => p.Text.Contains("SpecifiedStringHere")).OrderBy(p => p.Y).Reverse().ToList();
Any help would be greatly appreciated!

NULL symbol in file using StreamWriter

I want to add simple logger in to my app.
For this purpose I want to use StreamWriter.
Code:
private StreamWriter OutputStream;
OutputStream = new StreamWriter(this.LogFilePath, true);
// .... message - log from app
DateTime now = DateTime.Now;
message = string.Format("[{0:yyyy-MM-dd H:mm:ss}] {1}", now, message
if (OutputStream != null)
{
OutputStream.WriteLine(message);
OutputStream.Flush();
}
As result all strings are correctly captured and output is correct, but sometimes it can write empty string with invisible characters at the end:
sample:
[1970-08-31 14:56:26] Command response -> !c:65:f9:1b:82:97
and if i check this with some tool that can show invisible characters, I can see next:
As result ~600 lines of log - 125 mb.
I have found that reason could be next:
That happens. When you append a file first its size is corrected in
the directory (and that's transactional in NTFS) and then the actual
new data is written. There's good chance that if you shut down the
system you end up with a file appended with lots of null bytes because
data writes are not transactional unlike metadata (file size) writes.
There's no absolute solution to this problem.
Also tried to
check characters with isControl other similar checks;
tried to Trim last characters;
checked docs - looks like all correct
Any advice?
In case someone faced with same issue - reason for me unknown and i may only guess.... but I rewrite logic with log system and bug disappear:
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
public class EventLogger : MonoBehaviour
{
private string logFileName = "btlog.txt";
public bool EchoToConsole = true;
public bool AddTimeStamp = true;
public bool EnableFileStorage = true;
private string LogFilePath
{
get
{
return Path.Combine(Application.persistentDataPath, logFileName);
}
}
private static EventLogger Singleton = null;
const string format = "yyyy-MM-dd HH:mm:ss.fffffff";
public static EventLogger Instance
{
get { return Singleton; }
}
void Awake()
{
if (Singleton != null)
{
UnityEngine.Debug.LogError("Multiple EventLogger Singletons exist!");
return;
}
Singleton = this;
if (this.EnableFileStorage)
{
if (File.Exists(LogFilePath))
{
long length = new FileInfo(LogFilePath).Length;
int limit = 1024 * 1024 * 5; // 5mb
if (length > limit)
{
File.Delete(LogFilePath);
Log("log file removed");
}
}
Log("-------------------");
Log("NEW SESSION STARTED");
}
}
private async Task Write(string message)
{
if (this.EnableFileStorage)
{
if (AddTimeStamp)
{
DateTime now = DateTime.Now;
string strDate = now.ToString(format);
string trimmed = new string(message.Where(c => !char.IsControl(c)).ToArray());
message = string.Format("[{0}] {1}", strDate, trimmed);
}
using (StreamWriter outputStream = new StreamWriter(this.LogFilePath, true))
{
await outputStream.WriteLineAsync(message);
}
if (EchoToConsole)
{
UnityEngine.Debug.Log(message);
}
}
}
[Conditional("DEBUG"), Conditional("PROFILE")]
public static void Log(string Message)
{
if (EventLogger.Instance != null)
{
_ = EventLogger.Instance.Write(Message);
}
else
{
UnityEngine.Debug.Log(Message);
}
}
}

Background Agent Not Performing.: Windows Phone 8

NEED A SOLUTION
Background agent is working only once. After There is no occurrence of a background agent. It works at the first time and it works perfectly as soon as the page opens. however, after that it takes forever and ever to do that again. sometimes page close and open doesn't work. that would probably because of not removing the agenet
My background Agent Code:
#define DEBUG_AGENT
using System;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Info;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Threading;
using Microsoft.Xna.Framework.Media;
using System.Windows.Input;
using Microsoft.Devices;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.Net.Sockets;
using System.Text;
using System.Net;
namespace ScheduledTaskAgent1
{
public class ScheduledAgent : ScheduledTaskAgent
{
private static volatile bool _classInitialized;
//private DispatcherTimer s;
Socket _socket = null;
ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;
double lat = 7.16126666666667;
static ScheduledAgent()
{
// Subscribe to the managed exception handler
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Application.Current.UnhandledException += UnhandledException;
});
}
/// Code to execute on Unhandled Exceptions
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
protected override void OnInvoke(ScheduledTask task)
{
//TODO: Add code to perform your task in background
string toastTitle = "";
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
lat += 0.001;
string snmea = DD2NMEA(lat, 80.44506);
string dates = DateTime.UtcNow.ToString("ddMMyy");
string UTCTime = DateTime.UtcNow.ToString("hhmmss") + ".000";
string s1 = Checksum("$FRCMD,869444005499999,_SendMessage,,0809.67600,N,8050.70360,E,1.0,1.08,3.0,141013,055642.000,1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
string s = Send("$FRCMD,869444005499999,_SendMessage,," + snmea + ",1.0,1.08,3.0," + dates + "," + UTCTime + ",1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
startToastTask(task, toastTitle);
}
private void startToastTask(ScheduledTask task, string toastTitle)
{
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
#endif
// Call NotifyComplete to let the system know the agent is done working.
NotifyComplete();
}
}
}
My Page from app which calls the agent
PeriodicTask toastPeriodicTask;
const string toastTaskName = "ToastPeriodicAgent";
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
toastPeriodicTask = ScheduledActionService.Find(toastTaskName) as PeriodicTask;
StartPeriodicAgent(toastTaskName);
}
private void StartPeriodicAgent(string taskName)
{
toastPeriodicTask = ScheduledActionService.Find(taskName) as PeriodicTask;
if (toastPeriodicTask != null)
{
RemoveAgent(taskName);
}
toastPeriodicTask = new PeriodicTask(taskName);
toastPeriodicTask.Description = periodicTaskDesc;
try
{
ScheduledActionService.Add(toastPeriodicTask);
#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(2));
#endif
}
catch (InvalidOperationException exception)
{
if (exception.Message.Contains("BNS Error: The action is disabled"))
{
MessageBox.Show("Background agents for this application have been disabled by the user.");
}
else if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
{
MessageBox.Show("BNS Error: The maximum number of ScheduledActions of this type have already been added.");
}
else
{
MessageBox.Show("An InvalidOperationException occurred.");
}
}
catch (SchedulerServiceException)
{
}
}
Ensure that your project has DEBUG_AGENT defined. This is a setting within your project properties. To set this flag, follow these steps
Right click the project within VS and select Properties
Select the Build tab
Add DEBUG_AGENT to the "Conditional compilation symbols" field.
If that is set, I've found it's best to give at least 30 seconds in the LaunchForTest. Sometimes it doesn't quite schedule it when you tell it to.

Function works when called synchronously, but does not work when called asynchronously

It is my first post on StackOverflow forum so please to be lenient. I have a problem with function which works called synchronously, but doesnot works called asynchronously.
Below You will find function called synchronously:
private void issueInvoices(List<int> lista)
{
foreach (int knh_id in lista)
{
Invoice fs = new Invoice();
fs.FKS_AKCYZA = false;
fs.FKS_CZY_KLON = false;
fs.FKS_DATE = Convert.ToDateTime(MTBDataZapisuDoFK.Text);
fs.NUMBER = knh_id);
}
}
As You can see i passed list to function named issueInvoices list of invoice numbers and in loop i create some invoices.
This function works properly but if i try to call it asynchronously (to display progress bar) my function can not assign to fs.FKS_DATE object dateTime. It looks like static function “Convert.ToDateTime” doesnot work properly. But please take a look on below code where function issueInvoices is called asynchronously…
public delegate void BinaryDelegate(List<int> knh_id);
BinaryDelegate b = new BinaryDelegate(issueInvoices);
IAsyncResult theAsRes = b.BeginInvoke(lista, new AsyncCallback(AddComplete), "Thx U!");
FrmProgressBar fpb=new FrmProgressBar(“Please wait…”);
fpb.Show();
/* below i check how many operation i have to do, if all operations are done, then I close fpb window, program is updating progres bar and in thread make operation issueInvoices*/
while (ilosc_zrobionych != liczbaKontrahentow)
{
fpb.PBStan.Value = (int)((100 * ilosc_zrobionych) / liczbaKontrahentow);
}
fpb.Close();
I put some breakpoints and it looks like program stoping in line, it can conver to datetime, but when i do this synchronously, it works without any errors.
fs.FKS_DATE = Convert.ToDateTime(MTBDataZapisuDoFK.Text);
What could couse this problem and how to resolve it?
Many thanks in advance for reply.
BELOW IS WHOLE CLASS CALLED ASYNCHRONOUSLY:
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Npgsql;
using Castle.ActiveRecord;
using WFR.Model;
using System.Threading;
namespace Faktury_i_Rachunki_2.Forms
{
public partial class FrmEmisjaFakturPotwierdzonych : FrmBaseForm
{
private ArrayList listaSposobowZaplaty;
public List<int> lista;
private int liczbaWygenerowach;
private int liczbaKontrahentow;
private int ilosc_zrobionych;
private FrmProgressBar fpb;
public delegate void BinaryDelegate(List<int> knh_id);
public FrmEmisjaFakturPotwierdzonych()
{
InitializeComponent();
fpb = new FrmProgressBar("Please wait....");
}
private void BtOK_Click(object sender, EventArgs e)
{
BinaryDelegate b = new BinaryDelegate(WyemitujFakture);
lista.Add(12);
lista.Add(13);
lista.Add(17);
lista.Add(1);
liczbaKontrahentow = lista.Count;
if (TBRejestr.Text.Trim() != "")
{
if (liczbaKontrahentow > 0)
{
liczbaWygenerowach = 0;
ilosc_zrobionych = 0;
WyemitujFakture(lista);
IAsyncResult theAsRes = b.BeginInvoke(lista, new AsyncCallback(AddComplete), "THX");
fpb.Show();
while (ilosc_zrobionych != liczbaKontrahentow)
{
fpb.PBStan.Value = (int)((100 * ilosc_zrobionych) / liczbaKontrahentow);
}
fpb.Close();
}
try
{
MessageBox.Show("Wygenerowano " + liczbaWygenerowach.ToString() + " faktur");
}
catch
{
}
}
}
private void WyemitujFakture(List<int> lista)
{
foreach (int knh_id in lista)
{
try
{
if (luk.Count > 0)
{
FakturySprzedazy fs = new FakturySprzedazy();
fs.FKS_AKCYZA = false;
fs.FKS_CZY_KLON = false;
fs.FKS_DATA_DOW_KS = Convert.ToDateTime(MTBDataZapisuDoFK.Text);
fs.FKS_DATA_FAKTURY = Convert.ToDateTime(MTBDataFaktury.Text);
fs.FKS_DATA_SPRZEDAZY = Convert.ToDateTime(MTBDataSprzedazy.Text);
liczbaWygenerowach++;
}
}
catch (Exception ex)
{
MessageBox.Show("Nie można wyemitować faktury dla kontrahenta o id = " + knh_id.ToString() + " " + ex.Message);
}
ilosc_zrobionych++;
}
}
You are accessing a UI control from a background thread:
MTBDataZapisuDoFK.Text
That is not allowed.
Get this value before calling the method, store it in a variable and send the value as an argument to issueInvoices.
The problem is in getting the value of MTBDataZapisuDoFK.Text (which I assume to be a textbox). Getting or setting the text of a textbox means sending messages to its window. But you keep the UI-thread busy in the while loop and therefore it can not process any messages.
Put a call to Application.DoEvents() into the while loop to allow messages to be processed:
fpb.Show();
while (ilosc_zrobionych != liczbaKontrahentow)
{
Application.DoEvents();
fpb.PBStan.Value = (int)((100 * ilosc_zrobionych) / liczbaKontrahentow);
}
fpb.Close();
I assume that the only reason for calling the method asynchronously is to be able to update the UI during processing the WyemitujFakture-method. Using Application.DoEvents() you do not need asynchonous calls:
fpb = new FrmProgressBar("Please wait....");
fpb.Show();
Application.DoEvents();
WyemitujFakture(lista);
fpb.Close();
You should call Application.DoEvents() after you call fpb.Show() to allow the form to be displayed properly. Also you should instantiate the form in the method itself instead of the constructor, because you can not use the same instance again after calling fpb.Close() (it will be disposed).
Then you can update the progress bar in the WyemitujFakture-method:
private void WyemitujFakture(List<int> lista)
{
foreach (int knh_id in lista)
{
try
{
if (luk.Count > 0)
{
FakturySprzedazy fs = new FakturySprzedazy();
fs.FKS_AKCYZA = false;
fs.FKS_CZY_KLON = false;
fs.FKS_DATA_DOW_KS = Convert.ToDateTime(MTBDataZapisuDoFK.Text);
fs.FKS_DATA_FAKTURY = Convert.ToDateTime(MTBDataFaktury.Text);
fs.FKS_DATA_SPRZEDAZY = Convert.ToDateTime(MTBDataSprzedazy.Text);
liczbaWygenerowach++;
}
}
catch (Exception ex)
{
MessageBox.Show("Nie mozna wyemitowac faktury dla kontrahenta o id = " + knh_id.ToString() + " " + ex.Message);
}
ilosc_zrobionych++;
fpb.PBStan.Value = (int)((100 * ilosc_zrobionych) / liczbaKontrahentow);
Application.DoEvents();
}
}

when i running the below code iam getting handle is invalid it takes a string and pass it to remote batch file

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Security;
namespace SampleProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String input = textBox1.Text;
try
{
Process ps = new Process();
ps.StartInfo.FileName = #"\\199.63.55.163\d$\hello.bat";
ps.StartInfo.Arguments = input;
ps.StartInfo.CreateNoWindow = false;
String domain = ps.StartInfo.Domain;
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
ps.StartInfo.WorkingDirectory = #"d:\praveen";
ps.StartInfo.UserName = "Raj";
ps.StartInfo.Domain = "domain";
ps.StartInfo.Password = Encrypt("Hello123");
ps.StartInfo.UseShellExecute = false;
ps.Start();
ps.WaitForExit();
MessageBox.Show(ps.StandardOutput.ReadToEnd());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void label1_Click(object sender, EventArgs e)
{
}
public static SecureString Encrypt(String pwd)
{
SecureString ss = new SecureString();
for (int i = 0; i < pwd.Length; i++)
{
ss.AppendChar(pwd[i]);
}
return ss;
}
}
}
It's a shot in the dark, but I think that you can't read the processes standard output once it has exited.
Also you have to redirect it - take a look at this documentation: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
Duplicate of .NET Process Start Process Error using credentials (The handle is invalid) ? You need to assign RedirectStandardInput, RedirectStandardOutput, RedirectStandardError

Categories