Multitasking checking proxies - c#

I wrote that little program:
string sciezka = "http://proxyjudge.hell-spy.de/";
foreach(var ip in listBox1.Items)
{
////////////////// CHANGES IP:PORT TO WEBPROXY HOST,PORT
string host=null;
string zmiana=null;
string sport = null;
int port=0;
int pozycja=0;
zmiana=ip.ToString();
pozycja=zmiana.IndexOf(":");
host=zmiana.Remove(pozycja);
sport = zmiana.Replace(host + ":", "");
port = int.Parse(sport);
////////////////////////////////////////// CONNECTING TO PROXYJUDGE
string anonymous=null;
try
{
WebRequest request = WebRequest.Create(sciezka);
WebProxy myprox = new WebProxy(host, port);
request.Timeout = 5000;
request.Proxy = myprox;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream strumien = response.GetResponseStream();
StreamReader sr = new StreamReader(strumien);
anonymous = sr.ReadToEnd();
if (anonymous.Contains("HTTP_VIA"))
{
listBox3.Items.Add(zmiana);
}
else
{
listBox2.Items.Add(zmiana);
}
Update();
request.Abort();
sr.Close();
}
catch (Exception ex)
{
listBox3.Items.Add(zmiana);
Update();
}
and I want that it check few proxies at the same time... not one by one :)
can someone help with that?

well, you could use the .AsParallel extension method.
change
foreach(var ip in listBox1.Items)
to
foreach(var ip in listBox1.Items.AsParallel())

Related

API Call not successful

Good day Guys,
I am trying to Use an SMS API. Everything looks fine from my end but the SMS is not delivering. If i use the URL directly on Browser, it executes.
Or is anything wrong with how i built the string?
Below is the code.
Please Note tht cbo.Title is a comobox, txtFirstname is a Textbox.
public void NewText()
{
string username = "something#gmail.com";
string password = "Password";
string urlStr;
string message=" Dear " + cbo_Title.Text + " " + txt_FirstName.Text + ", Your New Savings Account Number is " + Account_No + ".Welcome to AGENTKUNLE Global Services. Your Future is Our Priority ";
string sender = "AGENTKUNLE";
string recipient=txt_Phone.Text;
urlStr = "https://portal.nigeriabulksms.com/api/?username="+username+"+password="+password+"+sender="+sender+"+message="+message+"+ mobiles="+recipient;
Uri success = new Uri(urlStr);
}
private string SendSms(string apiUrl)
{
var targetUri = new Uri(apiUrl);
var webRequest = (HttpWebRequest) WebRequest.Create(targetUri);
webRequest.Method = WebRequestMethods.Http.Get;
try
{
string webResponse;
using (var getresponse = (HttpWebResponse) webRequest.GetResponse())
{
var stream = getresponse.GetResponseStream();
if (stream != null)
using (var reader = new StreamReader(stream))
{
webResponse = reader.ReadToEnd();
reader.Close();
}
else
webResponse = null;
getresponse.Close();
}
if (!string.IsNullOrEmpty(webResponse?.Trim()))
return webResponse.Trim();
}
catch (WebException ex)
{
ErrorHelper.Log(ex);
}
catch (Exception ex)
{
ErrorHelper.Log(ex);
}
finally
{
webRequest.Abort();
}
return null;
}
You never make a request.
The Uri object is just a container for the uri (see Microsoft Docs).
Check out the HttpClient class if you want to send a request.

Post XML to a IP Camera using C#

