c# finding a string in a text file then do something? - c#

ok what im trying to do here is the following
private void addgsc()
{
if (File.Exists(hud))
{
{
string s = " itemDef\n\r"
+ "{"
+ " name \"zombiecounter\"\n\r"
+ " rect 100 70 0 0 HORIZONTAL_ALIGN_CENTER VERTICAL_ALIGN_BOTTOM\n\r "
+ " textscale .5\n\r"
+ " textstyle ITEM_TEXTSTYLE_SHADOWED\n\r"
+ " textfont UI_FONT_OBJECTIVE\n\r"
+ " textalign ITEM_ALIGN_CENTER\n\r"
+ " forecolor 1 0 0 1\n\r"
+ " exp text (\"Zombies Left: \" + dvarInt(\"zombie_counter\"))\n\r"
+ " visible when (dvarInt(\"zombie_counter\") > 0);\n\r"
+ "decoration\n\r"
+ "} ";
string file = hud;
List<string> lines = new List<string>(System.IO.File.ReadAllLines(file));
int index = lines.FindLastIndex(item => item.Contains("playerscores"));
if (index != -1)
{
lines.Insert(index + 1, s);//""
}
System.IO.File.WriteAllLines(file, lines);
MessageBox.Show("done");
}
}
and im looking for a line in a code like this
itemDef
{
name "playerscores"
rect 0 0 100 0
ownerdraw CG_COMPETITIVE_MODE_SCORES
visible 1
}
but what i want to do is find player scores then find the last } at the end and add it there because currently its adding it right under player scores but im not sure how i can get it to go to find that and then find the closest } one of those and add it under neath that so its in a new block not added into the player score one so would want something like the following
image 1

I'm a bit unclear of the desired output, so the below code may be more than what you need but should get you on the right track. Please forgive syntax errors.
EDIT: I reread the question a few times, and think this is what you are looking for.
var allLinesInFile = System.IO.File.ReadAllLines(file);
var isPlayerScore = false;
var linesToWrite = new List<string>();
var linesToAdd = new List<string> {
"itemDef\n\r",
"{",
" name \"zombiecounter\"\n\r",
//and so on
"}"
};
foreach (var line in allLinesInFile)
{
linesToWrite.Add(line);
if (line.IndexOf("playerscores", StringComparison.OrdinalIgnoreCase) >= 0)
{
//starting of data detected.
isPlayerScore = true;
}
else if (isPlayerScore == true && line.IndexOf("}") >= 0)
{
//end of data detected
isPlayerScore = false;
linesToWrite.AddRange(linesToAdd);
}
}
System.IO.File.WriteAllLines(file, linesToWrite);
MessageBox.Show("done");

Related

Google ortools - capacitated vehicle routing pb

The problem with the following code is :
even if I only have 10 locations to deliver and one depot set at location 0 , in this example, vehicles 1,2,3,4 seem to have they're depot at locations 10,11,12,13. Those locations don't exists. The 10 that I have are numbered from 0-9.
On the other hand the business logic seems to be OK :
as I isolated the cost of leaving the depot and the one of going back to it ( value 10 ) I get the expected result : 104. There are only 4 trips between cities that don't include the depot.
Is this a bug in Google or-tools ?
public static void Main(string[] args)
{
new CVRP().Solve(10);
}
private class RandomManhattan : NodeEvaluator2
{
public override long Run(int first_index, int second_index)
{
if (first_index == 0 || second_index == 0)
return 10;
return 1;
}
};
private class Demand : NodeEvaluator2
{
public override long Run(int first_index, int second_index)
{
return 1;
}
};
private void Solve(int locations)
{
var nr_vehicle = 5;
var routing = new RoutingModel(locations, nr_vehicle, new[] {0, 0, 0, 0, 0}, new[] {0, 0, 0, 0, 0});
Console.WriteLine("Depot : " + routing.GetDepot());
NodeEvaluator2 demandCallback = new Demand();
routing.AddDimension(demandCallback, 0, 3, true, "capacity");
var distances = new RandomManhattan();
routing.SetCost(distances);
var searchParameters =
RoutingModel.DefaultSearchParameters();
searchParameters.FirstSolutionStrategy =
FirstSolutionStrategy.Types.Value.PathCheapestArc;
var solution = routing.SolveWithParameters(searchParameters);
if (solution != null)
{
var output = "Total cost: " + solution.ObjectiveValue() + "\n";
// Dropped orders
var dropped = "";
for (var order = 0; order < locations; ++order)
{
if (solution.Value(routing.NextVar(order)) == order)
{
dropped += " " + order;
}
}
if (dropped.Length > 0)
{
output += "Dropped orders:" + dropped + "\n";
}
// Routes
for (var vehicle = 0; vehicle < nr_vehicle; ++vehicle)
{
var route = "Vehicle " + vehicle + ": ";
var order = routing.Start(vehicle);
if (routing.IsEnd(solution.Value(routing.NextVar(order))))
{
route += "Empty";
}
else
{
for (; !routing.IsEnd(order); order = solution.Value(routing.NextVar(order)))
{
var local_load = routing.CumulVar(order, "capacity");
route += order + " Load(" + solution.Value(local_load) + ") -> ";
}
if (route.Length > 0)
route = route + "0";
}
output += route + "\n";
}
Console.WriteLine(output);
}
}
You have to wrap order in
route += order + " Load(" + solution.Value(local_load) + ") -> ";
inside model.IndexToNode(order), like this
route += model.IndexToNode(order) + " Load(" + solution.Value(local_load) + ") -> ";

