c# changing this line so it outputs the string as a variable - c#

UPDATE TO POST ORIGIANAL POST AFTER THIS CODE --- this code is an update to what david has been helping me do its throwing one error need help
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string URL = "http://localhost/test2.php";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["var1"] = formData["var1"] = string.Format("MachineName: {0}", System.Environment.MachineName);
formData["var2"] = ip();
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responsefromserver);
webClient.Dispose();
System.Threading.Thread.Sleep(5000);
}
public void ip()
{
String publicIP = "";
System.Net.WebRequest request = System.Net.WebRequest.Create("http://checkip.dyndns.org/");
using (System.Net.WebResponse response = request.GetResponse())
{
using (System.IO.StreamReader stream = new System.IO.StreamReader(response.GetResponseStream()))
{
publicIP = stream.ReadToEnd();
}
}
//Search for the ip in the html
int first = publicIP.IndexOf("Address: ") + 9;
int last = publicIP.LastIndexOf("</body>");
publicIP = publicIP.Substring(first, last - first);
Console.WriteLine(publicIP);
System.Threading.Thread.Sleep(5000);
}
}
}
this is the error I am getting
Error 2 - An object reference is required for the non-static field, method, or property 'ConsoleApplication1.Program.ip()'
I am trying to create a function that will send the out put as var2
I have this c# script
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("MachineName: {0}", System.Environment.MachineName);
System.Threading.Thread.Sleep(5000);
}
}
}
how can I change this so it outputs the string to a variable say "VAR2" and use it in this script
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string URL = "http://localhost/test2.php";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["var1"] = "THIS IS WHERE VAR2 NEEDS TO BE ";
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responsefromserver);
webClient.Dispose();
System.Threading.Thread.Sleep(5000);
}
}
}
SO HOW CAN I ADD THE MACHINE NAME SCRIPT TO THIS FUNCTION AND THEN USE IT AS VAR2
any help would be brilliant
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
public static int Main(string[] args)
{
String publicIP = "";
System.Net.WebRequest request = System.Net.WebRequest.Create("http://checkip.dyndns.org/");
using (System.Net.WebResponse response = request.GetResponse())
{
using (System.IO.StreamReader stream = new System.IO.StreamReader(response.GetResponseStream()))
{
publicIP = stream.ReadToEnd();
}
}
//Search for the ip in the html
int first = publicIP.IndexOf("Address: ") + 9;
int last = publicIP.LastIndexOf("</body>");
publicIP = publicIP.Substring(first, last - first);
Console.WriteLine(publicIP);
System.Threading.Thread.Sleep(5000);
return 0;
}
}
}
her is the update david I would like to incude this script in my other script so it looks like this
formData["var1"] = formData["var1"] = string.Format("MachineName: {0}", System.Environment.MachineName);
formData["var2"] = "this is where this script needs to be ";

Why does it need to be in a separate application? If one application's output is going to be the command-line argument for another application's input, then they're both running on the same machine. Which means, in this case, they'd both get the same value from System.Environment.MachineName.
You can just get the value in the application where it's needed:
formData["var1"] = string.Format("MachineName: {0}", System.Environment.MachineName);

Related

Webclient doesnt like UrlEncoded slash. How to make it work?

I'm trying to pass an URL to an API using a .net 2.0 webclient (unable to upgrade). The webclient call only works if there are no slashes in the encoded value. Any idea why it is failing and how to make it work?
using System.Net;
using System.Text;
using System.Web;
namespace ConsoleAppWebClient
{
class Program
{
static void Main(string[] args)
{
using (var client = new WebClient())
{
client.Encoding = Encoding.UTF8;
client.Headers[HttpRequestHeader.Accept] = "application/xml";
var requestUrl = HttpUtility.UrlEncode("https://www.somewebsite.com");
var stringResult = client.DownloadString("https://localhost:12345/api/getstuff/" + requestUrl);
}
}
}
}
The above doesnt work but the below works just fine
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using System.Web;
namespace ConsoleAppWebClient
{
class Program
{
static void Main(string[] args)
{
using (var client = new WebClient())
{
client.Encoding = Encoding.UTF8;
client.Headers[HttpRequestHeader.Accept] = "application/xml";
var requestUrl = HttpUtility.UrlEncode("https:www.somewebsite.com");
var stringResult = client.DownloadString("https://localhost:12345/api/getstuff/" + requestUrl);
}
}
}
}
It looks like requestUrl is meant to be a query parameter, but you're adding it to the URL's path.
The result is
https://localhost:12345/api/getstuff/https%3A%2F%2Fwww.somewebsite.com
"%" is an unsafe character which can lead to unpredictable results.
Instead, try making it a querystring parameter:
var requestUrl = HttpUtility.UrlEncode("https:www.somewebsite.com");
var stringResult = client.DownloadString(
"https://localhost:12345/api/getstuff/?requestUrl=" + requestUrl);
Now that the URL-encoded parameter is in the querystring instead of the path it should be okay.

