C# My arrays are not populating answers. No matter what it always generates 0's [closed] - c#

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 10 months ago.
Improve this question
I have the .txt file saved in the appropriate folder (to be honest, I have one saved in every single possible folder relating to this code) but no matter what it always populates a bunch of zeros.... Can someone show me where I went wrong?
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System;
namespace WindowsFormsAppSix6AttemptNumber6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private double[] myArray =
{
1245.67,
1189.55,
1089.72,
1456.88,
2109.34,
1987.55,
1872.36
};
private void analyzeBtn_Click(object sender, EventArgs e)
{
string salesValue;
Double[] sales = new double[8];
int count = 0;
double maxSales = Double.MinValue;
double minSales =Double.MaxValue;
double totalSales = 0;
try
{
StringReader dataStream = new StringReader("Sales.Txt");
salesValue = dataStream.ReadLine();
var total = sales.Sum();
var average = sales.Average();
var high = sales.Max();
var low = sales.Min();
while (salesValue != null)
{
try
{
sales[count] = Convert.ToDouble(salesValue);
totalSales += sales[count];
if (sales[count] > maxSales)
maxSales = sales[count];
if (sales[count] < minSales)
minSales = sales[count];
count++;
}
catch (FormatException)
{
Console.WriteLine("\tException: '" + salesValue + "'");
salesValue = dataStream.ReadLine();
}
dataStream.Close();
for (int item = 0; item < 7; item++)
listBoxLbl.Items.Add(sales[item]);
string listItems = string.Join(",\n", sales);
Console.WriteLine(listItems);
Console.WriteLine(totalSales);
Console.WriteLine(maxSales);
Console.WriteLine(minSales);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void exitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
below is what it does when i use the analyze button. I have been going in circles with this one and cant figure out what I am doing wrong....
[1]: https://i.stack.imgur.com/OFGgv.png

If that's your intention, you should use "StreamReader".
//StringReader dataStream = new StringReader("Sales.Txt");
StreamReader dataStream = new StreamReader("Sales.Txt");
"sales[count] = Convert.ToDouble(salesValue);"
"salesValue = dataStream.ReadLine();"
"Console.WriteLine(ex);"
Please Put a breakpoint here and test it.
'salesValue' is file name.
breakpoint 'salesValue'

Related

Incorrect reading of an array

I am working in c-sharp .net and I am working on creating a login screen for my project. I have a text file with login info for all the users. My c-sharp scrip reads that file to a string then cuts it up into two lists, _usernames and _passwords. When the user types their login info and hits login the _usernames[0] and _passwords[0] account info are the only ones that work. What I want it to do is look through all the _usernames for the inputted one, if it finds it then check the _password[same index as _usernames] and if both are the same as what the user submitted then it will add "true" to the richTextBox.
Why is it not correctly reading from the array?
This is my users.txt:
admin,test|
andrew,yeet|
zana,happy|
This is my c-sharp script:
using System;
using System.IO;
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 BaseUserInterfase
{
public partial class Login : Form
{
string path = Directory.GetCurrentDirectory() + "\\data\\users.txt";
string data;
string[] _usernames = new string[10];
string[] _passwords = new string[10];
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
GetLoginData();
}
private void btnLogin_Click(object sender, EventArgs e)
{
rtbTemp.Text = "";
for(int i = 0; i < _usernames.Length; i++)
{
if(_usernames[i] == null)
{
break;
}
rtbTemp.AppendText("\n" + _usernames[i]);
rtbTemp.AppendText("\n" + tbUsername.Text.ToString());
rtbTemp.AppendText("\n" + _passwords[i]);
rtbTemp.AppendText("\n" + tbPassword.Text.ToString());
if (_usernames[i] == tbUsername.Text.ToString())
{
rtbTemp.AppendText("\nUsername true");
if (_passwords[i] == tbPassword.Text.ToString())
{
rtbTemp.AppendText("\nPassword true");
rtbTemp.AppendText("\ntrue");
return;
}
}
}
rtbTemp.AppendText("\nfalse");
}
public void GetLoginData()
{
using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
{
data = streamReader.ReadToEnd();
}
List<string> _data = data.Split('|').ToList();
_data.RemoveAt(_data.Count - 1);
rtbTemp.AppendText("\n");
Array.Resize<string>(ref _usernames, _data.Count);
Array.Resize<string>(ref _passwords, _data.Count);
foreach (string _item in _data)
{
List<string> userdata = _item.Split(',').ToList();
string username = userdata[0].ToString();
string password = userdata[1].ToString();
Console.WriteLine(_item);
Console.WriteLine(username);
Console.WriteLine(password);
for(int i = 0; i < _data.Count; i++)
{
if(_usernames[i] == null)
{
_usernames[i] = username;
_passwords[i] = password;
break;
}
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
And this is an image of the login screen:
1
Your file contains carriage return characters. Remove them before you split its content
data = streamReader.ReadToEnd().Replace("\r\n", "");

C# high score in game [closed]

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 5 years ago.
Improve this question
Bassicaly I'm stucked with displaying high scores via listbox by discending order(like 500 to 1). Here is my code, keep in mind that label1 is score in the game, so if anyone may help me please?
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
label1.Text = Form2.passingText;
StreamWriter q = new StreamWriter("C:\\Users\\BS\\Desktop\\tex.txt", true);
q.WriteLine(label1.Text);
q.Close();
StreamReader sr = new StreamReader("C:\\Users\\BS\\Desktop\\tex.txt");
string g = sr.ReadLine();
while (g != null)
{
listBox1.Items.Add(g);
g = sr.ReadLine();
}
sr.Close();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
You can read file as list of lines and then sort it using Linq
So, instead of using SteamReader, try this:
using System.Linq;
//....
List<string> hiscores = File.ReadAllLines("C:\\Users\\BS\\Desktop\\tex.txt").ToList();
hiscores.Sort();
foreach (string s in hiscores)
listBox1.Items.Add(s);
EDIT:
since you have to use StreamReader, here is this approach (but the principle is same):
List<string> hiscores = new List<string>();
StreamReader sr = new StreamReader("C:\\Users\\BS\\Desktop\\tex.txt");
string g = sr.ReadLine();
while (g != null)
{
hiscores.Add(g);
g = sr.ReadLine();
}
sr.Close();
hiscores.Sort();
hiscores.Reverse();
//alternatively, instead of Sort and then reverse, you can do
//hiscores.OrderByDescending(x => x);
foreach(string s in hiscores)
{
listBox1.Items.Add(s);
}

Parse the string to take the date before putting each variable into datetime object

I get this warning when I try to execute the attaching code.
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 prueb2 {
public partial class Acusado: Form {
public Acusado() {
InitializeComponent();
}
private void Acusado_Load(object sender, EventArgs e) {
listView1.Items.Clear();
List < ACUSADOcLAS > listaAcusado;
try {
listaAcusado = BD.GetAcusado();
if (listaAcusado.Count > 0) {
ACUSADOcLAS acusado;
for (int i = 0; i < listaAcusado.Count; i++) {
acusado = listaAcusado[i];
listView1.Items[i].SubItems.Add(acusado.NumeroSeguroSocial.ToString());
listView1.Items[i].SubItems.Add(acusado.NombreAcusado);
listView1.Items[i].SubItems.Add(acusado.ApellidoPaternoAcusado);
listView1.Items[i].SubItems.Add(acusado.ApellidoMaternoAcusado);
listView1.Items[i].SubItems.Add(acusado.FechaNacimientoAcusado.ToString());
listView1.Items[i].SubItems.Add(acusado.GeneroAcusado);
listView1.Items[i].SubItems.Add(acusado.DireccionAcusado);
listView1.Items[i].SubItems.Add(acusado.NivelMaximoEstudiosAcusado);
listView1.Items[i].SubItems.Add(acusado.EtnicidadAcusado);
listView1.Items[i].SubItems.Add(acusado.ReligionAcusado);
}
} else {
MessageBox.Show("No hay acusados", "Alerta");
}
} catch (Exception ex) {
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
}
private void button1_Click(object sender, EventArgs e) {
BD.AddAcusado(int.Parse(txtNumSeg.Text), txtNombreA.Text, txtApPat.Text, txtApMat.Text, DateTime.Parse(dateTimeFecha.Text), comboGenero.Text, txtDireccion.Text, comboEstudios.Text, txtEtnicidad.Text, txtReligion.Text);
txtNumSeg.Text = "";
txtNombreA.Text = "";
txtApPat.Text = "";
txtApMat.Text = "";
dateTimeFecha.Text = "";
comboGenero.Text = "";
txtDireccion.Text = "";
comboEstudios.Text = "";
txtEtnicidad.Text = "";
txtReligion.Text = "";
this.Acusado_Load(this, null);
}
}
}
Can you help me please?
You are probably getting exception because of the invalid date string. You need to validate it first.
Try this:
DateTime tempDateTimeFecha;
bool isValid = DateTime.TryParse(dateTimeFecha.Text, out tempDateTimeFecha);
Now if isValid == true you can pass tempDateTimeFecha as argument to theBD.AddAcusado() method.
I had this same issue trying to parse the Date column of my datagridview. The following procedure helped me resolve it:
I checked my loop body and decreased the maximum number for loop termination by 1.
int days = 0;
Datetime d;
for (int i = 1; i < pastedCells -1; i++){
d = Convert.ToDateTime(dgv_Copy.Rows[i].Cells[1].Value);
days = DateTime.DaysInMonth(d.Year, d.Month);
Console.WriteLine(days + "\t" + d);
}
//result:
//31 2002-05-31 0:00
//30 2002-11-30 0:00
//31 2003-05-31 0:00
//30 2003-06-30 0:00
//31 2003-10-31 0:00
//30 2003-11-30 0:00
//29 2004-02-29 0:00
//31 2004-10-31 0:00
Pls Note: Parsing Dates depend on the format (check this https://learn.microsoft.com/en-us/dotnet/standard/base-types/parsing-datetime for more info. MORE IMPORTANTLY, if your loop body tries to pass a null or empty, then it will definitely pop up error.
Also, remember to catch the exception but not after checking for coding error.

How do i loop for the next 25 results next page using facebook api?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Facebook;
using System.Net;
using System.IO;
namespace WebSite_Login_And_Browsing
{
class Posts
{
public string PostId { get; set; }
public string PostStory { get; set; }
public string PostMessage { get; set; }
public string PostPicture { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
}
class FacebookPosts
{
static string accesstoken;
//static string token = "2f89d691b5f39";
static string token = "1186840401345424|GoJRCpM";
static string mytoken = "CAACEdEose0cBACPu39NSSalHCGFGDGRKZAvwiTuzG8PHlNRJwbyMVugovDxgL7CT3a1QbRuVDZALXxWU0ntwSrDyq75LIIuzFpBtx47cJYCY2OiA21lpTRKt2bB0t5HrsQYIXHXhmU7GnavWZCzqN8yeuv5NWXxTIOfVCZAZArjYNiPWhZBqZAZAO03s6FKNIulm4kjzXvp4QKiahAlcyaZBg";
static string mytokenaslip = "CAACEdEose0cBABmWuBI9p9dpPxEsMJoFZAG3kScx61kZAImNBgt52kVrd8WWPRpwjWP8nCPX69zdLuFyVQHzxYfMk85ZBZC4BIajVWXNLo7OI7yaCbNIwqkcdwpabQVFZBRWt0rzTQrQr6ZBij45XnrQyEUqFKP4gADeO4Fl9yRaZAZCOFtV3b84sWUFEgwaKbZAPY4BCljVjWQZDZD";
public static void RetrievePosts()
{
try
{
var client = new FacebookClient(mytokenaslip);
dynamic result = client.Get("/me/posts");
List<Posts> postsList = new List<Posts>();
//all the posts and their information (like pictures and links) is strored in result.data not in result
for (int i = 0; i < result.data.Count; i++)
{
Posts posts = new Posts();
posts.PostId = result.data[i].id;
if (object.ReferenceEquals(result.data[i].story, null))
posts.PostStory = "this story is null";
else
posts.PostStory = result.data[i].story;
if (object.ReferenceEquals(result.data[i].message, null))
posts.PostMessage = "this message is null";
else
posts.PostMessage = result.data[i].message;
posts.PostPicture = result.data[i].picture;
posts.UserId = result.data[i].from.id;
posts.UserName = result.data[i].from.name;
postsList.Add(posts);
}
}
catch (Exception err)
{
//throw;
string myerr = err.ToString();
}
}
}
}
I'm getting 25 results in the List postsList
How do i loop now asgain to get the next page with the next 25 results and add it to postsList and loop over and over again untill there are no more results ?
What i want to do is to delete automatic every 50 minutes the last old 25 posts.
In my other class in my project i'm posting automatic to my wall a post every minute. After 50 minutes i want to delete the last old 25 posts so on my wall will be all the time with 25 posts only.
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 mshtml;
using HtmlAgilityPack;
using System.Net;
using System.IO;
namespace WebSite_Login_And_Browsing
{
public partial class Facebook_Post : Form
{
WebBrowser wb = new WebBrowser();
int postsCounter = 0;
StreamWriter w = new StreamWriter(#"e:\posts.txt");
WebBrowser webBrowser1;
public Facebook_Post()
{
InitializeComponent();
webBrowser1 = new WebBrowser();
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.Navigate("https://www.facebook.com/");
label4.Text = DateTime.Now.ToString();
w.WriteLine(label4.Text.ToString());
w.WriteLine(Environment.NewLine);
label5.Visible = false;
label2.Visible = false;
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
if (e.Url.AbsoluteUri != webBrowser1.Url.AbsoluteUri)
{
return;
}
wb = webBrowser1;
foreach (HtmlElement he in wb.Document.All.GetElementsByName("xhpc_message"))
{
he.SetAttribute("value", RandomString(10));
}
var elems = wb.Document.GetElementsByTagName("button");
foreach (HtmlElement elem in elems)
{
if (elem.InnerText == "Post")
{
elem.InvokeMember("click");
}
}
sent = true;
postsCounter += 1;
label2.Text = postsCounter.ToString();
label2.Visible = true;
timer1.Enabled = true;
webBrowser1.Dispose();
if (postsCounter == 720)
{
w.WriteLine(postsCounter.ToString());
w.WriteLine(Environment.NewLine);
label5.Text = DateTime.Now.ToString();
label5.Visible = true;
w.WriteLine(label5.Text.ToString());
w.Close();
}
}
catch(Exception err)
{
string myerr = err.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
List<string> results = new List<string>();
HtmlElementCollection elems = wb.Document.GetElementsByTagName("INPUT");
foreach (HtmlElement elem in elems)
{
String nameStr = elem.GetAttribute("value");
results.Add(nameStr);
}
}
bool sent = false;
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
try
{
count += 1;
if (sent == true && count >= 60)
{
count = 0;
timer1.Enabled = false;
webBrowser1 = new WebBrowser();
if (webBrowser1.IsBusy == false)
{
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
webBrowser1.Navigate("https://www.facebook.com/");
}
sent = false;
}
}
catch(Exception err)
{
string myerr = err.ToString();
}
}
private StringBuilder builder;
private static Random random = new Random((int)DateTime.Now.Ticks);
private string RandomString(int size)
{
try
{
builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
}
catch(Exception err)
{
string myerr = err.ToString();
}
return builder.ToString();
}
}
}
I believe this is what you're looking for:
var client = new FacebookClient(mytokenaslip);
//1-25
dynamic result = client.Get("/me/posts", new { limit = "25", offset = "0"});
//26-50
dynamic result = client.Get("/me/posts", new { limit = "25", offset = "25"});
You can also chose to get more than 25 posts at once.
//51-100
dynamic result = client.Get("/me/posts", new { limit = "50", offset = "50"});
You can use a "recursive function" to get all entries, and the "next" parameter in the API result includes the API call for the next batch of results: https://developers.facebook.com/docs/graph-api/using-graph-api#paging
Be careful though, you may hit an API limit if you try to do this too fast and if there are too many results. Also, since you want to delete old entries and deleting one entry is one API call, you should try with a timeout after each call just to make sure not to hit a limit.
Make sure you learn and understand how recursive functions work, hereĀ“s one of countless threads about that: Help with Creating a Recursive Function C#

How can i check if a text file contain more then one line of text inside?

I have this code:
BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(DateTime.Now + "===> " + Item + Environment.NewLine))));
foreach (string items in tempNamesAndTexts)
{
Logger.Write(items);
}
Once im running the program it will do: Logger.Write(items);
Then the text file will look like:
Danie hello
Ron hi
Yael bye
Josh everyone ok
Next time im running the program it will write to the text file the same strings.
I want to check if this string already exist in the text file dont write them again else do write so the result will be that each time im running the program it will write to the logger(text file) only new strings if there are any.
This is the string variable of the logger text file:
full_path_log_file_name
This variable inside have:
C:\\Users\\Chocolade\\AppData\\Local\\ChatrollLogger\\ChatrollLogger\\log\\logger.txt
This is the complete code untill this part wich is the part that DoWork always do one time when im running the program:
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;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using DannyGeneral;
namespace ChatrollLogger
{
public partial class Form1 : Form
{
string log_file_name = #"\logger.txt";
string full_path_log_file_name;
string path_log;
bool result;
List<string> namesAndTexts;
WebResponse response;
StreamReader reader;
string profileName;
string profileNameText;
string url;
string testingUrl;
int index;
List<string> names;
List<string> texts;
WebClient wc;
public Form1()
{
InitializeComponent();
Logger.exist();
wc = new WebClient();
result = true;
url = "http://chatroll.com/rotternet";
testingUrl = "http://chatroll.com/testings";
backgroundWorker1.RunWorkerAsync();
path_log = Path.GetDirectoryName(Application.LocalUserAppDataPath) + #"\log";
full_path_log_file_name = path_log + log_file_name;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
List<string> tempNamesAndTexts = new List<string>();
string tempDownload = downloadContent();
GetProfileNames(tempDownload);
GetTextFromProfile(tempDownload);
for (int i = 0; i < names.Count; i++)
{
tempNamesAndTexts.Add(names[i] + " " + texts[i]);
}
if (InvokeRequired)
{
BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(DateTime.Now + "===> " + Item + Environment.NewLine))));
foreach (string items in tempNamesAndTexts)
{
Logger.Write(items);
string t = full_path_log_file_name;
}
}
Something like this?
string path = "test.txt";
string valueToWrite = "....";
//only write to the file, if the specified string is not already there
if(!File.ReadLines(path).Any(l => string.Equals(l, valueToWrite)))
{
File.AppendAllText(path, valueToWrite);
}
Use File.ReadAllLines
string[] array = File.ReadAllLines("test.txt");
if(array.Length > 0)
{
// lines exist
}

Categories

Resources