I have a digital IP camera. It is preset to use set static IP address, and I have asked the manufacturer whether they have an API I can call to set it to DHCP.
They replied:
PUT /Network/interfaces/1/ipAddress HTTP/1.1
Authorization: Basic YWRtaW46MTIzNDU=
Content-Type:text/xml
Content-Length:387
<IPAddress version="1.0" xmlns="http://www.hikvision.com/ver10/XMLSchema">
<ipVersion>v4</ipVersion>
<addressingType>dynamic</addressingType>
<ipAddress>172.2.62.49</ipAddress>
<subnetMask>255.255.255.0</subnetMask>
<DefaultGateway>
<ipAddress>172.2.62.1</ipAddress>
</DefaultGateway>
<PrimaryDNS>
<ipAddress>0.0.0.0</ipAddress>
</PrimaryDNS>
</IPAddress>
So, I translated that to:
private void button1_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest req = null;
WebResponse rsp = null;
string uri = "http://192.0.0.64/Network/interfaces/1/ipAddress";
req =(HttpWebRequest) WebRequest.Create(uri);
req.UseDefaultCredentials = true;
//req.Credentials = new NetworkCredential("admin", "12345"); //I have tried using this as well as these are the default admin/pw supplied
req.Method = "PUT";
req.ProtocolVersion = HttpVersion.Version11;
req.ContentLength = 387;
string _cred = string.Format("{0} {1}", "Basic", "YWRtaW46MTIzNDU=");
req.Headers[HttpRequestHeader.Authorization] = _cred;
req.ContentType = "text/xml";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.WriteLine(GetDHCPPost());
writer.Close();
rsp = req.GetResponse();
}
catch (Exception ex)
{
//errors here >> cannot connect to server
}
}
private string GetDHCPPost()
{
StringBuilder sb = new StringBuilder();
sb.Append("<IPAddress version=\"1.0\" xmlns=\"http://www.hikvision.com/ver10/XMLSchema\">");
sb.Append("<ipVersion>v4</ipVersion>");
sb.Append("<addressingType>dynamic</addressingType>");
sb.Append("<ipAddress>172.2.62.49</ipAddress>");
sb.Append("<subnetMask>255.255.255.0</subnetMask>");
sb.Append("<DefaultGateway>");
sb.Append("<ipAddress>172.2.62.1</ipAddress>");
sb.Append("</DefaultGateway>");
sb.Append("<PrimaryDNS>");
sb.Append("<ipAddress>0.0.0.0</ipAddress>");
sb.Append("</PrimaryDNS>");
sb.Append("</IPAddress> ");
return sb.ToString();
}
But does not work. Am I making an obvious error?
Try this.
If you're using admin/12345.
I made this to write the temperature overlay to my hikvision camera.
Your xml code is definitely correct. I'm not 100% you would need to declare the port number, I know I always had too.
SendToHikVision("admin", "12345", "192.0.0.64", "*The Port You're Using");
void SendToHikVision(string UserName, string Password, string IP, string Port)
{
try
{
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://" + IP + ":" + Port + "/Network/interfaces/1/");
wr.Accept = "*/*";
wr.Method = "PUT";
wr.ReadWriteTimeout = 5000;
wr.Credentials = new NetworkCredential(UserName, Password);
byte[] pBytes = GetDHCPPost();
wr.ContentLength = pBytes.Length;
using (Stream DS = wr.GetRequestStream())
{
DS.Write(pBytes, 0, pBytes.Length);
DS.Close();
}
wr.BeginGetResponse(r => { var reponse = wr.EndGetResponse(r); }, null);
}
catch { }
}
byte[] GetDHCPPost()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<IPAddress version=\"1.0\" xmlns=\"http://www.hikvision.com/ver10/XMLSchema\">");
sb.AppendLine("<ipVersion>v4</ipVersion>");
sb.AppendLine("<addressingType>dynamic</addressingType>");
sb.AppendLine("<ipAddress>172.2.62.49</ipAddress>");
sb.AppendLine("<subnetMask>255.255.255.0</subnetMask>");
sb.AppendLine("<DefaultGateway>");
sb.AppendLine("<ipAddress>172.2.62.1</ipAddress>");
sb.AppendLine("</DefaultGateway>");
sb.AppendLine("<PrimaryDNS>");
sb.AppendLine("<ipAddress>0.0.0.0</ipAddress>");
sb.AppendLine("</PrimaryDNS>");
sb.AppendLine("</IPAddress> ");
return Encoding.ASCII.GetBytes(sb.ToString());
}

Is This Overkill to Retrieve an Int from a Web API REST call?

