using Iterateds.Properties;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace Iterateds {
public partial class Main : Form {
public static readonly int Max = 10;
public static List<string> Files = new List<string>();
public static int CountFiles = 0,
Threaded = 0,
Counters = 0;
public Main() {
string File;
StringReader strReader = new StringReader(Resources.files.Trim());
while (null != (File = strReader.ReadLine())) {
Files.Add(File);
}
CountFiles = Files.Count;
InitializeComponent();
}
public void Iterated() {
if (0 >= Files.Count) {
return;
}
string selectPath = this.selectPath?.Text;
if (string.IsNullOrEmpty(selectPath.Trim())) {
return;
}
int Counter = 0;
foreach (string file in Files) {
if (Main.Counters >= Counter) {
++Counter;
continue;
}
if (Max > Threaded) {
string filed = file.Trim();
if (string.IsNullOrEmpty(filed)) {
continue;
}
// -----------------------------------------------
// -----------------------------------------------
// -----------------------------------------------
//////////////////////////
// THE PROBLEM IS HERE: //
//////////////////////////
ListViewItem item = new ListViewItem(filed);
ProgressBar pb = new ProgressBar {
Maximum = 100
};
this.Logs.Items.Add(item);
Rectangle r = item.Bounds;
pb.SetBounds(r.X, r.Y, r.Width, r.Height);
this.Logs.Controls.Add(pb);
///////////////////////////////
// ^^ THE PROBLEM IS HERE ^^ //
///////////////////////////////
// -----------------------------------------------
// -----------------------------------------------
// -----------------------------------------------
// here is the load manager, after we reach "Threaded" it starts "Iterated" again to take another "Max" or the remainder if less.
++Threaded;
}
}
}
}
}
The problem is that when the first time is added, everything is fine, but I realized that they stick to the screen, after the next iteration, they no longer appear progressbars, or somewhere below in a bunch in 1 place, as if it were there 1, and the paths to the files themselves are displayed as needed.
The problem is probably due to pb.SetBounds, since ListView has a scrollbar, scrolling and everything collapses, maybe someone will tell you how to solve such a problem?
I need the file address on the left, and the progress bar on the right, nothing else is needed.
Each time the function should take no more than Max.
That is, only Max or less can be processed at a time.
It was possible to solve without ListView, through TableLayoutPanel.
this.tableLayoutPanel1.RowCount += 1;
Label txt = new Label {
Text = filed
};
txt.AutoSize = true;
ProgressBar pb = new ProgressBar {
Maximum = 100
};
pb.Height = 10;
this.tableLayoutPanel1.Controls.Add(txt);
this.tableLayoutPanel1.Controls.Add(pb);
Related
I am creating a project where random images show when i click a button and the total of the images (dice) will have to be guessed. I already have down the random image generating and keeping track of the persons amount of rolls. However; I cant figure out how to make a dice (image) have a certain value. Like dice 5 shows and has a value of 4. The person puts there guess in the guessBx and clicks on the guessBtn and it will pop up if they are correct or not.
Here is my code as of now:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PetalsAroundTheRose
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int a = 0;
int diceRoll;
int diceImage;
int diceValue;
private void btnRoll_Click_1(object sender, EventArgs e)
{
Random random = new Random();
picBx1.Image = imageList1.Images[random.Next(1, 6)];
picBx2.Image = imageList1.Images[random.Next(1, 6)];
picBx3.Image = imageList1.Images[random.Next(1, 6)];
picBx4.Image = imageList1.Images[random.Next(1, 6)];
a++;
txtBxRolls.Text = a.ToString();
//each dice seperate
//dice 1
diceRoll = 1;
diceImage = imageList1.Images[(1)];
diceValue = 0;
//dice 2
diceRoll = 1;
diceImage = imageList1.Images[(2)];
diceValue = 0;
//dice 3
diceRoll = 1;
diceImage = imageList1.Images[(3)];
diceValue = 2;
//dice 4
diceRoll = 1;
diceImage = imageList1.Images[(4)];
diceValue = 0;
//dice 5
diceRoll = 1;
diceImage = imageList1.Images[(5)];
diceValue = 4;
}
private void guessBx_TextChanged_1(object sender, EventArgs e)
{
}
}
}
On my design I have btnRoll for rolling the dice. guessBx for entering the guess, btnGuess, txtBxCorrect for the amount correct they got, and txtBxResult to say if they are correct or not
The images are in an imageList
Firstly i create a class with these two properties
public class Dice
{
public int Indexer { get; set; }
public string PhotoPath { get; set; }
public Dice(int indexer, string photoPath)
{
Indexer = indexer;
PhotoPath = photoPath;
}
}
After that i put in my form the picture boxes and then i created two methods
the first one:
public void SetUp()
{
for (int i = 1; i <= 6; i++)
{
temp = random.Next(1, 6);
dice = new Die(temp, "C:\\Users\\giorg\\Desktop\\dice\\dice" + temp + ".PNG");
dices.Add(dice); // list<Dice> dices = new list<Dice>();
}
}
and the second one:
public void RollDices()
{
//this is not necessary but if you want to keep a sum of dices keep
//it
var count = 0;
foreach (var dice in dices)
{
count += dice.Indexer;
}
//pictureboxes 2-7 are guess boxes
if(textBox2.Text.Equals(dices[0].Indexer.ToString()))
pictureBox1.Image = Image.FromFile(dices[0].PhotoPath);
if (textBox3.Text.Equals(dices[1].Indexer.ToString()))
pictureBox2.Image = Image.FromFile(dices[1].PhotoPath);
if (textBox4.Text.Equals(dices[2].Indexer.ToString()))
pictureBox3.Image = Image.FromFile(dices[2].PhotoPath);
if (textBox5.Text.Equals(dices[3].Indexer.ToString()))
pictureBox4.Image = Image.FromFile(dices[3].PhotoPath);
if (textBox6.Text.Equals(dices[4].Indexer.ToString()))
pictureBox5.Image = Image.FromFile(dices[4].PhotoPath);
if (textBox7.Text.Equals(dices[5].Indexer.ToString()))
pictureBox6.Image = Image.FromFile(dices[5].PhotoPath);
}
Put these two methods to your button click event and you are ok...
Inform me if you are ok with this approach.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Chrome;
using System.Text.RegularExpressions;
using System.IO;
using OpenQA.Selenium.Support.UI;
namespace FlippaSearch
{
public partial class Form1 : Form
{
static IWebDriver driverGC;
public Form1()
{
driverGC = new ChromeDriver(#"Z:\Justin\Documents\Visual Studio 2015\chromedriver_win32");
driverGC.Navigate().GoToUrl("https://flippa.com/websites/starter-sites?sitetype=blog&uniques_per_month_min=1000");
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
List<IWebElement> starterSites = new List<IWebElement>();
List<String> myStarterSites = new List<string>();
IWait<IWebDriver> wait = new WebDriverWait(driverGC, TimeSpan.FromSeconds(30.00));
var numPages = (driverGC.FindElement(By.XPath("//*[#id='searchBody']/div[1]/div[1]/h2/span")).Text);
double numberPages = int.Parse(Regex.Match(numPages, #"\d+", RegexOptions.RightToLeft).Value);
numberPages = Math.Ceiling(numberPages / 50);
int j;
for (int i = 1; i <= numberPages; i++)
{
driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
var mySites = driverGC.FindElements(By.CssSelector(".ListingResults___listingResult"));
int size = 1;
for (j = 0; j < 3; ++j)
{
driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
mySites = driverGC.FindElements(By.CssSelector(".ListingResults___listingResult"));
size = mySites.Count();
driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
String siteLink = " ";
siteLink = mySites[j].FindElement(By.CssSelector(".ListingResults___listingResultLink")).GetAttribute("href");
driverGC.Navigate().GoToUrl(siteLink);
driverGC.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
//testing tables
int row_tr = 5;
int Column_td = 3;
String CellValue;
String newCellValue;
String cellValueChange;
try
{
driverGC.FindElement(By.XPath("/html/body/div[3]/div[1]/div[1]/div[5]/div[1]/div/table[1]/tbody"));
for (int k = 1; k <= row_tr; k++)
{
for (int b = 1; b <= Column_td; b++)
{
CellValue = driverGC.FindElement(By.XPath("/html/body/div[3]/div[1]/div[1]/div[5]/div[1]/div/table[1]/tbody/tr[" + k + "]/td[" + b + "]")).Text.ToString();
if (CellValue == "Organic Search")
{
String mySiteName = driverGC.FindElement(By.XPath("/html/body/div[3]/div[1]/div[1]/div[1]/div[1]/h1")).Text.ToString();
newCellValue = driverGC.FindElement(By.XPath("/html/body/div[3]/div[1]/div[1]/div[5]/div[1]/div/table[1]/tbody/tr[" + k + "]/td[3]")).Text.ToString();
cellValueChange = Regex.Replace(newCellValue, #"[%\s]", string.Empty);
float organicSearch = float.Parse(cellValueChange);
if (organicSearch >= 50)
{
myStarterSites.Add(mySiteName);
myStarterSites.Add(CellValue);
myStarterSites.Add(newCellValue);
Console.WriteLine(mySiteName);
Console.WriteLine(CellValue);
Console.WriteLine(newCellValue);
}
}
}
}
}
catch (OpenQA.Selenium.NoSuchElementException)
{
}
//testing tables
driverGC.Navigate().Back();
//write shit to file
siteLink = "";
driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
}
j = 0;
//mySites = null;
try
{
driverGC.FindElement(By.XPath("//*[#id='searchBody']/div[2]/div[2]/div/a[3]")).Click();
//driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
}
catch (ElementNotVisibleException)
{
Console.WriteLine("No more pages");
}
}
using (StreamWriter writer = new StreamWriter(#"C:\Users\Justin\Desktop\newFile.txt"))
{
foreach (string s in myStarterSites)
{
writer.WriteLine(s + " ");// Writes in next line
writer.WriteLine(" ");
}
}
//MessageBox.Show("End");
driverGC.Quit();
Application.Exit();
}
}
}
Upon starting, the code will run fine on the first page. It grab's the elements, puts them in a list, and then i can gather the required information. Once it loops through the first page (i have it set to 3 strictly for testing reasons so its quicker) it will click next page, and then the next page loads and the loop begins again. The issue is, when the second page loads, the first element on the first page is being checked again, and then after that one is checked, it will go to the 2nd element on the 2nd page, and then continue on from there. My question is, how can i get it to scan the first element on the second page instead of redoing the first element on the first page again? I have tried using Waits but I cannot seem to get anything to work.
Thanks in advance.
It probably timing issue, the next loop iteration starts before the next page is actually loaded. You can use explicit wait and ExpectedConditions TextToBePresentInElementLocated on the page numbers to make sure the current page is what you actually need. You can do it by checking the number in the element with Pagination___activeLink class
driverGC.FindElement(By.XPath("//*[#id='searchBody']/div[2]/div[2]/div/a[3]")).Click(); // go to next page
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.ClassName("Pagination___activeLink"), (i + 1).ToString()));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm currently working with a project that a book has assigned for me (Head First C#, 3rd Edition) and I'm facing some problems with my code.
The whole project is based on a gambling game that 3 guys can participate in.
The gambling game consists of the 3 guys betting on 4 dogs that can randomly win a race on a track.
One of the problems is when a guy bets a bigger amount of money than he has, the program sets the value of Amount to 0.
I don't know why I'm not seeing the obvious mistake or not but I really appreciate the help if someone would offer it.
The code for the whole program is as follows:
Guy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace A_Day_at_the_Races
{
public class Guy
{
public string Name; // The guy's name
public Bet MyBet = null; // An instance of Bet() that has how much he's betting
public int Cash; // How much cash he has
// These last two fields are the guy's GUI controls on the form
public RadioButton MyRadioButton; // My RadioButton
public Label MyLabel; // My Label
public void UpdateLabels()
{
//1.Set my label to my bet's description,
if (MyBet == null)
MyLabel.Text = Name + " hasnt placed any bets";
else if (MyBet.Amount > Cash)
MyLabel.Text = Name + " doesn't have that amount of money";
else
MyLabel.Text = MyBet.GetDescription();
if (Cash >= 0)
{
//2.Set the label on my radio button to show my cash ("Joe has 43 dollars")
MyRadioButton.Text = Name + " has " + Cash + " bucks";
}
else
{
MyRadioButton.Text = Name + " has no cash left";
}
}
public void ClearBet()
{
//1.Reset my bet so it's zero
MyBet = null;
}
public bool PlaceBet(int Amount, int Dog)
{
//1.Place a new bet and store it in my bet field
this.MyBet = new Bet();
//2.Return true if the guy had enough money to bet
if (Cash >= Amount)
{
Cash = Cash - Amount; // Remove the amount bet
MyBet.Amount = Amount;
MyBet.Dog = Dog;
MyBet.Bettor = this;
UpdateLabels();
return true;
}
else if (Cash < Amount)
{
return false;
}
else
{
return false;
}
}
public void Collect(int Winner)
{
if (MyBet != null)
//1.Ask my bet to pay out (hint use the bet object to do the work)
Cash += MyBet.PayOut(Winner);
}
}
}
Greyhound.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace A_Day_at_the_Races
{
public class Greyhound
{
public int StartingPosition; // Where PictureBox starts
public int RacetrackLength; // How long the racetrack is
public PictureBox MyPictureBox = null; // My PictureBox object
public int Location = 0; // My location on the racetrack
public Random Randomizer; // An instance of Random
public bool Run()
{
// Move forward either 1, 2, 3 or 4 spaces at random
int x = Randomizer.Next(1, 4);
// Update the position of my PictureBox on the form
Point p = MyPictureBox.Location;
p.X += x;
MyPictureBox.Location = p;
// Return true if I won the game
if (p.X >= RacetrackLength)
{
return true;
}
else
{
return false;
}
}
public void TakeStartingPosition ()
{
// Reset starting position of PictureBox
StartingPosition = 0;
}
}
}
Bet.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace A_Day_at_the_Races
{
public class Bet
{
public int Amount; // The amount of cash that was bet
public int Dog; // The number of the dog the bet is on
public Guy Bettor = new Guy(); // The guy who placed the bet
public string GetDescription()
{
// Return a string that says who placed the bet, how much cash
// was bet, and which dog he bet on ("Joe bets 8 on dog #4").
if (Amount > 0 && Amount < Bettor.Cash)
{
return Bettor.Name + " bets $" + Amount + " on dog #" + Dog;
}
// If the amount is zero, no bet was placed; ("Joe hasn't placed
// a bet").
else if (Amount == 0)
{
return Bettor.Name + " hasn't placed a bet";
}
else if (Amount > Bettor.Cash)
{
return Bettor.Name + " doesn't have that amount of money";
}
else
{
return Bettor.Name + "'s bet";
}
}
public int PayOut(int Winner) // The parameter is the winner of the race
{
// If the dog won, return the amount bet.
if (Winner == Dog)
{
return Amount;
}
// Otherwise, return the negative of the amount bet.
else
{
return -1 * Amount;
}
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace A_Day_at_the_Races
{
public partial class Form1 : Form
{
Guy[] Bettors;
Greyhound[] Dogs;
Guy CurrentBettor;
public Form1()
{
InitializeComponent();
Random Randomizer = new Random();
// Initialise all my Guys and Dogs
Bettors = new Guy[3];
Dogs = new Greyhound[4];
// Guys
// Joe
Bettors[0] = new Guy();
Bettors[0].Name = "Joe";
Bettors[0].MyRadioButton = joeRadioButton;
Bettors[0].MyLabel = joeBetLabel;
Bettors[0].Cash = 50;
Bettors[0].UpdateLabels();
// Bob
Bettors[1] = new Guy();
Bettors[1].Name = "Bob";
Bettors[1].MyRadioButton = bobRadioButton;
Bettors[1].MyLabel = bobBetLabel;
Bettors[1].Cash = 75;
Bettors[1].UpdateLabels();
// Al
Bettors[2] = new Guy();
Bettors[2].Name = "Al";
Bettors[2].MyRadioButton = alRadioButton;
Bettors[2].MyLabel = alBetLabel;
Bettors[2].Cash = 45;
Bettors[2].UpdateLabels();
// Local integers on distance and starting position of the Dogs
int StartPosition = pictureBoxDog1.Location.X;
int distance = pictureBox1.Width;
// Initialize all 4 Dogs
for (int i = 0; i < Dogs.Length; i++)
{
Dogs[i] = new Greyhound();
Dogs[i].Randomizer = Randomizer;
Dogs[i].RacetrackLength = distance;
Dogs[i].Location = Dogs[i].StartingPosition = StartPosition;
}
// Connect pictureboxes with MyPictureBox in the Dog class
Dogs[0].MyPictureBox = pictureBoxDog1;
Dogs[1].MyPictureBox = pictureBoxDog2;
Dogs[2].MyPictureBox = pictureBoxDog3;
Dogs[3].MyPictureBox = pictureBoxDog4;
CurrentBettor = Bettors[0];
}
private void RaceButton_Click(object sender, EventArgs e)
{
int winner = 0; // Number of the winner Dog
int num_winners = 0; // Amount of winners
// While none has won,
while (num_winners == 0)
{
for (int i = 0; i < Dogs.Length; i++)
{
// If a Dog has reached max length of the race track,
// increment number of winners and add 1 to i and save it
// to the winner variable
if (Dogs[i].Run())
{
num_winners++;
winner = i + 1;
}
}
Application.DoEvents();
System.Threading.Thread.Sleep(3);
}
// If there is more than one winner, show this message
if (num_winners > 1)
MessageBox.Show("We have " + num_winners + " winners");
// Otherwise if there are more than or equal to one winner,
// show this message
else if (num_winners >= 1)
MessageBox.Show("Dog #" + winner + " wins!");
// Place all Dogs in their starting positions
for (int i = 0; i < Dogs.Length; i++)
{
Dogs[i].TakeStartingPosition();
}
for (int i = 0; i < Bettors.Length; i++)
{
Bettors[i].Collect(winner);
Bettors[i].ClearBet();
Bettors[i].UpdateLabels();
}
numericUpDownBet.Value = numericUpDownBet.Minimum;
numericUpDownDog.Value = numericUpDownDog.Minimum;
}
private void joeRadioButton_CheckedChanged(object sender, EventArgs e)
{
// Bettor = Joe when his radio button is checked
SetBettor(0);
}
private void bobRadioButton_CheckedChanged_1(object sender, EventArgs e)
{
// Bettor = Bob when his radio button is checked
SetBettor(1);
}
private void alRadioButton_CheckedChanged_1(object sender, EventArgs e)
{
// Bettor = Al when his radio button is checked
SetBettor(2);
}
private void BetsButton_Click(object sender, EventArgs e)
{
// Place bet depending on the value of the two numericUpDowns
// (Amount & Dog)
CurrentBettor.PlaceBet((int)numericUpDownBet.Value, (int)numericUpDownDog.Value);
CurrentBettor.UpdateLabels();
}
private void SetBettor(int index)
{
// Set the current bettor and update the name label
// to the his name
CurrentBettor = Bettors[index];
NameLabel.Text = CurrentBettor.Name;
// If the Guy's bet isn't 0,
// then save the amount and the dog he's
// betting on
if (CurrentBettor.MyBet != null)
{
numericUpDownBet.Value = CurrentBettor.MyBet.Amount;
numericUpDownDog.Value = CurrentBettor.MyBet.Dog;
}
// Otherwise, make the value of the bet
// to the minimum on the numericUpDownBet
// and set the default Dog that is being
// bet on as the first Dog
else
{
numericUpDownBet.Value = numericUpDownBet.Minimum;
numericUpDownDog.Value = 1;
}
}
private void Form1_Load(object sender, EventArgs e)
{
minimumBetLabel.Text = "Minimum Bet: $5.00";
}
private void ResetButton_Click(object sender, EventArgs e)
{
// Reset Dogs to their default location when
// the Reset button is pressed
pictureBoxDog1.Location = new Point(22, 21);
pictureBoxDog2.Location = new Point(22, 63);
pictureBoxDog3.Location = new Point(22, 120);
pictureBoxDog4.Location = new Point(22, 170);
}
}
}
All answers are appreciated.
The problem is in the following code.
Here, a new bet is created (Amount defaults to 0 if not set otherwise!):
//1.Place a new bet and store it in my bet field
this.MyBet = new Bet();
Here, all relevant data is set for MyBet:
//2.Return true if the guy had enough money to bet
if (Cash >= Amount)
{
Cash = Cash - Amount; // Remove the amount bet
MyBet.Amount = Amount;
MyBet.Dog = Dog;
MyBet.Bettor = this;
UpdateLabels();
return true;
}
Here, no data is set for MyBet, so Amount remains 0:
else if (Cash < Amount)
{
return false;
}
This can not occur at all:
else
{
return false;
}
I PlaceBet - you create an empty Bet, and only then check, if the guy has enough cash. If he hasn't, then the empty Bet will stay empty - and its Amount field will remain at the default 0.
public bool PlaceBet(int Amount, int Dog)
{
//1.Place a new bet and store it in my bet field
this.MyBet = new Bet(); // EMPTY BET
//2.Return true if the guy had enough money to bet
if (Cash >= Amount)
{
Cash = Cash - Amount; // Remove the amount bet
MyBet.Amount = Amount;
MyBet.Dog = Dog;
MyBet.Bettor = this;
UpdateLabels();
return true;
}
else if (Cash < Amount)
{
// THE BET REMAINS EMPTY
return false;
}
else
{
return false;
}
}
Also, the "else" block will never happen - you can actually remove the else if (Cash < Amount) case.
//1.Place a new bet and store it in my bet field
this.MyBet = new Bet();
//2.Return true if the guy had enough money to bet
if (Cash >= Amount)
{
Cash = Cash - Amount; // Remove the amount bet
MyBet.Amount = Amount;
MyBet.Dog = Dog;
MyBet.Bettor = this;
UpdateLabels();
return true;
}
else if (Cash < Amount)
{
return false;
}
At (1) you are creating a new Bet object then if Cash < Amount at (2) you return false without setting this.MyBet to null.
The best solution would probably be to put this.MyBet = new Bet(); within the Cash >= Amount block.
i am a newbie in C# and i have a simple console application with method validateVoters() which takes a studentID argument, compares it against text file then return appropriate boolean value.
However i want it to delete that specific studentID if it exists then return true, but there is no generic delete from file method so i used a method recommended by a member here:
Giving me an error with the method in double asterics ** :
Error 2
The name 'RemoveUnnecessaryLine' does not exist in the current context c:\Users\Hlogoyatau\Documents\Visual Studio 2010\Projects\Ijoo\Ijoo\Program.cs 28 43 Ijoo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace SRCVotingSystem
{
public class Program
{
public bool validateVoter(String cisNo)
{
bool found = false;
try
{
string[] ID = System.IO.File.ReadAllLines(#"C:\Users\Hlogoyatau\Pictures\votersRoll.txt");
foreach (string line in ID)
{
//compares it against text file contents
if (cisNo == line)
{
string[] allLines= File.ReadAllLines("votersRoll.txt");
string[] newIDs= **RemoveUnnecessaryLine**(allLines);
File.WriteAllLines("votersRoll.txt", newIDs);
found = true;
}
}
}
catch (IOException e)
{
Console.WriteLine(e.ToString());
}
return found;
}
public static void Main()
{
Program vv = new Program();
Console.WriteLine(vv.validateVoter("cis11-005"));
}
}
}
/* sample data in text.tx
ID 1 asdfsdaf
ID 2 asdfdsafasdfsadf
ID 3 lkjasdfjsdf
*/
private static void Main(string[] args)
{
var id = 2;
var lines = File.ReadAllLines("C:\\temp\\text.txt");
var remaining = lines.Where(x => !x.Contains(id.ToString())).ToArray();
File.WriteAllLines("C:\\temp\\out.txt", remaining);
}
Try this:
public bool validateVoter(String cisNo)
{
bool found = false;
try
{
string[] ID = System.IO.File.ReadAllLines(#"C:\Users\Hlogoyatau\Pictures\votersRoll.txt");
for (int i = 0; i < ID.Length; i++)
{
string line = ID[i];
//compares it against text file contents
if (cisNo == line)
{
//Shift remaining lines up, overwriting current line
for (int j = i; j < ID.Length - 1; j++)
{
ID[j] = ID[j+1];
}
//Set last line to empty string
ID[ID.Length - 1] = "";
//Write file back to disk
System.IO.File.WriteAllLines(#"C:\Users\Hlogoyatau\Pictures\votersRoll.txt", ID);
found = true;
//Exit loop after something is found
break;
}
}
}
catch (IOException e)
{
Console.WriteLine(e.ToString());
}
return found;
}
It will read the file, and when a match is found, then it shifts the remaining lines up one line. The last line will be cleared, then the file gets written back to disk. If you do not want to have an empty last line, then you can resize the array (see Array.Resize).
Try using LINQ
public void validateVoter(String cisNo)
{
var newIDs = System.IO.File.ReadAllLines(#"C:\Users\Hlogoyatau\Pictures\votersRoll.txt").Where(l => l != cisNo);
File.WriteAllLines(#"C:\Users\Hlogoyatau\Pictures\votersRoll.txt", newIDs);
}
I've created a Random Number Generator app. It allows the user to enter integers into min, max, and amount to gen. There are three buttons; generate, clear output, and save. All work except the save.
I've been working on this for about 6 hours now (not joking) and I still can't figure it out. I found this thread, but I don't understand how it is implemented:
How to store an integer value in isolated storage in wp7?
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Random_Number_Generator_by_Bailey.Resources;
using System.Windows.Input;
using System.IO.IsolatedStorage;
namespace Random_Number_Generator_by_Bailey
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
if (IsolatedStorageSettings.ApplicationSettings.Contains("minstorage"))
{
min1 = (int)IsolatedStorageSettings.ApplicationSettings["minstorage"];
string min1text = min1.ToString();
MinNumInput.Text = min1text;
}
// Retrieve settings
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private int randomNumber(int min, int max)
{
Random random = new Random(Guid.NewGuid().GetHashCode());
return random.Next(min, max);
}
public void Randomize_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
int tester2;
if (!Int32.TryParse(MinNumInput.Text, out tester2))
{
OutputBox.Text = "You did not specify an integer for \"Minimum Number\" ";
return;
}
int tester3;
if (!Int32.TryParse(MaxNumInput.Text, out tester3))
{
OutputBox.Text = "You did not specify an integer for \"Maximum\" ";
return;
}
int tester;
if (!Int32.TryParse(AmountToGenInput.Text, out tester))
{
OutputBox.Text = "You did not specify an integer for \"Amount to generate\" ";
return;
}
int gen;
gen = Convert.ToInt32(AmountToGenInput.Text);
gen = int.Parse(AmountToGenInput.Text);
int min1;
min1 = Convert.ToInt32(MinNumInput.Text);
min1 = int.Parse(MinNumInput.Text);
int max1;
max1 = Convert.ToInt32(MaxNumInput.Text);
max1 = int.Parse(MaxNumInput.Text);
if (gen <= 100 && gen > 0)
{
for (int i = 0; i < gen; i++)
{
int random = randomNumber(min1, max1);
OutputBox.Text += " " + random;
}
}
else
{
if (gen > 100) { OutputBox.Text = "You cannot generate more than 100 numbers."; }
if (gen < 0) { OutputBox.Text = "You cannot generate less than 0 numbers."; }
}
}
private void ClearTextBox_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
OutputBox.Text = "";
}
private void SaveParameters(object sender, System.Windows.Input.GestureEventArgs e)
{
int gen;
gen = Convert.ToInt32(AmountToGenInput.Text);
gen = int.Parse(AmountToGenInput.Text);
int min1;
min1 = Convert.ToInt32(MinNumInput.Text);
min1 = int.Parse(MinNumInput.Text);
int max1;
max1 = Convert.ToInt32(MaxNumInput.Text);
max1 = int.Parse(MaxNumInput.Text);
//If the variables need to be strings:
//string gen = AmountToGenInput.Text;
//string min1 = MinNumInput.Text;
//string max1 = MaxNumInput.Text;
// Store the value
IsolatedStorageSettings.ApplicationSettings["minstorage"] = min1;
}
// Sample code for building a localized ApplicationBar
//private void BuildLocalizedApplicationBar()
//{
// // Set the page's ApplicationBar to a new instance of ApplicationBar.
// ApplicationBar = new ApplicationBar();
// // Create a new button and set the text value to the localized string from AppResources.
// ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
// appBarButton.Text = AppResources.AppBarButtonText;
// ApplicationBar.Buttons.Add(appBarButton);
// // Create a new menu item with the localized string from AppResources.
// ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
// ApplicationBar.MenuItems.Add(appBarMenuItem);
//}
}
}
If anyone could PLEASE help me, that would be great. Thank you.
You are using min1 in your constructor without declaring the variable.
min1 = (int)IsolatedStorageSettings.ApplicationSettings["minstorage"];
Change to
var min1 = IsolatedStorageSettings.ApplicationSettings["minstorage"];