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.
Related
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'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.
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 an details view that is attached to a sql datasource. When a new workorder is inserted i am sending an email. Right now there is some issue with my program and the user is not able to insert the data from my application but the email still gets send assuming the data is inserted.
This is my Details View Inserted Method:
protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
if (successfull == true && Page.IsValid && e.AffectedRows ==1)
{
//TextBox TextBoxWorkOrderNumber = (TextBox)(DetailsView1.FindControl("TextBox11"));
TextBox TextBoxRequestor = (TextBox)(DetailsView1.FindControl("TextBox3"));
TextBox TextBoxDate = (TextBox)(DetailsView1.FindControl("TextBox1"));
//TextBoxDate.Text = DateTime.Now.ToShortDateString();
TextBox TextBoxDepartment = (TextBox)(DetailsView1.FindControl("TextBox4"));
TextBox TextBoxCompletionDate = (TextBox)(DetailsView1.FindControl("TextBox16"));
TextBox TextBoxMachineDescription = (TextBox)(DetailsView1.FindControl("TextBox5"));
TextBox TextBoxMachineLocation = (TextBox)(DetailsView1.FindControl("TextBox6"));
TextBox TextBoxWorkRequired = (TextBox)(DetailsView1.FindControl("TextBox7"));
// DropDownList status = (DropDownList)(DetailsView1.FindControl("DropDownList2"));
TextBox TextBoxStatus = (TextBox)(DetailsView1.FindControl("TextBox12"));
TextBoxStatus.Text = "Open";
DropDownList list = (DropDownList)(DetailsView1.FindControl("DropDownList1"));
TextBox9.Text = list.SelectedValue;
DropDownList lists = (DropDownList)(DetailsView1.FindControl("DropDownList2"));
TextBox14.Text = lists.SelectedValue;
if (TextBoxRequestor.Text.Length <= 0)
{
TextBoxRequestor.Text = "Not Applicable";
}
if (TextBox14.Text.Length <= 0)
{
TextBoxDepartment.Text = "Not Provided";
}
if (TextBoxCompletionDate.Text.Length <= 0)
{
TextBoxCompletionDate.Text = "Not Provided";
}
if (TextBoxMachineDescription.Text.Length <= 0)
{
TextBoxMachineDescription.Text = "Not Provided";
}
if (TextBoxMachineLocation.Text.Length <= 0)
{
TextBoxMachineLocation.Text = "Not Provided";
}
if (TextBoxWorkRequired.Text.Length <= 0)
{
TextBoxWorkRequired.Text = "Not Provided";
}
if (TextBox9.Text == "Safety" && e.AffectedRows==1)
{
{
bool isLocal = HttpContext.Current.Request.IsLocal;
if (isLocal == true)
{
string id = TextBox13.Text.ToString();
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();
mm.From = new System.Net.Mail.MailAddress("no_reply_workorder#.com");//who send
mm.To.Add(new System.Net.Mail.MailAddress("abc#.com"));
//abc#abc.com
mm.Subject = "WorkOrders Type Safety";
mm.Body = "DO NOT REPLY TO THIS EMAIL" + "<br><br/>" + "WorkOrderNumber"
+ ": " + "<a href=\"http://localhost:49695/SafetyReport.aspx?WorkOrderNum=" + TextBox13.Text + "\">"
+ TextBox13.Text + "</a>" + "<-Click on the Work Order Number For Report"
+ "<br><br/>" + "WorkOrderNumber" + ": " +
"<a href=\"http://localhost:49695/Safety.aspx?WorkOrderNum=" +
TextBox13.Text + "\">" + TextBox13.Text + "</a>" +
"<-Click on this Work Order Number To Enter Data" +
"<br><br/>" + "Requestor" + ": " + TextBoxRequestor.Text +
"<br><br/>" + "Date" + ": " + TextBoxDate.Text +
"<br><br/>" + "Department" + ": " + TextBox14.Text +
"<br><br/>" + "Machine Description" + ": " +
TextBoxMachineDescription.Text + "<br><br/>" +
"Machine Location" + ": " +
TextBoxMachineLocation.Text + "<br><br/>" +
"Work Required" + ": " + TextBoxWorkRequired.Text + "<br><br/>"
mm.IsBodyHtml = true;
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.Host = ConfigurationManager.AppSettings["smtpServer"];
client.Send(mm);
captureuseremail();
}
}
}
}
i see an DetailsView1_Item Inserting how can i check if that is inserting into the sql database?? if the inserting is successful i like to set a boolean value to true and if true then perform the Details_View1 Inserted and send email else cancel the insert.
i am also using the insert button that comes with the details view. please ask me for additional code if your confused and i would more than happily provide it.
please help :(
Added Additional code:
INSERT INTO Master(Requestor, Date, Department, CompletionDate, MachineDescription,
MachineLocation, [Type of Work Order], [Work Required], Status)
VALUES (#Requestor, #Date, #Department, #CompletionDate,
#MachineDescription, #MachineLocation, #Type_of_Work_Order,
#Work_Required, #Status); SET #NewId = Scope_Identity()
i just have a bool successfull; which i set to true at the end of Item_Inserting method().
when user clicks submit on the details view which is nothing but the command button insert then the code hits the item_inserting takes all the value
Item_Inserting of the details view:
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
if (Page.IsValid)
{
//TextBox TextBoxWorkOrderNumber = (TextBox)(DetailsView1.FindControl("TextBox11"));
TextBox TextBoxRequestor = (TextBox)(DetailsView1.FindControl("TextBox3"));
TextBox TextBoxDate = (TextBox)(DetailsView1.FindControl("TextBox1"));
//TextBoxDate.Text = DateTime.Now.ToShortDateString();
TextBox TextBoxDepartment = (TextBox)(DetailsView1.FindControl("TextBox4"));
TextBox TextBoxCompletionDate = (TextBox)(DetailsView1.FindControl("TextBox16"));
TextBox TextBoxMachineDescription = (TextBox)(DetailsView1.FindControl("TextBox5"));
TextBox TextBoxMachineLocation = (TextBox)(DetailsView1.FindControl("TextBox6"));
TextBox TextBoxWorkRequired = (TextBox)(DetailsView1.FindControl("TextBox7"));
// DropDownList status = (DropDownList)(DetailsView1.FindControl("DropDownList2"));
TextBox TextBoxStatus = (TextBox)(DetailsView1.FindControl("TextBox12"));
TextBoxStatus.Text = "Open";
DropDownList list = (DropDownList)(DetailsView1.FindControl("DropDownList1"));
TextBox9.Text = list.SelectedValue;
DropDownList lists = (DropDownList)(DetailsView1.FindControl("DropDownList2"));
TextBox14.Text = lists.SelectedValue;
if (TextBoxRequestor.Text.Length <= 0)
{
TextBoxRequestor.Text = "Not Applicable";
}
if (TextBox14.Text.Length <= 0)
{
TextBoxDepartment.Text = "Not Provided";
}
if (TextBoxCompletionDate.Text.Length <= 0)
{
TextBoxCompletionDate.Text = "Not Provided";
}
if (TextBoxMachineDescription.Text.Length <= 0)
{
TextBoxMachineDescription.Text = "Not Provided";
}
if (TextBoxMachineLocation.Text.Length <= 0)
{
TextBoxMachineLocation.Text = "Not Provided";
}
if (TextBoxWorkRequired.Text.Length <= 0)
{
TextBoxWorkRequired.Text = "Not Provided";
}
successfull = true;
}
else
{
e.Cancel = true;
successfull = false;
}
}
This is Where the actual insert takes place, its my sqldatasource:
**all the values from the item_inserting are inserted here with an identity value **
protected void RequestorSource_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
if (successfull == true)
{
try
{
int newid = (int)e.Command.Parameters["#NewId"].Value;
TextBox13.Text = newid.ToString();
}
catch
{
successfull = false;
}
if (e.AffectedRows == 1 && successfull == true)
{
successfull = true;
}
else
{
successfull = false;
}
}
else
{
successfull = false;
}
}
the issue is the email is still getting sent when i stop the program, how can i create a bad insert like i want it to fail similar what is happening to the user i am not able to recreate the issue for example i tried adding a new field in the insert statement but did not give it any values and the error it threw was you have more columns then values.
This is a picture of my details view:
**all of the .cs code at http://pastebin.com/6VC6FZK7 and the .aspx code at http://pastebin.com/QhjWNNt0 ** hope this helps out a bit.
If you just setting the bool successful to true after the insert and have not done any error checking then it can fail and still send the email. I suggest either wrapping the insert code in a TRY..CATCH..and set the succssful state to false in the catch OR running a IF...ELSE.. to check if the data was inserted correctly and setting the successful state there.
I'm a noob programmer, 1 month into my first class. Right now i'm fooling around making a WINFORM-application in C# that is supposed to some sort of cash register for a bar.
The form consists of:
- 6 buttons named Drank1 to Drank6
- one OK button
- One textbox and button named total.
- a reset-button that accompanies each "drank" button.
The essence of the form is: you type in name, type, content and price in the textboxes and one of the drankbuttons gets a name & value. after youve named these buttons, you can press them a desirable amount of times then press total to get the price of every drink combined.
The form works as expected but i whas wondering. I wrote a if-else statement connected to the pressing of the OK button that needs to be pressed in order to declare values to the buttons.
I did this with the following piece of code.
private void btnValidate_Click(object sender, EventArgs e)
{
if (btnDrank1.Text == "Drank1")
{
btnDrank1.Text = txtNaam.Text + "\n" + txtInhoud.Text + "cl";
drank[0].Naam = txtNaam.Text;
drank[0].Inhoud = txtInhoud.Text;
drank[0].Prijs = Convert.ToDouble(txtPrijs.Text);
}
else
{
if (btnDrank2.Text == "Drank2")
{
btnDrank2.Text = txtNaam.Text + "\n" + txtInhoud.Text + "cl";
drank[1].Naam = txtNaam.Text;
drank[1].Inhoud = txtInhoud.Text;
drank[1].Prijs = Convert.ToDouble(txtPrijs.Text);
}
else
{
if (btnDrank3.Text == "Drank3")
{
btnDrank3.Text = txtNaam.Text + "\n" + txtInhoud.Text + "cl";
drank[2].Naam = txtNaam.Text;
drank[2].Inhoud = txtInhoud.Text;
drank[2].Prijs = Convert.ToDouble(txtPrijs.Text);
}
else
{
if (btnDrank4.Text == "Drank4")
{
btnDrank4.Text = txtNaam.Text + "\n" + txtInhoud.Text + "cl";
drank[3].Naam = txtNaam.Text;
drank[3].Inhoud = txtInhoud.Text;
drank[3].Prijs = Convert.ToDouble(txtPrijs.Text);
}
else
{
if (btnDrank5.Text == "Drank5")
{
btnDrank5.Text = txtNaam.Text + "\n" + txtInhoud.Text + "cl";
drank[4].Naam = txtNaam.Text;
drank[4].Inhoud = txtInhoud.Text;
drank[4].Prijs = Convert.ToDouble(txtPrijs.Text);
}
else
{
if (btnDrank6.Text == "Drank6")
{
btnDrank6.Text = txtNaam.Text + "\n" + txtInhoud.Text + "cl";
drank[5].Naam = txtNaam.Text;
drank[5].Inhoud = txtInhoud.Text;
drank[5].Prijs = Convert.ToDouble(txtPrijs.Text);
}
else
{
MessageBox.Show("6 dranken is genoeg!", "My Application",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
I was wondering if there is a way to reduce the amount of code and still get the same result. I was thinking maybe a foreach loop, but can't quite figure out how exactly to write one with custom classes.
Cheers
What you want is called a switch statement.
http://www.dotnetperls.com/string-switch
It would end up looking something like this:
switch (btnDrank2.Text)
{
case "Drank2":
btnDrank2.Text = txtNaam.Text + "\n" + txtInhoud.Text + "cl";
drank[1].Naam = txtNaam.Text;
drank[1].Inhoud = txtInhoud.Text;
drank[1].Prijs = Convert.ToDouble(txtPrijs.Text);
break;
case "Drank3":
btnDrank3.Text = txtNaam.Text + "\n" + txtInhoud.Text + "cl";
drank[2].Naam = txtNaam.Text;
drank[2].Inhoud = txtInhoud.Text;
drank[2].Prijs = Convert.ToDouble(txtPrijs.Text);
break;
}
etc. The code may have errors as I do not have access to a c# compiler.
Use the switch statement. in you case the code would be something like that
private void btnValidate_Click(object sender, EventArgs e)
{
string text = btnDrank4.Text;
switch(text)
{
case "Drank1":
btnDrank1.Text = txtNaam.Text + "\n" + txtInhoud.Text + "cl";
drank[0].Naam = txtNaam.Text;
drank[0].Inhoud = txtInhoud.Text;
drank[0].Prijs = Convert.ToDouble(txtPrijs.Text);
break;
case "Drank2":
// your code here
break;
// here the other cases
default ""
// here everything is not the previous values
// I suppose these lines
MessageBox.Show("6 dranken is genoeg!", "My Application",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
break;
}
}