I'm working on a C# console application that includes a chat group. I thought I had figured it out but it doesn't seems to work... I'm a total beginner, so the way I did it was to create a folder the program fills with .txt files with the message infos (no internet included). That worked to support the user/password/options part of the program but the chat is reacting weirdly. When you enter a message, it react and shows it on screen but when someone else post it you don't see it unless you restart the app. Here's the code:
chat_group:
temp1I = Directory.GetFiles((message_folder + "\\1-Groupe"), "*", SearchOption.AllDirectories).Length;
temp1S = temp1I.ToString();
System.IO.StreamReader ChatFile = new System.IO.StreamReader(message_folder + "\\1-Groupe\\" + temp1S + ".txt");
counter = 0;
while ((temp2S = ChatFile.ReadLine()) != null)
{
switch (counter)
{
case 0:
text = (temp2S + ": ");
WRITE_R();
break;
case 1:
text = (temp2S);
WRITE();
break;
}
counter++;
}
ChatFile.Close();
Console.WriteLine("");
test:
if (File.Exists((message_folder + "\\1-Groupe\\" + (temp1S + 1) + ".txt")))
{
goto chat_group;
}
if ((temp3S = Console.ReadLine()) != null)
{
temp1S = (temp1I + 1).ToString();
string[] ChatLines2 = { username, temp3S };
System.IO.File.WriteAllLines(message_folder + "\\1-Groupe\\" + temp1S + ".txt", ChatLines2);
}
goto test;
Note: As it is a big application, I've not copy the variables but I ensure they are correct as they work on all the other parts of the app.
Related
I am creating a C# .NET Mono application to read logs in from a text file and display them in a listview. The logs are stored in JSON format so they can be parsed easily and be displayed as subitems in the listview.
Picture of the working ListView run on Windows
My application is working correctly when I run the application on windows, however when I run it on the raspbian OS using mono none of the items in the listview are shown. I know that the logs are being read correctly from the text file on both Windows & Linux, as I have logged them to the console for debugging purposes. I have also confirmed that the logs have been copied into the ListViewItem "eachRow" correctly by logging it to the console as well.
I am hoping to find the problem that is causing the ListView Items to not be displayed when run on Raspbian. Due to the fact that I have the data stored correctly all the way up until it is added to the listview, I believe my problem is with the redrawing of the screen/listview.
This is the code I am using to Add each JSON item to the listview.
private void AddLogsToScreen()
{
//Create a copy of the current logList Stack
LogMutex.WaitOne();
Stack<string[]> logListCopy = new Stack<string[]>(new Stack<string[]>(LogList));
Console.WriteLine("LLC: " + string.Join(" , ", logListCopy.Peek()));
LogMutex.ReleaseMutex();
if (HUBsLogsListView.InvokeRequired)
{
HUBsLogsListView.Invoke(new MethodInvoker(delegate
{
MessageBox.Show("Invoke Begin Update");
HUBsLogsListView.BeginUpdate();
}));
}
else
{
MessageBox.Show("Begin Update");
HUBsLogsListView.BeginUpdate();
}
var allItemsToAdd = new List<ListViewItem>();
int totalLogs = logListCopy.Count;
for (int logNum = 0; logNum < totalLogs; logNum++)
{
string[] log = logListCopy.Pop();
string[] deepLogCopy = new string[8];
// Copy to avoid messing up original
log.CopyTo(deepLogCopy, 0);
deepLogCopy[2] = DateTime.Parse(log[2]).ToString("dd-MM-yyyy, hh:mm:ss tt");
ListViewItem eachRow = new ListViewItem(deepLogCopy);
Console.WriteLine("ListViewItem eachRow: " + eachRow.SubItems[0] + " , " + eachRow.SubItems[1] + " , " + eachRow.SubItems[2] + " , " + eachRow.SubItems[3] + " , " + eachRow.SubItems[4] + " , " + eachRow.SubItems[5] + " , " + eachRow.SubItems[6] + " , " + eachRow.SubItems[7]);
if (deepLogCopy[4] == "3") //Warning
{
eachRow.BackColor = Color.Yellow;
}
else if (deepLogCopy[4] == "4") //Error
{
eachRow.BackColor = Color.Red;
}
allItemsToAdd.Add(eachRow);
}
if (HUBsLogsListView.InvokeRequired)
{
HUBsLogsListView.Invoke(new MethodInvoker(delegate
{
ListView.ListViewItemCollection lvic = new ListView.ListViewItemCollection(HUBsLogsListView);
lvic.AddRange(allItemsToAdd.ToArray());
HUBsLogsListView.EndUpdate();
}));
}
else
{
ListView.ListViewItemCollection lvic = new ListView.ListViewItemCollection(HUBsLogsListView);
lvic.AddRange(allItemsToAdd.ToArray());
HUBsLogsListView.EndUpdate();
}
}
I can't come up with a reason why this function is acting differently, with the same files, on Windows compared to running on Linux using mono. I am not as experienced writing .NET programs using mono, so any and all help is appreciated.
Does anyone have any idea what could be the problem? Thanks!
I am working on a website ATM school project, and I need to be able to rewrite the account balance in the original .txt file based on session transactions. The .txt file contains 3 lines, each with (username),(password),(balance). The issue I'm having is that the program cannot write to file while it is still reading it. The loop works fine if I write to a different file, but I have to edit the original (so the updated balance is retained the next time the program is run). Below is the code from the Logout page load event.
//Stream variable
StreamReader readFile;
StreamWriter writeFile;
//Counter variable
int index = 0;
//Open file
readFile = File.OpenText(#"C:\C#\Project4_TSullivan\loginFile.txt");
//Array rows
const int ROWS = 3;
while (index < ROWS && !readFile.EndOfStream)
{
string str = readFile.ReadLine();
string[] tokens = str.Split(',');
//Check if username matches session username
if (tokens[0] == Convert.ToString(Session["sessionUserName"]))
{
//Update balance
tokens[2] = Convert.ToString(Session["sessionBalance"]);
}
if (index == 0)
{
writeFile = File.CreateText(#"C:\C#\Project4_TSullivan\loginFile.txt");
writeFile.WriteLine(tokens[0] + "," + tokens[1] + "," + tokens[2]);
writeFile.Close();
}
else
{
writeFile = File.AppendText(#"C:\C#\Project4_TSullivan\loginFile.txt");
writeFile.WriteLine(tokens[0] + "," + tokens[1] + "," + tokens[2]);
writeFile.Close();
}
index++;
}
//Close file
readFile.Close();
Please let me know if any additional info would be helpful. I may be going about this in entirely the wrong way, and any advice would be much appreciated. Thanks!
Edited
Here is the solution in case the mods want to save it. Using File.ReadAllLines I was able to store the contents of the file in an array. Then I created 3 more arrays (1 for each line in the file) to tokenize each line.
string path = #"C:\C#\Project4_TSullivan\loginFile.txt";
string[] readFile = File.ReadAllLines(path);
string[] token0 = readFile[0].Split(',');
string[] token1 = readFile[1].Split(',');
string[] token2 = readFile[2].Split(',');
if (token0[0] == Convert.ToString(Session["sessionUsername"]))
{
token0[2] = Convert.ToString(Session["sessionBalance"]);
}
else if (token1[0] == Convert.ToString(Session["sessionUsername"]))
{
token1[2] = Convert.ToString(Session["sessionBalance"]);
}
else
{
token2[2] = Convert.ToString(Session["sessionBalance"]);
}
using (StreamWriter writeFile = File.CreateText(path))
{
writeFile.WriteLine(token0[0] + "," + token0[1] + "," + token0[2]);
writeFile.WriteLine(token1[0] + "," + token1[1] + "," + token1[2]);
writeFile.WriteLine(token2[0] + "," + token2[1] + "," + token2[2]);
}
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.
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 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.