Alternative for If-else - c#

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;
}
}

Related

Keep int variables values from dataReader c#

I don't have much experience with C# but I am trying to make a simple windows forms app with personal finances.
So, I have 2 dataReader (I am using the Oracle provider), and the sql (oracle table) commands that select only 2 columns from a table, only with 1 value, mainly income 1 and income2 and the sum of all values from a specific month.
the sql strings look like this:
strSQL_sel_income1 = "select DISTINCT categorie,SUM(suma) from financiar where main_categ='income' and categorie IN ('income1') and EXTRACT(month FROM data)=" + luna_income + " Group by categorie";
strSQL_sel_income2 = "select DISTINCT categorie,SUM(suma) from financiar where main_categ='income' and categorie IN ('Income2') and EXTRACT(month FROM data)=" + luna_income + " Group by categorie";
the "luna_income" value is taken from a combobox where I select a specific month.
The problem is when I try to declare an Int variable from the values I get with data reader and these variables are not kept outside the while statement... dr_income1/2 being the dataReader
if (dr_income1.HasRows)
{
while (dr_income1.Read())
{
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
int suma_income1 = dr_incomei1.GetInt32(1);
}
}
else
{
label26.Text = "No info;
}
so, I have two similar data readers and two int variables suma_income1 and suma_income2. If I try to make a sum of them, outside the WhIle codes, I get a zero value. Where should I declare the two variables and how to keep their values?
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "Income total: " + suma_income_total;
The suma_income_total is ZERO!!!
dr_income1 = cm1.ExecuteReader();
dr_income2 = cm2.ExecuteReader();
label26.Text = "";
label28.Text = "";
if (dr_income1.HasRows)
{
while (dr_income1.Read())
{
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
int suma_income1 = dr_income1.GetInt32(1);
}
}
else
{
label26.Text = "No info";
}
if (dr_income2.HasRows)
{
while (dr_income2.Read())
{
label28.Text = dr_income2.GetString(0) + ": " + dr_income2.GetInt32(1) + "\n";
int suma_income2 = dr_income2.GetInt32(1);
}
}
else
{
label28.Text = "no info";
}
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "income total: " + suma_income_total;
dr_income2.Close();
dr_income1.Close();
I put some changes in your code. It is not ideal since there are several much simple ways. But it is ok as workaround:
dr_income1 = cm1.ExecuteReader();
dr_income2 = cm2.ExecuteReader();
label26.Text = "";
label28.Text = "";
var suma_income1 =0;
var suma_income2 =0;
if (dr_income1.HasRows)
{
while (dr_income1.Read())
{
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
suma_income1 += dr_income1.GetInt32(1);
}
}
else
{
label26.Text = "No info";
}
if (dr_income2.HasRows)
{
while (dr_income2.Read())
{
label28.Text = dr_income2.GetString(0) + ": " + dr_income2.GetInt32(1) + "\n";
suma_income2 += dr_income2.GetInt32(1);
}
}
else
{
label28.Text = "no info";
}
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "income total: " + suma_income_total;
dr_income2.Close();
dr_income1.Close();

Doesn't parse updated row from LinqToSQLDataClass to Database LINQ C# WPF