adding an Interface

My main Program.cs is as follows:
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.IO;
using System.Threading.Tasks;
namespace HTTPrequestApp
{
class Program
{
static void Main(string[] args)
{
var lstWebSites = new List<string>
{
"www.amazon.com",
"www.ebay.com",
"www.att.com",
"www.verizon.com",
"www.sprint.com",
"www.centurylink.com",
"www.yahoo.com"
};
string filename = #"RequestLog.txt";
{
using (var writer = new StreamWriter(filename, true))
{
foreach (string website in lstWebSites)
{
for (var i = 0; i < 4; i++)
{
MyWebRequest request = new MyWebRequest();
request.Request();
}
}
}
}
}
}
}
Then I have a class, and this is where the errors are.
The GetList() error - 'HTTPrequestApp.Program' does not contain a definition for 'GetList'
The client2 error - The name 'client2' does not exist in the current content
MyWebRequest.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace HTTPrequestApp
{
public class MyWebRequest : HTTPrequestApp.IWebRequest
{
public void Request()
{
List<string> lstWebSites = Program.GetList();
using (var client = new TcpClient(lstWebSites[1], 80))
{
using (NetworkStream stream = client2.GetStream())
using (StreamWriter writer = new StreamWriter(stream))
using (StreamReader reader2 = new StreamReader(stream))
{
writer.AutoFlush = true;
writer.WriteLine("GET / HTTP/1.1");
writer.WriteLine("HOST: {0}:80", lstWebSites[1]);
writer.WriteLine("Connection: Close");
writer.WriteLine();
writer.WriteLine();
string theresponse = reader2.ReadToEnd();
Console.WriteLine(theresponse);
}
}
}
}
}
Finally, I have an Interface. Is this done correctly?
If I am doing something incorrectly please help me, how should I fix it?
IWebRequest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HTTPrequestApp
{
interface IWebRequest
{
void Request();
}
}
What I have to do is: send HTTP request to get the initial page and get back the HTTP response. Save it into the .cvs file. Check that it is a 200 response code and time how long it took to retrieve the response. I have to get the response 4 times from each of those websites in my list.
Please help me.
First about your errors :
The provided code does not contain GetList method in Program class as the code shared contains the only main method which defines your websites.
The line using (var client = new TcpClient(lstWebSites[1], 80)) creates client object instead of client2.
Another point, instead of writing to open TCPClient connection to read the response of website you can use HttpClient or WebRequest in-built classes to achieve your functionality.
Here's a full example of what I mean. Keep adding all the websites you want to lstWebSites, and instead of dumping the HTML results to the console, you can write them to a file.
var lstWebSites = new List<string>
{
"https://www.stackoverflow.com",
"https://www.google.com"
};
foreach (string website in lstWebSites)
{
var request = WebRequest.Create(website);
request.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)request).UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"; // Lie
var response = request.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
var stream = response.GetResponseStream();
var reader = new StreamReader(stream);
Console.WriteLine(string.Format("***** {0} *****", website));
Console.WriteLine(reader.ReadToEnd()); // Dump HTML response
}
}

Error with C# Web crawler

Can some one please assist me with this webcrawler, I keep getting the error :
Cannot implicitly convert type
'System.Collections.Generic.ISt' to 'string.
This error is in line where it is String Links = GetNewLinks(Rstring);, can someone please help, here is my 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;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace Crawler
{
public partial class Crawler : Form
{
String Rstring;
public Crawler()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
WebRequest myWebRequest;
WebResponse myWebResponse;
String URL = txt1.Text;
myWebRequest = WebRequest.Create(URL);
myWebResponse = myWebRequest.GetResponse();
Stream streamResponse = myWebResponse.GetResponseStream();
StreamReader sreader = new StreamReader(streamResponse);
Rstring = sreader.ReadToEnd();
String Links = GetNewLinks(Rstring);
txt2.Text = Rstring;
txt3.Text = Links;
sreader.Close();
streamResponse.Close();
myWebResponse.Close();
}
public ISet<string> GetNewLinks(string content)
{
Regex regexL = new Regex("(?<=<a\\s*?href=(?:'|\"))[^'\"]*?(?=(?:'|\"))");
ISet<string> newLinks = new HashSet<string>();
foreach (var match in regexL.Matches(content))
{
if (!newLinks.Contains(match.ToString()))
newLinks.Add(match.ToString());
}
return newLinks;
}
}
}
GetNewLinks() returns a set of strings (ISet<String>), not one only. So if you want to assign to a single string (String Links) then you have to select a string from the set, e.g. using First().

