alright I'm doing something that should be rather simple, I believe I am overlooking something here.
Alright I and using a HttpWebRequest and a WebResponse to detect if a Robots.txt exists on a server (and that works perfectly fine). However, I am trying to add to do myList.Add(reader.ReadLine()); Which (works). But problem is, it keeps skipping the very first line.
https://www.assetstore.unity3d.com/robots.txt < That is the one I started noticing the problem on (just so you know what I'm talking about). It is just for testing purposes. (Look at that link so you can get an idea as to what I'm talking about).
Anywho, it is also not adding the reader.ReadLine to my list either (first line only). So I'm not exactly understanding what's going on, I've tried looking this up and the only things I'm finding is to purposely want to skip a line, I don't want to do that.
My Code Below.
Console.WriteLine("Robots.txt Found: Presenting Rules in (Robot Rules).");
HttpWebRequest getResults = (HttpWebRequest)WebRequest.Create(ur + "robots.txt");
WebResponse getResponse = getResults.GetResponse();
using (StreamReader reader = new StreamReader(getResponse.GetResponseStream())) {
string line = reader.ReadLine();
while(line != null && line != "#") {
line = reader.ReadLine();
rslList.Add(line);
results.Text = results.Text + line + Environment.NewLine; // At first I thought it might have been this (nope).
}
// This didn't work either (figured perhaps maybe it was skipping because I had to many things.
// So I just put into a for loop, - nope still skips first line.
// for(int i = 0; i < rslList.Count; i++) {
// results.Text = results.Text + rslList[i] + Environment.NewLine;
// }
}
// Close the connection sense it is no longer needed.
getResponse.Close();
// Now check for user-rights.
CheckUserRights();
Image of the results.
Change when next you call the read line
var line = reader.ReadLine(); //Read first line
while(line != null && line != "#") { //while line condition satisfied
//perform your desired actions
rslList.Add(line);
results.Text = results.Text + line + Environment.NewLine;
line = reader.ReadLine(); //read the next line
}
Related
I am working with C# for the first time and I am facing a strange issue.
I am building my own class for a plugin, but copied parts of the code from an existing class. Basically it's
var sanInput = Console.ReadLine();
alternativeNames = sanInput.Split(',');
sanList = new List<string>(alternativeNames);
but somehow this doesn't work. The debug console says System.Console.ReadLine returned jogi,philipp string, but sanInput keeps null as its value.
Even stranger is the fact, that the next step works "a bit". string.Split returned {string[2]} string[], so it returns an array of [jogi, philipp], but still sanInput, alternativeNamesand sanList stay as null.
How is it possible, that the second line works if sanInput has no value and how can I fix this problem? When I work with the existing class with the same code everything works as expected.
//EDIT:
Looks like a quite complicated issue. Here is the complete method:
public override void HandleMenuResponse(string response, List<Target> targets)
{
if (response == "r")
{
Console.WriteLine("Which hosts do you want to configure? Enter numbers separated by a comma.");
var hostsInput = Console.ReadLine();
int[] hosts = null;
string[] alternativeNames = null;
List<string> sanList = null;
hosts = hostsInput.Split(',').Select(int.Parse).ToArray();
Console.Write("Generating certificates for ");
foreach (int entry in hosts)
{
Console.Write(targets[entry - 1].Host + ", ");
}
Console.Write("\n \n");
foreach (int entry in hosts)
{
int entry2 = entry - 1;
if (Program.Options.San)
{
Console.WriteLine("Enter all Alternative Names for " + targets[entry2].Host + " seperated by a comma:");
// Copied from http://stackoverflow.com/a/16638000
int BufferSize = 16384;
Stream inputStream = Console.OpenStandardInput(BufferSize);
Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, BufferSize));
var sanInput = Console.ReadLine();
alternativeNames = sanInput.Split(',');
sanList = new List<string>(alternativeNames);
targets[entry2].AlternativeNames.AddRange(sanList);
}
Auto(targets[entry - 1]);
}
}
if (response == "e")
{
string[] alternativeNames = null;
List<string> sanList = new List<string>();
if (Program.Options.San)
{
Console.WriteLine("Enter all Alternative Names seperated by a comma:");
// Copied from http://stackoverflow.com/a/16638000
int BufferSize = 16384;
Stream inputStream = Console.OpenStandardInput(BufferSize);
Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, BufferSize));
var sanInput = Console.ReadLine();
alternativeNames = sanInput.Split(',');
}
if (alternativeNames != null)
{
sanList = new List<string>(alternativeNames);
}
foreach (var entry in targets)
{
Auto(entry);
}
}
}
I know the code isn't pretty and efficient. All in all it let's the user decide if he wants to use all detected hosts (response e) or only single ones (response r). But the mentioned problem occurs only in the second if-method. If I switch them it's again the latter one. So maybe the reason lies in the main program or in this BufferSize-Stuff? I don't know.
//EDIT 2: I think I found the problem: Somehow the integer BufferSize (shortly before the Console.Read()) is set to 0, so of course without any buffer it can't read the input. So the question remains: Why?
//EDIT 3: Okay, I'm done. It looks like I can't use the same name for the variables although they are in two different if-methods. I just named them sanInput2, alternativeNames2 etc. and now everything works.
try this, all of the variables are having values(you can use var also for all the variables):
var sanInput = Console.ReadLine();
string[] alternativeNames = sanInput.Split(',');
List<string> sanList = new List<string>(alternativeNames);
The problem you mention is, that debugging code in VS do assignements in two steps. First is to execute Console.ReadLine() (therefore you see Console.Readline returned message) and AFTER that is is assigned into sanInput. Same situation is after Split. Function is called, but not assigned yet.
My recommendation: use rather the step over instead of step inside. After time, you get used to this functionality and appreciate it.
I need to check if a element exists basically and if it does I want to open a url then back to the original page and then continue writing as it was. I tried a few approaches but they kept giving throwing exceptions. I added comments to the lines in question. I just cant figure out how to implement it.
foreach (string line in File.ReadLines(#"C:\\tumblrextract\\in7.txt"))
{
if (line.Contains("#"))
{
searchEmail.SendKeys(line);
submitButton.Click();
var result = driver.FindElement(By.ClassName("invite_someone_success")).Text;
if (driver.FindElements(By.ClassName("invite_someone_failure")).Count != 0)
// If invite_someone_failure exists open this url
driver.Url = "https://www.tumblr.com/lookup";
else
// Then back to following page and continue searchEmail.SendKeys(line); submitButton.Click(); write loop
driver.Url = "https://www.tumblr.com/following";
using (StreamWriter writer = File.AppendText("C:\\tumblrextract\\out7.txt"))
{
writer.WriteLine(result + ":" + line);
}
}
}
What is the exception you are getting? probably it may be Null reference exception. Please consider adding Null check in your code for the following
if(By.ClassName("invite_someone_success") != null){
var result = driver.FindElement(By.ClassName("invite_someone_success")).Text;
}
Above is not verified/exact code, just a pseudo code
you are using selenium and your might throw exceptions in some lines of code you have there - also take in consideration that i don't know tumblr website and it's html structure.
But first:
You're in a foreach loop and everytime you load at least once a page, all your elements will Stale, so this lines:
var searchEmail = driver.FindElement(By.Name("follow_this"));
var submitButton = driver.FindElement(By.Name("submit"));
will probably Stale in the next execution. (ElementStaleException).
Paste them too after:
driver.Url = "https://www.tumblr.com/following";
Second:
when using FindElement method you have to make sure the element exists or an ElementNotFoundException will also be thrown.
var result = driver.FindElement(By.ClassName("invite_someone_success")).Text;
var isThere = driver.FindElements(By.ClassName("invite_someone_failure"));
the dotNet selenium client have a static (i believe) class to help with that it's the ExpectedCondition
that you can use to check if an element is present before trying to read it's text..
I Invite you to understand how selenium works, specially StaleElementReferenceException.
Have fun.
I'm working to program a MCU board over RS485. I have the section of code done to access the bootloader no problem. My problem is in this code:
int xon_off = ComPort.ReadChar();
if (xon_off == send_data) {
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("C:/Users/user/Desktop/x.hex");
while ((line = file.ReadLine()) != " ") // reads until end of file
{
write_line: line = file.ReadLine();
if (xon_off == send_data) {
ComPort.Write(line);
//System.Threading.Thread.Sleep(500);
counter++;
xon_off = ComPort.ReadByte(); // should be x_off
error_check = ComPort.ReadByte(); // will give line complete or error
xon_off = ComPort.ReadByte(); // should be x_on
} else if (xon_off == stop_data) {
read_again: xon_off = ComPort.ReadByte();
if (xon_off == send_data) {
goto write_line;
} else {
goto read_again;
}
}
}
My issue is with the flow control (x_on/x_off/eof/etc). The way the current code is, it can send a page error, and the tool keeps sending like it was nothing, so obviously my read/compare statements are off. Can someone help me find out why when it sends a page error, my code thinks it's sending an x_on?
NOTE: x_on is a variable above set to 0x11 and x_off is a var above set to 0x13 just to clarify.
NOTE: Once I get this figured out, my next step is to remove the goto statements...they're gross I know, but they worked for here.
Ok so from what I can understand, here's what the better option is:
First off, do remove the goto statements, they're horrindious and should never be used. As for the issue of not being able to mix chars/hex values, every char when brought in as an int will be assigned it's hex value (convert to int32 in the program). When the bootloader sends the 0x11, it will more than likely send it as a char, which will come into your software as an unprintable ASCII char, but still have the 0x11 if you use your debugger and see what it's actually coming in as. So my suggestion is to do a readbyte, then do a convert to int32 in software, and do a switch statement/state machine for what you want done.
I have a code that gets a line of text from raw.githubusercontent.com
WebRequest webRequest = WebRequest.Create(getargs[1]);
using (WebResponse response = webRequest.GetResponse())
using (Stream content = response.GetResponseStream())
using (StreamReader reader = new StreamReader(content))
{
string strCntent = reader.ReadToEnd();
string[] plgnCntn;
plgnCntn = strCntent.Split('(', ')', ':', ',');
if (plgnCntn[0] != "validplgn")
{
newln("Plgn couldn't be installed. Not validated.");
}
else
{
string dmy = plgnCntn[1];
dummy = dmy.Split('-');
install_id = Convert.ToInt32(dummy[1]);
dummy = plgnCntn[2].Split('-');
install_plgn_nme = dummy[1];
dummy = plgnCntn[3].Split('-');
install_cmmd = dummy[1];
plgnbyID.Add(install_id, install_plgn_nme);
plgncmds.Add(install_plgn_nme, install_cmmd);
inverseplgncmds.Add(install_cmmd, install_plgn_nme);
plgnparse.Add(install_plgn_nme, plgnCntn[4]);
}
}
And all seems fine, the program gets the data, i'm testing with
"validplgn(id-0001,plgn_nme-plgn,cmmd-plgninfo):{ln-This plugin has been downloaded from the creator's GitHub;hlp-hlp}"
When it gets the data, it splits it in
"validplgn", "id-0001", "plgn_nme-plgn", "cmmd-plgninfo", "{ln-This plugin has been downloaded from the creator's GitHub;hlp-hlp}"
It is supposed to test if [0] == "validplgn", saves all the data in dictionaries. When all of this data is saved, the program continues running and checking for commands in a loop. Basically detecting what I put on the textbox, checking IF statements and giving answers, when the content in the textbox doesn't match with any command, it writes:
"Command wasn't recognized. Please type hlp".
The problem comes, i think, in this code:
else if (plgncmds.ContainsValue(inp))
{
string plgnnme;
string toparse;
string[] splitparse = {};
int arglength;
inverseplgncmds.TryGetValue(inp, out plgnnme);
plgnparse.TryGetValue(plgnnme, out toparse);
splitparse = toparse.Split(';');
arglength = splitparse.Length;
foreach (string statement in splitparse)
{
string[] dmmy = statement.Split('-');
...
At the final of the checker loop, tests if the unknown command to the client matches with any downloaded command in:
else if (plgncmds.ContainsValue(inp))
So, when i input "plgninfo", that is the text that executes this code:
{ln-This plugin has been downloaded from the creator's GitHub;hlp-hlp}
It was declared before, when "cmmd-plgninfo", was splitted and saved the plgninfo part. Now this code gets the key on the dictionary using the command (plgninfo), but it doesn't display anything. And thats the problem. It should print "This plugin has been downloaded from the creator's GitHub" and show program help for the command "hlp". but nothing, I have ReSharper 9 in VS 2013 and any issue is thrown, just nothing happens.
I hope theres a way to fix.
Thanks.
i'm having trouble searching a virtual listview in c#.
what i am doing right now is reading a large log file. here is what i have implemented so far
I read the file one line at a time and note the position of the start of the line. Add these positions to a List and when RetrieveVirtualItem is called - look up the position in the file using the index of the item and the List and then read the line from file.
So there is no lag when reading the file.
I want to now search for items. Here is what I have thought of so far, but I have not been able to implement it successfully.
I am not actually searching the listview, but during my filereading, i mark the position of hits of the specific string, say "INFO". if it hits, i add the position to a List.
When RetrieveVirtualItem is called, I just read the line back with all the hits.
Seems that through debugging - if (line.IndexOf("INFO", StringComparison.OrdinalIgnoreCase) >= 0) is not hitting any matches. I'm not sure why, anyone help?
using (var sr = new myStreamReader("test.log"))
{
while ((line = sr.ReadLine()) != null)
{
if (line.IndexOf("INFO", StringComparison.OrdinalIgnoreCase) >= 0)
{
position = sr.BytesRead;
Search.Add(position);
searchcount++;
}
}
newMessageView.VirtualListSize = searchcount;
}
I don't know how your "myScreamReader" class works, but if it similar to StreamReader this code could be working for you:
using (var sr = new StreamReader("test.log"))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (line.IndexOf("INFO", StringComparison.OrdinalIgnoreCase) >= 0)
{
// line contains "info"
}
}
}
You should debug your code by setting a breakpoint at line.IndexOf... check to see if value of line is changing and look correct.