How to call a file for picturebox

I have a Form with 6 arrays, 15 elements each. I wrote them in a way that if I search for myself (being the 1st element in the string[] name array), the form would load the 1st element of every array: age, gender, hobby, photo etc.
Here is the part of the pictureBox code I'm using
//I have more arrays here, like: Name,Gender,Age,Hobby,Place & Talent
string[] photo=new string[] { "764.jpg", " 765.jpg", " 766.jpg", " 767.jpg"," 765.jpg", " 767.jpg", " 768.jpg", " 769.jpg", " 770.jpg", " 771.jpg", " 772.jpg", " 773.jpg", " 774.jpg", " 775.jpg", " 776.jpg"};
string name="",gender="",place="",warning=""; int age = 0; string image="";
for (int i = 0; i < 15; i++)
{
if (textBox6.Text == emri[i])
{
//I applied every element of every array to the declared variables
image = photo[i];
j++;
}
if (j == 1)
{
//Associated the textBoxes with the variables
pictureBox1.Image = Image.FromFile(#"C:\Users\NComputers\Documents\Visual Studio 2015\Projects\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\Sony Xperia\" + image);
}
else
{
MessageBox.Show("Person not found!");
}
While there are no errors shown, the picture simply doesn't load. All the other items are working. Help?

Count number of times an item appears in a list C#

It's suppose to allow the user to choose a team from the ListBox, click a button and display the number of times that team has won the World Series by referring to a .txt file (called World Series).
I'm trying to take the selected item and check how many times that selected item appears in the World Series .txt file.
Any pointers?
private void compareList()
{
StreamReader champFile = File.OpenText("WorldSeries.txt");
List<string> champList = new List<string>();
string selectedTeam;
while (!champFile.EndOfStream)
{
champList.Add(champFile.ReadLine());
}
while (teamList.SelectedIndex != 0)
{
selectedTeam = teamList.SelectedItem.ToString();
}
if (selectedTeam = champList???)
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + champList.????.Count + "times! ")
}
else
{
MessageBox.Show("The " + selectedTeam + "has never won the World Series.")
}
}
You can use File.ReadLines and some LINQ
selectedTeam = teamList.SelectedItem.ToString();
var count = File.ReadLines("WorldSeries.txt")
.Count(x => x.Contains(selectedTeam));
if(count > 0)
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + count + "times! ")
}
if (teamList.SelectedIndex == -1)
{
MessageBox.Show("Please select an Item first!");
return;
}
string selectedTeam = teamList.SelectedItem.ToString();
var count = File.ReadAllLines("WorldSeries.txt").Where(line => line ==selectedTeam).Count();
//var count = champList.Where(l=>l==selectedTeam).Count();
if (count >0)
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + count + "times! ");
}
else
{
MessageBox.Show("The " + selectedTeam + "has never won the World Series.")
}
You can do it simply this way
Updated Code
if(teamList.SelectedIndex != 0 && champList.Contains(SelectedTeam))
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + champList.Where(w => w == SelectedItem).Count() + "times! ");
}
Place the champList in a dictionary and increment a counter if they already exist.
private void compareList()
{
StreamReader champFile = File.OpenText("WorldSeries.txt");
Dictionary<string, int> champList = new Dictionary<string, int>();
string selectedTeam;
string currentChamp;
while (!champFile.EndOfStream)
{
currentChamp = champFile.ReadLine();
if(champList.containsKey(currentChamp))
champList.get(currentChamp) += 1;
else
champList.Add(champFile.ReadLine(), 1);
}
while (teamList.SelectedIndex != 0)
{
selectedTeam = teamList.SelectedItem.ToString();
}
if (champList.hasKey(selectedTeam))
{
MessageBox.Show("The " + selectedTeam + "has won the World Series " + champList.get(selectedTeam) + "times! ")
}
else
{
MessageBox.Show("The " + selectedTeam + "has never won the World Series.")
}
}