C# Grabbing text from a span

I tried this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Sockets;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Danish to English: ");
string tittyfuck = Console.ReadLine();
Console.Beep();
WebRequest webRequest = new WebRequest.Create("http://translate.google.com/#da/en/" + tittyfuck);
WebResponse webResponse = webRequest.GetResponse();
Stream data = webResponse.GetResponseStream();
string html;
using (StreamReader streamReader = new StreamReader(data))
{
string line;
while ((line = streamReader.ReadLine() != null))
{
if (line == "<span class=\"hps\">")
{
Console.Beep();
Console.WriteLine(line);
}
}
}
}
}
}
Okay, so I try that but I get these errors:
Error 1 'System.Net.WebRequest.Create(System.Uri)' is a 'method' but is used like a 'type' C:\Users\Dylan\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 18 52 ConsoleApplication1
and
Error 2 Cannot implicitly convert type 'bool' to 'string' C:\Users\Dylan\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 27 32 ConsoleApplication1
As you can probably tell, I'm trying to open a request to translate.google.com with the text after the link, which then grabs the text that's printed to the which is the translated text.. It's basically a translator.
Please help.
Line 18:
WebRequest webRequest = WebRequest.Create(new URI("http://translate.google.com/#da/en/" + tittyfuck));
Line 27:
while ((line = streamReader.ReadLine()) != null)
Remove the new keyword, and set other parenthesis.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Sockets;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Danish to English: ");
string tittyfuck = Console.ReadLine();
Console.Beep();
WebRequest webRequest = WebRequest.Create("http://translate.google.com/#da/en/" + tittyfuck);
WebResponse webResponse = webRequest.GetResponse();
Stream data = webResponse.GetResponseStream();
string html;
using (StreamReader streamReader = new StreamReader(data))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
if (line == "<span class=\"hps\">")
{
Console.Beep();
Console.WriteLine(line);
}
}
}
}
}
}
You can't use google translate in this way because the translation is requested by javascript, you can try with a webbrowser or buying some characters for using the translate api
Another way is parsing the result of the request(http://translate.google.com/translate_a/t?....) , that is in json style

Unable to post data through HttpClient PostAsync

I am using HttpClient to send the data to the server through C# console application using post .
The HttpClient PostAsync is unable to post the data I have tried to send in various format
i.e string content , binary content , stream content , http content through Dictionary object but the post is null and the server is returning the request invalid exception below is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Windows;
using System.Windows.Input;
using System.IO;
using System.Web;
namespace ConsoleApplication1
{
class Program
{
string str = ""; int j = 0;
static void Main(string[] args)
{
Program df = new Program();
df.Started();
}
public async void Started()
{
string contentLength="0";
try
{
contentLength = await AccessTheWebAsync();
}
catch (Exception e)
{
}
Console.WriteLine(contentLength);
}
async Task<string> AccessTheWebAsync()
{
HttpClient client = new HttpClient();
string token = "qwerty1234";
string test = "1";
string postrequest = "<?xml version='1.0' encoding='UTF-8'?>" +
"<request> " +
"<rec>asdf1234</rec> " +
" <lid>9876</lid> " +
"</request> ";
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("token", token);
dict.Add("test", test);
dict.Add("request", postrequest);
HttpContent content = new FormUrlEncodedContent(dict);
Uri url = new Uri("http://example.com/");
Task<HttpResponseMessage> getStringTask = client.PostAsync(url, content);
HttpResponseMessage httpmesssage = await getStringTask;
Stream respons = await httpmesssage.Content.ReadAsStreamAsync();
StreamReader sr = new StreamReader(respons);
string response = sr.ReadToEnd();
return response;
}
}
}
thanks in advance
In a Console application, you need to wait for the operation to complete, either using Task.Wait, Console.ReadKey, or similar. Also, avoid async void:
static void Main(string[] args)
{
Program df = new Program();
df.StartedAsync().Wait();
}
public async Task StartedAsync()

Categories

Resources