This code works, but may be only as performant as a 112-year-old alcoholic:
try
{
const string uri = "http://localhost:28642/api/departments/Count";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "GET";
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
MessageBox.Show(string.Format("Content from HttpWebRequest is {0}", s));
}
else
{
MessageBox.Show(string.Format("Status code == {0}", webResponse.StatusCode));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The Web API REST method being called simply returns an int. Is this StreamReader jazz overkill for getting that one simple value? If so, what is the preferred method?
Jon Skeet is on the case - WebClient.DownloadString is easy as (eating) pie:
var client = new WebClient();
MessageBox.Show(client.DownloadString("http://localhost:28642/api/departments/Count"));
IOW, the code I originally showed is definitely overkill for retrieving a scalar value.
UPDATE
Better yet:
private void buttonGetDeptCount2_Click(object sender, EventArgs e)
{
MessageBox.Show(GetScalarVal("http://localhost:28642/api/departments/Count"));
}
private string GetScalarVal(string uri)
{
var client = new WebClient();
return client.DownloadString(uri);
}

How retry try statement in try/catch inside a foreach

Please see this thread:
In this thread we have the same issue answered about do...while. But what about foreach? Meaning how can we retry a try statement in try/catch inside this foreach with another proxy (another number of proxy_line_num integer):
foreach (string link_1 in links_with_kid)
{
try
{
getData = "";
req = (HttpWebRequest)WebRequest.Create(link_1);
req.Method = "GET";
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0";
req.ContentType = "text/html; charset=utf-8";
req.Referer = "http://www.example.com/";
req.KeepAlive = true;
req.Timeout = 25000;
if (useproxy)
{
string[] Ok_ip_port_ar = list_lines_GPL[proxy_line_num].Split(':');
proxy_line_num++;
if (proxy_line_num == list_lines_GPL.Count)
{
proxy_line_num = 0;
}
proxy = new WebProxy(Ok_ip_port_ar[0], int.Parse(Ok_ip_port_ar[1]));
}
req.Proxy = proxy;
req.CookieContainer = cookieJar1;
res = (HttpWebResponse)req.GetResponse();
Stream = res.GetResponseStream();
reader = new StreamReader(Stream);
reader_str = reader.ReadToEnd();
htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(reader_str);
var images = from image in htmlDoc.DocumentNode.Descendants("img")
select image;
string address = string.Empty;
foreach (var image in images)
{
if (image.Attributes["src"] != null)
{
string[] address_ar = image.Attributes["src"].Value.Split('/');
string address_ar_last = address_ar[address_ar.Length - 1];
char[] address_ar_last_char = address_ar_last.ToCharArray();
if (address_ar_last_char.Length == 8
&&
Char.IsUpper(address_ar_last_char[0])
&&
Char.IsUpper(address_ar_last_char[1])
&&
Char.IsUpper(address_ar_last_char[2])
&&
Char.IsUpper(address_ar_last_char[3]))
{
address = image.Attributes["src"].Value;
string localFilename = #"c:\images-from-istgah\" + address_ar_last;
using (WebClient client = new WebClient())
{
client.DownloadFile(address, localFilename);
}
}
}
}
}
catch (Exception ex)
{
}
reader.Close();
Stream.Close();
res.Close();
}
I don't think that you can with a foreach. It is designed to give you the next item in the iterator.
If I were you I would use an ordinary for-loop with an iterator. That way you can control when to go to the next item.
Edit:
When writing it, a while actually made more sense in C#.
IEnumerator<String> iter = list.GetEnumerator();
bool bHasMore = iter.MoveNext();
while (bHasMore) {
try {
...
bHasMore = Iter.MoveNext();
}
catch ...
}
I dont have the entire refernce in my head, so you might need to look something up to get it to compile, but I hope not.

Why does HttpWebrequest through .Net proxy fail?

I have the following code:
int repeat = 1;
int proxyIndex = 1;
if (listBox1.Items.Count == proxyIndex) //If we're at the end of the proxy list
{
proxyIndex = 0; //Make the selected item the first item in the list
}
try
{
int i = 0;
while (i < listBox1.Items.Count)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(textBox1.Text);
string proxy = listBox1.Items[i].ToString();
string[] proxyArray = proxy.Split(':');
WebProxy proxyz = new WebProxy(proxyArray[0], int.Parse(proxyArray[1]));
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
Thread.Sleep(100);
{
repeat++;
continue;
}
}
catch (Exception ex) //Incase some exception happens
{
listBox2.Items.Add("Error:" + ex.Message);
}
I don't understand what I do wrong?
You're not setting Proxy on your HttpWebRequest. (You're creating a WebProxy object, but not using it.) You need to add:
request.Proxy = proxyz;
before calling request.GetResponse().
You also need to fix your use of objects which implement IDisposable. Since they're created in a loop, you cannot delay this - it could be causing any amount of random damage:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
string[] proxyArray = proxyHostAndPort.Split(':');
WebProxy proxyz = new WebProxy(proxyArray[0], int.Parse(proxyArray[1]));
request.Proxy = proxyz;
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string str = reader.ReadToEnd();
}
}

Categories