Adding +1 every time radiobox is used

I'm wanting to add +1 every time a radiobox or checkbox is used. This happens when calculate is pressed and putting it into a string then when the summary button is pushed it displays it in a messagebox with the final total of times it was pushed.
this is my code so far but it doesnt seem to work,
This is my Calculate button
int Quantity;
int Finalprice;
if (lunchRadioButton.Checked == true)
{
Meal = Lunch;
}
else if (tableCheckBox.Checked && waiterCheckBox.Checked)
{
Extras = Waiter + Table;
}
else if (waiterCheckBox.Checked)
{
Extras = Waiter;
}
else if (tableCheckBox.Checked)
{
Extras = Table;
}
//Early Evening Meal
if (earlyEveningRadioButton.Checked == true)
{
Meal = Early;
}
else if (tableCheckBox.Checked && waiterCheckBox.Checked)
{
Extras = Table + Waiter;
}
else if (waiterCheckBox.Checked)
{
Extras = Waiter;
}
else if (tableCheckBox.Checked)
{
Extras = Table;
}
//Late evening options
if (lateEveningRadioButton.Checked == true)
{
Meal = Late;
}
//Late Evening, Corner table and Dedicated waiter selected.
else if (tableCheckBox.Checked && waiterCheckBox.Checked)
{
Extras = Table + Waiter;
}
//Late Evening and Dedicated waiter selected.
else if (waiterCheckBox.Checked)
{
Extras = Waiter;
}
//Late Evening and Corner Table
else if (tableCheckBox.Checked)
{
Extras = Table;
;
}
try
{
Quantity = int.Parse(guestTextBox.Text);
Mealprice = (Meal * Quantity);
Finalprice = (Mealprice + Extras);
finalAmountLabel.Text = Finalprice.ToString("C");
}
catch
{
guestTextBox.Focus();
guestTextBox.SelectAll();
MessageBox.Show("Please enter a quantity in numerical form","Quantity Error!");
}
This is the Summary Button
int TotalLunch = 0;
int TotalEarly = 0;
int TotalLate = 0;
int TotalBookings = 0;
int TotalWaiters = 0;
int LateWaiters = 0;
int EarlyWaiters = 0;
int LunchWaiters = 0;
int TotalCornerTables = 0;
int EarlyCornerTables = 0;
int LateCornerTables = 0;
int LunchCornerTables = 0;
if (earlyEveningRadioButton.Checked == true)
{
TotalEarly = +1;
TotalEarly.ToString();
}
else if (earlyEveningRadioButton.Checked && waiterCheckBox.Checked)
{
EarlyWaiters = +1;
EarlyWaiters.ToString();
}
else if (tableCheckBox.Checked && earlyEveningRadioButton.Checked)
{
EarlyCornerTables = +1;
EarlyCornerTables.ToString();
}
else if (waiterCheckBox.Checked && tableCheckBox.Checked)
{
EarlyWaiters = +1;
EarlyCornerTables = +1;
EarlyWaiters.ToString();
EarlyCornerTables.ToString();
}
MessageBox.Show("Number of Early Bookings" + " " + TotalEarly + " " +
"Number of Early Evening Waiters" + " " + EarlyWaiters
+ "number of Early Evening Corner Tables tables" + " " + EarlyCornerTables
);
Any suggestions or help would be greately appriciated :)
The best way you can do this, is using the eventhandler CheckedChanged foreach checkbox.
in the event do this:
if(checkBox.Checked)
{
//int +1
}
I'll start with an answer to your question...
Your code will not increment TotalEarly by one, but it will assign +1 to the variable.
TotalEarly = +1;
For incrementing you should either use the ++ or the += operator:
TotalEarly++; // increments by 1
TotalEarly += 1; // also increments by 1, but += can be used with other numbers
Some other notes, not related to your question:
TotalEarly.ToString();
This will not do anything since you do not assign the result to a variable. This will not convert TotalEarly to a string variable! The type of TotalEarly is fixed to int as you specified.
You would have to write
var totalEarlyString = TotalEarly.ToString();
to be able to use the result afterwards. You might wonder why your MessageBox still displays that number as a string although you use the int variable:
"Number of Early Bookings" + " " + TotalEarly
This is because the ToString() method is called automatically in this case. So, you can really save some lines by removing your calls to ToString() after the assignments.
One more thing: local variables are typically named using camelCase. That means, the first character is lower case and every additional word starts with an uppercase character. PascalCase (i.e. also starting with uppercase character) is typically used for properties, methods, class names etc, but not for local or member variables.
It seems like you want each value in the MessageBox to be on a separate line (at least I assume that is why you added some spaces at the end of the first line:
MessageBox.Show("Number of Early Bookings" + " " + TotalEarly + " " +
"Number of Early Evening Waiters" + " " + EarlyWaiters
+ "number of Early Evening Corner Tables tables" + " " + EarlyCornerTables
);
This might not work on all machines. The MessageBox has different sizing behavior on differnt versions of Windows. Some will wrap the text to multiple lines, some will not, or at least at different widths!
Therefore, you better add an Environment.NewLine at the end of each line. This will add a line break to your string which will be interpreted as such by the MessageBox:
MessageBox.Show("Number of Early Bookings " + TotalEarly + Environment.NewLine +
"Number of Early Evening Waiters " + EarlyWaiters + Environment.NewLine +
"Number of Early Evening Corner Tables tables " + EarlyCornerTables);
Accordion to your comments in your code I think the problem is that your if else statements are wrong.
Q1: Should it calculate on every checkbox click or only when you click calculate?
- if it should calculate on every checkbox click then you have to use the CheckedChanged event as RaZor points out.
Q2: Is it true that de client can have a lunch + waiter + table?
- if that is true then your if else statement should be as follows:
if (lunchRadioButton.Checked == true)
{
Meal = Lunch;
if (tableCheckBox.Checked && waiterCheckBox.Checked)
{
Extras = Waiter + Table;
}
else if (waiterCheckBox.Checked)
{
Extras = Waiter;
}
else if (tableCheckBox.Checked)
{
Extras = Table;
}
}

.NET TextBox does not update SelectedText value after calling Select

I have a .NET Winforms-based program I wrote in C# where I programmatically select text within a TextBox using the Select() method. I can see the selected text on the screen and the SelectionLength member reports an accurate amount of selected characters, but the SelectedText member doesn't contain any text:
int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);
thisTextbox.Focus();
if (indexPeriod > -1)
{
thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}
Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();
What's going on?
Update Nov 16 2013
I am adding additional code per #KingKing's request:
delegate void delegateMoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators);
private void MoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators)
{
string strLectureText = String.Empty;
strLectureText = thisTextbox.Text;
int currentStartPos = thisTextbox.SelectionStart + thisTextbox.SelectionLength - 1
// search the rest of the buffer after the currently-selected string to find the next period
int skipLastChar = 0;
// don't include last selected character in search
try
{
if ((thisTextbox.SelectionLength > 0) & (strLectureText[currentStartPos] != '.'))
{
skipLastChar = 1;
}
}
catch (Exception ex)
{
Debug.WriteLine("exception caught! ex=" + ex.Message);
skipLastChar = 0;
}
int indexStart = 0;
if (currentStartPos == 0)
{
indexStart = 0;
}
else
{
indexStart = currentStartPos + 1;
}
int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);
if (indexPeriod > -1)
{
thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}
thisTextbox.Focus();
Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();
}

Categories

Resources