This problem concerns a thermal receipt printer. I have downloaded C# EPSON OPOS receipt printing examples in attempt to implement such a printer in my current project, all is working well but when I print a bitmap logo, successive text is being printed under it, and I need to print some text to the right side of it. Here is an approximation of what it does now:
This is what I need it to do:
My current code, pretty much as-is from EPSON's samples:
private void btnReceipt_Click(object sender, System.EventArgs e)
{
//<<<step8>>>--Start
//Initialization
DateTime nowDate = DateTime.Now; //System date
DateTimeFormatInfo dateFormat = new DateTimeFormatInfo(); //Date Format
dateFormat.MonthDayPattern = "MMMM";
string strDate = nowDate.ToString("MMMM,dd,yyyy HH:mm",dateFormat);
int iRecLineSpacing;
int iRecLineHeight;
bool bBuffering = true;
bool bBitmapPrint = false;
int iPrintRotation = 0;
string strCurDir = Directory.GetCurrentDirectory();
string strFilePath = strCurDir.Substring(0,
strCurDir.LastIndexOf("Step8") + "Step8\\".Length);
strFilePath += "bitmap_logo.bmp";
Cursor.Current = Cursors.WaitCursor;
Rotation[] arBitmapRotationList = m_Printer.RecBitmapRotationList;
Rotation[] arBarcodeRotationList = m_Printer.RecBarCodeRotationList;
//Check rotate bitmap
for (int i = 0; i < arBitmapRotationList.Length; i++)
{
if (arBitmapRotationList[i].Equals(Rotation.Left90))
{
bBitmapPrint = true;
iPrintRotation = (iPrintRotation | (int)PrintRotation.Left90)
| ((int)PrintRotation.Bitmap);
}
}
iRecLineSpacing = m_Printer.RecLineSpacing;
iRecLineHeight = m_Printer.RecLineHeight;
if (m_Printer.CapRecPresent == true)
{
try
{
m_Printer.TransactionPrint(PrinterStation.Receipt, PrinterTransactionControl.Transaction);
m_Printer.RotatePrint(PrinterStation.Receipt, (PrintRotation)iPrintRotation);
if (bBitmapPrint == true)
{
m_Printer.PrintBitmap(PrinterStation.Receipt, strFilePath, m_Printer.RecLineWidth, PosPrinter.PrinterBitmapCenter);
}
m_Printer.PrintNormal(PrinterStation.Receipt,"\u001b|4C" + "\u001b|bC" + " Receipt ");
m_Printer.PrintNormal(PrinterStation.Receipt,"\u001b|3C" + "\u001b|2uC" + " Mr. Brawn\n");
m_Printer.PrintNormal(PrinterStation.Receipt,"\u001b|2uC" + " \n\n");
m_Printer.PrintNormal(PrinterStation.Receipt,"\u001b|2uC" + "\u001b|3C" + " Total payment $" +"\u001b|4C" + "21.00 \n");
m_Printer.PrintNormal(PrinterStation.Receipt,"\u001b|1C\n" );
m_Printer.PrintNormal(PrinterStation.Receipt,strDate + " Received\n\n");
m_Printer.RecLineHeight = 24;
m_Printer.RecLineSpacing = m_Printer.RecLineHeight;
m_Printer.PrintNormal(PrinterStation.Receipt,"\u001b|uC" + " Details \n");
m_Printer.PrintNormal(PrinterStation.Receipt,"\u001b|1C" + " " + "\u001b|2C" + "OPOS Store\n");
m_Printer.PrintNormal(PrinterStation.Receipt,"\u001b|uC" + " Tax excluded $20.00\n");
m_Printer.PrintNormal(PrinterStation.Receipt,"\u001b|1C" + " " + "\u001b|bC" + "Zip code 999-9999\n");
m_Printer.PrintNormal(PrinterStation.Receipt,"\u001b|uC" + " Tax(5%) $1.00" + "\u001b|N" + " Phone#(9999)99-9998\n");
}
catch(PosControlException ex)
{
if(ex.ErrorCode == ErrorCode.Illegal && ex.ErrorCodeExtended == 1004)
{
MessageBox.Show("Unable to print receipt.\n", "Printer_SampleStep8", MessageBoxButtons.OK, MessageBoxIcon.Warning);
// Clear the buffered data since the buffer retains print data when an error occurs during printing.
m_Printer.ClearOutput();
bBuffering = false;
}
}
try
{
m_Printer.RotatePrint(PrinterStation.Receipt, PrintRotation.Normal);
if(bBuffering == true)
{
m_Printer.PrintNormal(PrinterStation.Receipt, "\u001b|fP");
}
m_Printer.TransactionPrint(PrinterStation.Receipt, PrinterTransactionControl.Normal);
}
catch(PosControlException)
{
// Clear the buffered data since the buffer retains print data when an error occurs during printing.
m_Printer.ClearOutput();
}
}
m_Printer.RecLineSpacing = iRecLineSpacing;
m_Printer.RecLineHeight = iRecLineHeight;
Cursor.Current = Cursors.Default;
//<<<step8>>>--End
}
If there is a method to do absolute text positioning or being able to write to the same line where the bitmap is, it would solve my issue. Any directions appreciated!
Please ask EPSON whether you can print with the layout you want with one set of RotatePrint.
As an alternative, consider dividing it into two sets of RotatePrint.
If you first set of RotatePrint with Bitmap and "Some other text", and the second set of RotatePrint with "Sample text 1" to "Sample text 3", it will be close to the layout you want.
In addition:
Epson OPOS seems to support PageMode, so can you print it?
As for explanation of Japanese, please look through google translation etc.
Related
if (GUILayout.Button("Copy settings"))
{
var selection = Selection.gameObjects.ToList();
for (int i = selection.Count - 1; i >= 0; --i)
{
var selected = selection[i];
WriteDataToFile("Transform " + i.ToString() + " Name ==> " + selected.name);
WriteDataToFile("************************" +
"********************");
if (selected.transform.parent != null)
WriteDataToFile(selected.transform.parent.ToString());
WriteDataToFile("local position " + selected.transform.localPosition.ToString());
WriteDataToFile("local rotation " + selected.transform.localRotation.ToString());
WriteDataToFile("local scale " + selected.transform.localScale.ToString());
WriteDataToFile("************************" +
"********************");
WriteDataToFile(" ");
}
}
And the WriteDataToFile:
private void WriteDataToFile(string line)
{
string path = "Assets/Resources/test.txt";
StreamWriter writer = new StreamWriter(path, true);
writer.WriteLine(line);
writer.Close();
}
First I want to check that if I click more then once on the button and it's the same data: name position rotation scale don't write again.
Second how can I read back the lines of the data and assign them into a object ? Also the name. So a new object will be created in the same name parent if the original was parent position rotation and scale.
This is how I'm reading now:
void ReadString()
{
string path = "Assets/Resources/test.txt";
StreamReader reader = new StreamReader(path);
Debug.Log(reader.ReadToEnd());
reader.Close();
}
To add new data to the file that doesn't already exist:
private void WriteDataToFile(string line)
{
string path = "Assets/Resources/test.txt";
string[] text = new string[];
if(File.Exists(path))
{
text = File.ReadAllLines(path);
if(!text.Contains(line))
File.AppendAllText(path, Line);
}
}
If you are not limited to using a text file for storing and retrieving data then I recommend finding a way to write all this data:
WriteDataToFile("Transform " + i.ToString() + " Name ==> " + selected.name);
WriteDataToFile("************************" +
"********************");
if (selected.transform.parent != null)
WriteDataToFile(selected.transform.parent.ToString());
WriteDataToFile("local position " + selected.transform.localPosition.ToString());
WriteDataToFile("local rotation " + selected.transform.localRotation.ToString());
WriteDataToFile("local scale " + selected.transform.localScale.ToString());
WriteDataToFile("************************" +
"********************");
WriteDataToFile(" ");
in less writes because opening and closing the file could be expensive. Maybe something like this:
var selected = selection[i].transform;
string toWrite = $"{parent}:{localPosition}:{localRotation}:{localScale}";
WriteDataToFile(toWrite);
This would mean retrieval would be simply - (not sure the type)
private gameObject GetObjectFromFile(Path, Id)
{
string[] text = new string[];
if(File.Exists(path))
{
text = File.ReadAllLines(path);
foreach(string s in text)
{
if(s.Split(':')[0] == Id.ToString())
{
text = s.Split(':');
break;
}
}
var Id = Convert.ToInt32(text[0]);
var localPosition = Convert.ToInt32(text[1]);
var localRotation = Convert.ToInt32(text[2]);
var localScale = Convert.ToInt32(text[3]);
return new gameObject(Id, localPosition, localRotation, localScale);
}
I've looked at Parallel.ForEach - System Out of Memory Exception regarding this issue but not much of a solution was given. I'm very new to using Parallel.ForEach, so I'm trying to figure out what's going on.
Diagnostic tools caps out at 1023 repeating (I understand this is an x86 to x64 arch restriction, but I wanted to offer the program in both formats.) I also don't feel like any program should ever meet that threshold. When I compile the program in x64, I sit around 1.1-1.4GB with MaxDegree . For sake of testing, I am running GC.Collection() at the end of each Parallel.ForEach iteration (I understand this isn't good practice, I'm just trying to troubleshoot at this point.)
Here's what I'm seeing:
Now if I try to use a Partitioner method, such as:
var checkforfinished = Parallel.ForEach<ListViewItem>(Partitioner.Create(0,lstBackupUsers.Items.Count), lstBackupUsers.Items.Cast<ListViewItem>(), opts, name =>
The I get an error of:
"No overload for method 'ForEach' takes 4 arguments"
That's fine, I modify my Parallel.ForEach statement so it looks like this:
var checkforfinished = Parallel.ForEach(Partitioner.Create(0,lstBackupUsers.Items.Count), lstBackupUsers.Items, opts, name => (I removed my casts)
and then my ForEach method won't accept the statement because it wants me to explicitly tell it that it's addressing a listviewbox.items method.
I am so confused on what to do.
Do I create a Partitioner, and if I do, how do I make my Parallel.ForEach method understand how to address a listviewbox?
update 1
I want to try to give as many details as possible because this is just rough. I'm sure it's easy, I'm just overcomplicationg it by an nth degree.
I have my Parallel.ForEach(//) running in a background worker function. My DoWork process is over 300 lines (I'm not an expert in C#, I'm just putting things together for a program at work.)
Here are bullet points of its basic structure
User clicks a "Start backup" button as seen in the screenshot
Button begins a separate function that checks to see which method the user selected to grab a list of usernames from (LDAP or flat text file)
That function then sends off a bgw_dowork() request
Inside the DoWork request, it looks like a summary of:
Check preliminary statements (bgw.cancellationpending for example)
Move on to grabbing some settings from the configurationmanager.appsettings
Begin the "complex" Parallel.ForEach command which Reads the listbox record rows and foreach row performs a very long list of commands to complete an operation for one user
The entire program, especially bgw_dowork heavily uses Google's v3 Drive API to login as a user, grab a file as recorded by other functions that prepare the user directory to be backed up (separate functions which login as a user, record their files (and fileIds) and their directories/subdirectories) and the bgw_dowork performs a chunk of the actual download functionality, which then calls off to the other functions to finish moving the files after they have been downloaded.
The actual "code" I use is (and I promise it's not pretty...)
private void bgW_DoWork(object sender, DoWorkEventArgs e)
{
{
try
{
txtFile.ReadOnly = true;
btnStart.Text = "Cancel Backup";
var appSettings = ConfigurationManager.AppSettings;
string checkreplace = ConfigurationManager.AppSettings["checkreplace"];
string userfile = txtFile.Text;
int counter = 0;
int arraycount = 0;
if (bgW.CancellationPending)
{
e.Cancel = true;
stripLabel.Text = "Operation was canceled!";
}
else
{
for (int z = 0; z >= counter; z++)
{
if (bgW.CancellationPending)
{
e.Cancel = true;
stripLabel.Text = "Operation was canceled!";
break;
}
else
{
double totalresource = int.Parse(ConfigurationManager.AppSettings["multithread"]);
totalresource = (totalresource / 100);
//var opts = new ParallelOptions { MaxDegreeOfParallelism = Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * totalresource) * 1.0)) };
var opts = new ParallelOptions { MaxDegreeOfParallelism = 2 };
var part = Partitioner.Create(1, 100);
//foreach (ListViewItem name in lstBackupUsers.Items)
var checkforfinished = Parallel.ForEach(lstBackupUsers.Items.Cast<ListViewItem>(), name =>
{
try
{
string names = name.SubItems[0].Text;
lstBackupUsers.Items[arraycount].Selected = true;
lstBackupUsers.Items[arraycount].BackColor = Color.CornflowerBlue;
arraycount++;
stripLabel.Text = "";
Console.WriteLine("Selecting user: " + names.ToString());
txtLog.Text += "Selecting user: " + names.ToString() + Environment.NewLine;
txtCurrentUser.Text = names.ToString();
// Define parameters of request.
string user = names.ToString();
// Check if directory exists, create if not.
string savelocation = ConfigurationManager.AppSettings["savelocation"] + user + "\\";
if (File.Exists(savelocation + ".deltalog.tok"))
File.Delete(savelocation + ".deltalog.tok");
FileInfo testdir = new FileInfo(savelocation);
testdir.Directory.Create();
string savedStartPageToken = "";
var start = CreateService.BuildService(user).Changes.GetStartPageToken().Execute();
// This token is set by Google, it defines changes made and
// increments the token value automatically.
// The following reads the current token file (if it exists)
if (File.Exists(savelocation + ".currenttoken.tok"))
{
StreamReader curtokenfile = new StreamReader(savelocation + ".currenttoken.tok");
savedStartPageToken = curtokenfile.ReadLine().ToString();
curtokenfile.Dispose();
}
else
{
// Token record didn't exist. Create a generic file, start at "1st" token
// In reality, I have no idea what token to start at, but 1 seems to be safe.
Console.Write("Creating new token file.\n");
//txtLog.Text += ("Creating new token file.\n" + Environment.NewLine);
StreamWriter sw = new StreamWriter(savelocation + ".currenttoken.tok");
sw.Write(1);
sw.Dispose();
savedStartPageToken = "1";
}
string pageToken = savedStartPageToken;
int gtoken = int.Parse(start.StartPageTokenValue);
int mytoken = int.Parse(savedStartPageToken);
txtPrevToken.Text = pageToken.ToString();
txtCurrentToken.Text = gtoken.ToString();
if (gtoken <= 10)
{
Console.WriteLine("Nothing to save!\n");
//txtLog.Text += ("User has nothing to save!" + Environment.NewLine);
}
else
{
if (pageToken == start.StartPageTokenValue)
{
Console.WriteLine("No file changes found for " + user + "\n");
//txtLog.Text += ("No file changes found! Please wait while I tidy up." + Environment.NewLine);
}
else
{
// .deltalog.tok is where we will place our records for changed files
Console.WriteLine("Changes detected. Making notes while we go through these.");
lblProgresslbl.Text = "Scanning Drive directory.";
// Damnit Google, why did you change how the change fields work?
if (savedStartPageToken == "1")
{
statusStripLabel1.Text = "Recording folder list ...";
txtLog.Text = "Recording folder list ..." + Environment.NewLine;
exfunctions.RecordFolderList(savedStartPageToken, pageToken, user, savelocation);
statusStripLabel1.Text = "Recording new/changed files ... This may take a bit!";
txtLog.Text += Environment.NewLine + "Recording new/changed list for: " + user;
exfunctions.ChangesFileList(savedStartPageToken, pageToken, user, savelocation);
}
else
{
//proUserclass = proUser;
statusStripLabel1.Text = "Recording new/changed files ... This may take a bit!";
txtLog.Text += Environment.NewLine + "Recording new/changed list for: " + user + Environment.NewLine;
exfunctions.ChangesFileList(savedStartPageToken, pageToken, user, savelocation);
}
// Get all our files for the user. Max page size is 1k
// after that, we have to use Google's next page token
// to let us get more files.
StreamWriter logFile = new StreamWriter(savelocation + ".recent.log");
string[] deltafiles = File.ReadAllLines(savelocation + ".deltalog.tok");
int totalfiles = deltafiles.Count();
int cnttototal = 0;
Console.WriteLine("\nFiles to backup:\n");
if (deltafiles == null)
{
return;
}
else
{
double damn = ((gtoken - double.Parse(txtPrevToken.Text)));
damn = Math.Round((damn / totalfiles));
if (damn <= 0)
damn = 1;
foreach (var file in deltafiles)
{
try
{
if (bgW.CancellationPending)
{
stripLabel.Text = "Backup canceled!";
e.Cancel = true;
break;
}
DateTime dt = DateTime.Now;
string[] foldervalues = File.ReadAllLines(savelocation + "folderlog.txt");
cnttototal++;
bgW.ReportProgress(cnttototal);
proUser.Maximum = int.Parse(txtCurrentToken.Text);
stripLabel.Text = "File " + cnttototal + " of " + totalfiles;
double? mathisfun;
mathisfun = ((100 * cnttototal) / totalfiles);
if (mathisfun <= 0)
mathisfun = 1;
double mathToken = double.Parse(txtPrevToken.Text);
mathToken = Math.Round((damn + mathToken));
// Bring our token up to date for next run
txtPrevToken.Text = mathToken.ToString();
File.WriteAllText(savelocation + ".currenttoken.tok", mathToken.ToString());
int proval = int.Parse(txtPrevToken.Text);
int nowval = int.Parse(txtCurrentToken.Text);
if (proval >= nowval)
proval = nowval;
proUser.Value = (proval);
lblProgresslbl.Text = ("Current progress: " + mathisfun.ToString() + "% completed.");
// Our file is a CSV. Column 1 = file ID, Column 2 = File name
var values = file.Split(',');
string fileId = values[0];
string fileName = values[1];
string mimetype = values[2];
mimetype = mimetype.Replace(",", "_");
string folder = values[3];
string ext = null;
int folderfilelen = foldervalues.Count();
fileName = GetSafeFilename(fileName);
Console.WriteLine("Filename: " + values[1]);
logFile.WriteLine("ID: " + values[0] + " - Filename: " + values[1]);
logFile.Flush();
// Things get sloppy here. The reason we're checking MimeTypes
// is because we have to export the files from Google's format
// to a format that is readable by a desktop computer program
// So for example, the google-apps.spreadsheet will become an MS Excel file.
switch (mimetype)
{
(switch statement here removed due to body length issues for this post.)
}
if (ext.Contains(".doc") || ext.Contains(".xls"))
{
string whatami = null;
if (ext.Contains(".xls"))
{
whatami = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
else if (ext.Contains(".doc"))
{
whatami = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
else if (ext.Contains(".ppt"))
{
whatami = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
}
if (fileName.Contains(".mov") || ext == ".ggl" || fileName.Contains(".mp4"))
{
txtLog.Text += Environment.NewLine + "Skipping file.";
return;
}
var requestfileid = CreateService.BuildService(user).Files.Export(fileId, whatami);
statusStripLabel1.Text = (savelocation + fileName + ext);
txtCurrentUser.Text = user;
string dest1 = Path.Combine(savelocation, fileName + ext);
var stream1 = new System.IO.FileStream(dest1, FileMode.OpenOrCreate, FileAccess.ReadWrite);
scrolltobtm();
requestfileid.MediaDownloader.ProgressChanged +=
(IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
logFile.WriteLine("Downloading: " + progress.BytesDownloaded);
txtLog.Text += ("Downloading ... " + progress.BytesDownloaded + Environment.NewLine);
scrolltobtm();
logFile.Flush();
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
logFile.WriteLine("[" + user + "] Download complete for: " + requestfileid.ToString());
txtLog.Text += ("[" + user + "] Download complete for: " + fileName + Environment.NewLine);
logFile.Flush();
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
logFile.WriteLine("Download failed.");
logFile.Flush();
break;
}
}
};
scrolltobtm();
GC.Collect();
GC.WaitForPendingFinalizers();
requestfileid.Download(stream1);
stream1.Close();
stream1.Dispose();
}
else
{
scrolltobtm();
var requestfileid = CreateService.BuildService(user).Files.Get(fileId);
//Generate the name of the file, and create it as such on the local filesystem.
statusStripLabel1.Text = (savelocation + fileName + ext);
string dest1 = Path.Combine(savelocation, fileName + ext);
var stream1 = new System.IO.FileStream(dest1, FileMode.OpenOrCreate, FileAccess.ReadWrite);
requestfileid.MediaDownloader.ProgressChanged +=
(IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
logFile.WriteLine("Downloading: " + progress.BytesDownloaded);
txtLog.Text += ("Downloading ... " + progress.BytesDownloaded + Environment.NewLine);
scrolltobtm();
logFile.Flush();
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
logFile.WriteLine("Download complete for: " + requestfileid.ToString());
txtLog.Text += (Environment.NewLine + "[" + user + "] Download complete for: " + fileName + Environment.NewLine);
logFile.Flush();
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
logFile.WriteLine("Download failed.");
logFile.Flush();
break;
}
}
};
scrolltobtm();
GC.Collect();
GC.WaitForPendingFinalizers();
requestfileid.Download(stream1);
stream1.Close();
stream1.Dispose();
}
}
catch (Google.GoogleApiException ex)
{
Console.Write("\nInfo: ---> " + ex.Message.ToString() + "\n");
}
}
}
exfunctions.MoveFiles(savelocation);
Console.WriteLine("\n\n\tBackup completed for selected user!");
txtLog.Text += ("\n\nBackup completed for selected user.\n\n");
statusStripLabel1.Text = "";
//logFile.Close();
//logFile.Dispose();
}
}
}
catch (Google.GoogleApiException ex)
{
Console.WriteLine("Info: " + ex.Message.ToString());
}
}
);
if (checkforfinished.IsCompleted == true)
{
MessageBox.Show("Parallel.ForEach() Finished!");
Console.WriteLine("Parallel.ForEach() Finished!");
}
else
{
MessageBox.Show("Parallel.ForEach() not completed!");
Console.WriteLine("Parallel.ForEach() not completed!");
}
}
}
}
}
catch (Google.GoogleApiException ex)
{
Console.WriteLine("Info: " + ex.Message.ToString());
}
}
}
You can see where I initiate the Parallel.ForEach(...) and then see what it is in charge of doing. It's a lot, and I understand it's not pretty, so I appreciate constructive criticism.
I have done everything how is in this question. everything is alright except one. I can't save the taken snapshot. If I'll follow with debug everything is alright.. what's wrong?
public class FFMPEG
{
Process ffmpeg;
public void exec(string input, string parametri, string output)
{
ffmpeg = new Process();
ffmpeg.StartInfo.Arguments = " -i " + input + (parametri != null ? " " + parametri : "") + " " + output;
ffmpeg.StartInfo.FileName = HttpContext.Current.Server.MapPath("~/ffmpeg.exe");
ffmpeg.StartInfo.UseShellExecute = false;
ffmpeg.StartInfo.RedirectStandardOutput = true;
ffmpeg.StartInfo.RedirectStandardError = true;
ffmpeg.StartInfo.CreateNoWindow = true;
ffmpeg.Start();
ffmpeg.WaitForExit();
ffmpeg.Close();
}
public void GetThumbnail(string video, string jpg, string velicina)
{
if (velicina == null) velicina = "640x480";
exec(video, "-ss 00:00:06 " + velicina, jpg);
}
}
FFMPEG f = new FFMPEG();
f.GetThumbnail(Server.MapPath("~/Uploads/" + unique), Server.MapPath("~/Thumbnails/" + unique.Remove(unique.IndexOf(".")) + ".jpg"), "1200x223");
I assume you are extracting 640x480 thumbnails, and velicina is the parameter used to specify the resolution judging by the partial code you posted. In this case, you have a ffmpeg syntax error and you can change GetThumbnail function as belowing for a try:
public void GetThumbnail(string video, string jpg, string velicina)
{
if (velicina == null) velicina = "640x480";
exec(video, "-ss 00:00:06 -s" + velicina, jpg);
}
Specially, -s tells ffmpeg the resolution for the output. Try whether it works out.
I just recently posted something earlier regarding a C# game project I am working on in Microsoft visual C# express and after trial and error the code that I have presented underneath will not work. Does anyone have any advice or help they could give me on how to get it to work? the part of the code with the brackets and asterisks and arrows is the error that will not work for me. (NOTE: I am making a Form on Microsoft Visual C# express.)
if (buttonFlag[0])
{
return;
}
if (accept)
{
return;
}
textBox2.Text = "";
textBox1.Text = "";
offerCounter++;
---> [[[ **pictureBox2.Image**]]]<--- = tempLabel = buttonList[0].ToString();
LostValues(tempLabel);
textBox1.Text = "-> you just opend " + tempLabel + "\n";
CallZero(tempLabel);
if (offerCounter == 20)
{
finalValue = GetFinalValue();
MessageBox.Show("You win " + finalValue.ToString());
textBox1.Text = "Game is over" + "\n";
textBox1.Text += "you won: " + finalValue.ToString();
label16.Content = "you won:";
label17.Content = finalValue.ToString();
label18.Text = "Game Over";
accept = true;
}
if (offerCounter <= 18)
{
if ((offerCounter % 3) == 0)
{
GenerateNewOffer();
textBox1.Text += "-> you have a new offer ";
MessageBox.Show("you recieved a new offer !");
textBox2.Text = newOffer.ToString();
}
else
{
offerRemainder = 3 - (offerCounter % 3);
textBox1.Text += "-> Open " + offerRemainder.ToString() + "more box(es) for new offer";
}
}
else
{
textBox2.Text = "";
}
The PictureBox.Image Property takes an Image instance. Read MSDN for both and code accordingly.
I trying to capture packets using SharpPcap library.
I'm able to return the packets details but I'm having problem to get what the message content inside the packet.
the packet using .Data to return the message and when I use it it is returning (System.Byte[]).
here is the library website:
http://www.codeproject.com/KB/IP/sharppcap.aspx
here is my code:
string packetData;
private void packetCapturingThreadMethod()
{
Packet packet = null;
int countOfPacketCaptures = 0;
while ((packet = device.GetNextPacket()) != null)
{
packet = device.GetNextPacket();
if (packet is TCPPacket)
{
TCPPacket tcp = (TCPPacket)packet;
myPacket tempPacket = new myPacket();
tempPacket.packetType = "TCP";
tempPacket.sourceAddress = Convert.ToString(tcp.SourceAddress);
tempPacket.destinationAddress = Convert.ToString(tcp.DestinationAddress);
tempPacket.sourcePort = Convert.ToString(tcp.SourcePort);
tempPacket.destinationPort = Convert.ToString(tcp.DestinationPort);
tempPacket.packetMessage = Convert.ToString(tcp.Data);
packetsList.Add(tempPacket);
packetData =
"Type= TCP" +
" Source Address = "+ Convert.ToString(tcp.SourceAddress)+
" Destination Address =" +Convert.ToString(tcp.DestinationAddress)+
" SourcePort =" + Convert.ToString(tcp.SourcePort)+
" SourcePort =" +Convert.ToString(tcp.DestinationPort)+
" Messeage =" + Convert.ToString(tcp.Data);
txtpackets.Invoke(new UpdatetxtpacketsCallback(this.Updatetxtpackets),
new object[] { packetData });
string[] row = { packetsList[countOfPacketCaptures].packetType, packetsList[countOfPacketCaptures].sourceAddress, packetsList[countOfPacketCaptures].destinationAddress, packetsList[countOfPacketCaptures].sourcePort, packetsList[countOfPacketCaptures].destinationPort, packetsList[countOfPacketCaptures].packetMessage };
try { //dgwPacketInfo.Rows.Add(row); countOfPacketCaptures++;
//lblCapturesLabels.Text = Convert.ToString(countOfPacketCaptures);
}
catch (Exception e) { }
}
else if (packet is UDPPacket)
{
UDPPacket udp = (UDPPacket)packet;
myPacket tempPacket = new myPacket();
tempPacket.packetType = "UDP";
tempPacket.sourceAddress = Convert.ToString(udp.SourceAddress);
tempPacket.destinationAddress = Convert.ToString(udp.DestinationAddress);
tempPacket.sourcePort = Convert.ToString(udp.SourcePort);
tempPacket.destinationPort = Convert.ToString(udp.DestinationPort);
tempPacket.packetMessage = udp.Data.ToArray() + "\n";
packetsList.Add(tempPacket);
packetData =
"Type= UDP" +
" Source Address = "+ Convert.ToString(udp.SourceAddress)+
" Destination Address =" +Convert.ToString(udp.DestinationAddress)+
" SourcePort =" + Convert.ToString(udp.SourcePort)+
" SourcePort =" +Convert.ToString(udp.DestinationPort)+
" Messeage =" + udp.Data.ToArray() + "\n";
string[] row = { packetsList[countOfPacketCaptures].packetType, packetsList[countOfPacketCaptures].sourceAddress, packetsList[countOfPacketCaptures].destinationAddress, packetsList[countOfPacketCaptures].sourcePort, packetsList[countOfPacketCaptures].destinationPort, packetsList[countOfPacketCaptures].packetMessage };
try {
//dgwPacketInfo.Rows.Add(row);
//countOfPacketCaptures++;
//lblCapturesLabels.Text = Convert.ToString(countOfPacketCaptures);
txtpackets.Invoke(new UpdatetxtpacketsCallback(this.Updatetxtpackets),
new object[] { packetData });
}
catch (Exception e) { }
}
}
}
I found the answer...
Data is a byte array so I need to use bit converter and instead of using:
Convert.ToString(tcp.Data);
I should use:
BitConverter.ToString(tcp.Data)
The parser isn't that complex...
I looked at the Packet.Net code (which is the parse for SharpPcap) and all of the fields are stored in commonly used formats.
The IP Addresses are stored in System.Net.IPAddress format so you can just call .ToString on them to get a text string that properly includes the dot marks.
The port numbers are stored as ushort which can be printed the same as any other integer.
The only part that needs to be interpreted in its binary form is the Data field because that changes based on what protocol is being used on the next layer up. SharpPcap/Packet.Net does most of the work for you already and fields are stored in the most convenient or identical forms to those found in the protocol specification. Just use intellisense to check the field's type and if it's not one you're familiar with (such as System.Net.IPAddress or System.NetworkInformation.PhysicalAddress (For MAC addresses)) just google it.