I'm building an Edit/Update system in my program using Linq in C# WPF.
My problem is that my code does submit to the LinqToSQLDatacontex but doesn't parse it through to the actual Database.
The result of that is that the datarow is updated in Runtime but in fact isn't updated in the actual Database.
this is the code I use for Updating my rows.
private void dgUsers_MouseUp(object sender, MouseButtonEventArgs e)
{
try
{
item = dgUsers.SelectedItem;
this.name = (dgUsers.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
var query =
from t in db.tbl_Users
where t.Name == name
select t;
foreach (var q in query)
{
tbMoreName.Text = q.Name;
tbMoreRights.Text = q.Rights;
tbMoreTag.Text = q.Operatortag;
checkMoreActive.IsChecked = q.Active;
tbMoreCardCode.Text = q.CardCode;
}
var table =
from q in db.tbl_UserProfiles
where q.Userprofile == tbMoreRights.Text
select q;
}
catch (Exception exc)
{
MessageBox.Show("NOPE");
}
}
private void btnSaveUser_Click(object sender, RoutedEventArgs e)
{
switch (saveType)
{
case "Edit":
#region save Edit User
var edit =
(from t in db.tbl_Users
where t.Name == name
select t).First();
MessageBox.Show(edit.Id.ToString() + " " + edit.Name.ToString() + " " + edit.Operatortag.ToString() + " " + edit.Rights.ToString() + " " + edit.Active.ToString());
edit.Id = edit.Id;
edit.Name = tbName.Text;
edit.Operatortag = tbOperatortag.Text;
edit.Rights = cbRights.Text;
edit.Active = checkActive.IsChecked.Value;
edit.CardCode = tbCardcode.Text;
MessageBox.Show(edit.Id.ToString() + " " + edit.Name.ToString() + " " + edit.Operatortag.ToString() + " " + edit.Rights.ToString() + " " + edit.Active.ToString() + " " + edit.CardCode.ToString());
db.SubmitChanges();
#endregion
saveType = "";
break;
}
var refresh =
(from q in db.tbl_Users
select new { Name = q.Name, Rights = q.Rights, Operatortag = q.Operatortag, Active = q.Active, Cardcode = q.CardCode }).ToList();
dgUsers.ItemsSource = null;
dgUsers.ItemsSource = refresh;
MessageBox.Show(refresh[0].ToString() + " " + refresh[1].ToString() + " " + refresh[2].ToString() + " " + refresh[3].ToString() + " " + refresh[4].ToString());
}
I hope that one of you guys can help me.
Thanks in advance!!!

Parallel.ForEach(...) System Out of Memory exception

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.

response redirect makes session_end in global asax

I am getting frustrated due to the session become null.When I click on save button I save the data to DB from code behind and if this successfully I am redirecting the user to the main projects page,using syntax:
Response.Redirect("~/Admin/Projects.aspx?i=esc&prjName=abc",'false');
but its make my session null.Its goes to Globex.asax page ang executes the Session_End and make all session null.
I even tried Server.Transfer but by this the browser url remains same and client doesn't want this.Even some where I read that the Server.Execute is also used to redirect but it is showing some wrong results.
can I use the Response.Redirect without this session null problem ??
(In this page I am creating the text file to store some long description and if this is successful then I am redirecting to the another page.)
Update::
here is my code for button click
protected void lnkbtnAddDescription_Click(object sender, EventArgs e)
{
try
{
if ((!hidProjId.Value.ToString().Equals("") || !hidEditProjId.Value.ToString().Equals("")) && !txtDescription.Value.ToString().Equals(""))
{
//ProjectDescription
int projId = 0;
if (!hidIsEdit.Value.ToString().Equals(""))
{
projId = Convert.ToInt32(hidEditProjId.Value.ToString());
}
else
{
projId = Convert.ToInt32(hidProjId.Value.ToString());
}
ProjectM proj = new ProjectM();
proj.LoadByKey(projId);
string prj = proj.ProjectName.ToString().Replace(" ", "-");
string strDirectoryPath = Server.MapPath("~/ProjectDescription/") + proj.ProjectId + "-" + prj;
if (!Directory.Exists(strDirectoryPath))
{
Directory.CreateDirectory(strDirectoryPath);
string filePath = strDirectoryPath + "/" + proj.ProjectId + "-" + prj + ".txt";
string strDescription = txtDescription.Value.ToString().Replace("<br />", "<p>");
createTextFile(filePath, strDescription);
string dbDirectoryPath = "~/ProjectDescription/" + proj.ProjectId + "-" + prj + "/" + proj.ProjectId + "-" + prj + ".txt";
proj.Description = dbDirectoryPath.ToString();
proj.IsNew = false;
proj.Save();
if (!hidIsEdit.Value.ToString().Equals(""))
{
//Server.Execute("~/SuperAdmin/Projects.aspx?i=esc&prjName=" + proj.ProjectName.ToString() + "",false);
Session["dsProj"] = null;
Session["editProjId"] = null;
Session["fname"] = hidFname.Value.ToString();
Session["UserId"] = hidUserId.Value.ToString();
Session["role"] = hidRole.Value.ToString();
Response.Redirect("~/SuperAdmin/Projects.aspx?i=esc&prjName=" + proj.ProjectName.ToString());
}
else
{
//Server.Execute("~/SuperAdmin/Projects.aspx?i=sc&prjName=" + proj.ProjectName.ToString() + "",false);
Session["dsProj"] = null;
Session["editProjId"] = null;
Session["fname"] = hidFname.Value.ToString();
Session["UserId"] = hidUserId.Value.ToString();
Session["role"] = hidRole.Value.ToString();
Response.Redirect("~/SuperAdmin/Projects.aspx?i=sc&prjName=" + proj.ProjectName.ToString());
}
}
else
{
Directory.Delete(strDirectoryPath, true);
Directory.CreateDirectory(strDirectoryPath);
string fileName = proj.ProjectName.ToString().Replace(" ", "-");
string filePath = strDirectoryPath + "/" + proj.ProjectId + "-" + fileName + ".txt";
string strDescription = txtDescription.Value.ToString().Replace("<br>", "<p>");
createTextFile(filePath, strDescription);
string dbDirectoryPath = "~/ProjectDescription/" + proj.ProjectId + "-" + proj.ProjectName.ToString() + "/" + proj.ProjectId + "-" + proj.ProjectName.ToString() + ".txt";
proj.Description = dbDirectoryPath.ToString();
proj.IsNew = false;
proj.Save();
if (!hidIsEdit.Value.ToString().Equals(""))
{
//Server.Execute("~/SuperAdmin/Projects.aspx?i=esc&prjName=" + proj.ProjectName.ToString() + "", false);
Session["dsProj"] = null;
Session["editProjId"] = null;
Session["fname"] = hidFname.Value.ToString();
Session["UserId"] = hidUserId.Value.ToString();
Session["role"] = hidRole.Value.ToString();
Response.Redirect("~/SuperAdmin/Projects.aspx?i=esc&prjName=" + proj.ProjectName.ToString());
}
else
{
//Server.Execute("~/SuperAdmin/Projects.aspx?i=sc&prjName=" + proj.ProjectName.ToString() + "", false);
Session["dsProj"] = null;
Session["editProjId"] = null;
Session["fname"] = hidFname.Value.ToString();
Session["UserId"] = hidUserId.Value.ToString();
Session["role"] = hidRole.Value.ToString();
Response.Redirect("~/SuperAdmin/Projects.aspx?i=sc&prjName=" + proj.ProjectName.ToString());
}
}
}
}
catch (Exception)
{
}
}
private void createTextFile(string filePath, string strDescription)
{
try
{
StreamWriter w = File.CreateText(filePath);
w.WriteLine(strDescription);
w.Flush();
w.Close();
}
catch (Exception ex)
{
}
}
Before you redirect to the next page,
assign the existing session value in the button click event also.
This would solve the problem.
hope this will be helpful to you,
ASP.NET Session becomes null after postback on local
This think your problem is related to some kind of permission denial, which is nulling your session.
There must be a problem in creating or saving the text file.
This may be making Session_End call so you are getting all values null.
Folder delete, move, rename causes Session end and long refresh
http://www.telerik.com/community/forums/aspnet-ajax/file-explorer/folder-delete-move-rename-causes-session-end-and-long-refresh.aspx#1365780

C# Adding values to pictureboxes

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.

Categories