C# check if a string is a valid WebProxy format - c#

so after searching both on here and Google I have been unable to find a solution. Basically I want to allow the user to add a list of proxies from a text file, but I want to check that what gets passed in is a valid Proxy format before I make the WebProxy. I know using try catch like try {var proxy = new WebProxy(host + ":" + port;} catch{} will work, but as you may already know using try catch is slow, even more so when doing it in bulk.
So what would be a good and fast way to test a string to see if it's in a valid WebProxy format?
Thanks

This is how I do it:
var ValidIpAddressPortRegex = #"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]):[\d]+$";
if (System.Text.RegularExpressions.Regex.IsMatch(proxy_string_to_validate, ValidIpAddressPortRegex ))
{
do_stuff_with_proxy();
}
else
{
//MessageBox.Show("IP:PORT url not valid!","Information");
}

Related

Uri.EscapeDataString or HttpUtility.UrlEncode does not work for my case

I have an API in a project which I coded as following:
[Route("api/SearchCustomer/{customer}")]
[HttpGet]
public List<Customer> SearchCustomer(string customer)
{
return customerRepo.GetSearchJoined(customer);
}
At first, I got an issue when I am calling this API from my front end, if customer contains dot or space(for example: https://www.somesite.com/walmart Inc.), I will get 404 error(cannot found this API). I find an easy way to solve this problem. Just add a "/" will solve this problem.(https://www.somesite.com/walmart Inc./ )
Now I need to call this API in another project at the back end. So I did something like this:
var urlParm = "https://www.somesite.com/api/SearchCustomer/" + name + "/";
response = client.GetAsync(urlParm).Result;
var dataObjects = response.IsSuccessStatusCode ? response.Content.ReadAsAsync<IList<Customer>>().Result : null;
return dataObjects;
Unfortunately, adding the "/" at back does not work. I am still getting 404 error. Then, I tried to use Uri.EscapeDataString or HttpUtility.UrlEncode to encode "name".(Does C# have an equivalent to JavaScript's encodeURIComponent()?)
name = Uri.EscapeDataString(name)
or name = HttpUtility.UrlEncode(name)
or name = HttpUtility.UrlPathEncode(name)
var urlParm = "https://www.somesite.com/api/SearchCustomer/" + name + "/";
or var urlParm = = "https://www.somesite.com/api/SearchCustomer/" + name
response = client.GetAsync(urlParm).Result;
var dataObjects = response.IsSuccessStatusCode ? response.Content.ReadAsAsync<IList<Customer>>().Result : null;
return dataObjects;
I have tried all the different matches of above code. All of them did not work. I am still getting the 404 error. Does anyone know what I am doing wrong here?
Sorry for the typo, I removed some sensitive information so I deleted the "api" by mistake. The route is not the problem. I have tested that the api call from the back end worksif name contains only letters or numbers but fails when name contains dot.
The problem is not relevant the customer parameter is encoded or not. You should specify the routing and apply the request correctly. Firstly fix the route;
[Route("api/SearchCustomer/{customer}")]
Then apply the request.
https://www.somesite.com/api/SearchCustomer/samplecustomer

How to find the other part of a string

I'm trying to make C# program that gets a line on a website and use it.
Unfortunately, I don't know the full line on the site. I only know "steam://joinlobby/730/". Although, what comes after "/730/" is always different.
So i need help getting the full line that comes after it.
What I've got:
public void Main()
{
WebClient web = new WebClient();
// here is the site that i want to download and read text from it.
string result = web.DownloadString("http://steamcommunity.com/id/peppahtank");
if (result.Contains("steam://joinlobby/730/"))
{
//get the part after /730/
}
}
I can tell you that it always ends with "xxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxx"
so: steam://joinlobby/730/xxxxxxxxx/xxxxxxxx.
What's to prevent you from just splitting the string on '/730/'?
result.Split(#"/730/")[1]
https://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx
The easiest method for this particular case would be to take the first part, and then just skip that many characters
const string Prefix = #"steam://joinlobby/730/";
//...
if(result.StartsWith(Prefix))
{
var otherPart = result.SubString(Prefix.Length);
// TODO: Process other part
}
Make sure your result is not null and begins with steam://joinlobby/730/
if(string.IsNullOrWhiteSpaces(result) && result.StartsWith("steam://joinlobby/730/"))
{
string rest = result.SubString(("steam://joinlobby/730/").Length);
}

IP data lookup - C#

Okay, so I've googled on several occasions regarding this, but each one suggests respectfully decent choices like : "Selenium" which works fine, but isn't use-able without firefox (or even within an API to my knowledge?).
I have this code :
public byte[] GetFileViaHttp(string url)
{
using (WebClient client = new WebClient())
{
return client.DownloadData(url);
}
}
Then I also have this code :
byte[] result = GetFileViaHttp(#"http://ip-lookup.net/");
string str = Encoding.UTF8.GetString(result);
richTextBox1.Text = str;
Works fine, returns my IP's information, but I want to automate this with other IP addresses, rather than return my own.
How would this be done ?
By this I mean, I want the API to take txtBox1.Text (IP) & print the details into richTextBox1.Text (Host/Country) ..
How could this be done ?
I looked around the site and found a help document that details exactly what you want.
Simply pass the IP value as an unnamed query string parameter:
http://ip-lookup.net/?127.0.0.1
In your code:
byte[] result = GetFileViaHttp(string.Format("http://ip-lookup.net?{0}", ipAddress));
where you are injecting a string ip address as ipAddress.
You can find their help page here. I looked for a legal agreement but I wasn't able to find one, so please use at your own risk and discretion.
UPDATE:
If you are getting 403s, you need to pass along a user agent header. Your WebClient instance can be modified to include a header in the request.
public byte[] GetFileViaHttp(string url)
{
using (WebClient client = new WebClient())
{
client.Headers.Add("User-Agent: Other");
return client.DownloadData(url);
}
}

Validate folder name in C#

I need to validate a folder name in c#.
I have tried the following regex :
^(.*?/|.*?\\)?([^\./|^\.\\]+)(?:\.([^\\]*)|)$
but it fails and I also tried using GetInvalidPathChars().
It fails when i try using P:\abc as a folder name i.e Driveletter:\foldername
Can anyone suggest why?
You could do that in this way (using System.IO.Path.InvalidPathChars constant):
bool IsValidFilename(string testName)
{
Regex containsABadCharacter = new Regex("[" + Regex.Escape(System.IO.Path.InvalidPathChars) + "]");
if (containsABadCharacter.IsMatch(testName) { return false; };
// other checks for UNC, drive-path format, etc
return true;
}
[edit]
If you want a regular expression that validates a folder path, then you could use this one:
Regex regex = new Regex("^([a-zA-Z]:)?(\\\\[^<>:\"/\\\\|?*]+)+\\\\?$");
[edit 2]
I've remembered one tricky thing that lets you check if the path is correct:
var invalidPathChars = Path.GetInvalidPathChars(path)
or (for files):
var invalidFileNameChars = Path.GetInvalidFileNameChars(fileName)
Validating a folder name correctly can be quite a mission. See my blog post Taking data binding, validation and MVVM to the next level - part 2.
Don't be fooled by the title, it's about validating file system paths, and it illustrates some of the complexities involved in using the methods provided in the .Net framework. While you may want to use a regex, it isn't the most reliable way to do the job.
this is regex you should use :
Regex regex = new Regex("^([a-zA-Z0-9][^*/><?\"|:]*)$");
if (!regex.IsMatch(txtFolderName.Text))
{
MessageBox.Show(this, "Folder fail", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);
metrotxtFolderName.Focus();
}

Getting exchange rates from the internet

What I wanna do is, to get exchange rates from internet.
I found this function after long research.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string xmlResult = null;
string url;
url = "http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=" + TextBox1.Text + "&ToCurrency=" + TextBox2.Text + "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader resStream = new StreamReader(response.GetResponseStream());
XmlDocument doc = new XmlDocument();
xmlResult = resStream.ReadToEnd();
doc.LoadXml(xmlResult);
Label1.Text = "Current Exchange Rate for " + TextBox1.Text.ToUpper() + " ---> " + TextBox2.Text.ToUpper() + " value " + doc.GetElementsByTagName("double").Item(0).InnerText;
}
catch(Exception ex)
{
Label1.Text="Not a valid Currency or Try again later";
}
}
But http://www.webservicex.net/ doesn't support AZN (Azerbaijani Manat) to usd and vice versa conversion. What I wanna do is, if it's possible connect to the internet and get rates. Else use written function for conversion (I'VE already written).
What do you advice, how can I get current rates for USD and AZN (or just get result by sending USD or AZN) ? Is there anyway to get it from inside Windows forms application?
This simple algorythm will give you all that you need in a key value pair list.
public static List<KeyValuePair<string, decimal>> GetCurrencyListFromWeb(out DateTime currencyDate)
{
List<KeyValuePair<string, decimal>> returnList = new List<KeyValuePair<string, decimal>>();
string date = string.Empty;
using (XmlReader xmlr = XmlReader.Create(#"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"))
{
xmlr.ReadToFollowing("Cube");
while (xmlr.Read())
{
if (xmlr.NodeType != XmlNodeType.Element) continue;
if (xmlr.GetAttribute("time") != null)
{
date = xmlr.GetAttribute("time");
}
else returnList.Add(new KeyValuePair<string, decimal>(xmlr.GetAttribute("currency"), decimal.Parse(xmlr.GetAttribute("rate"), CultureInfo.InvariantCulture)));
}
currencyDate = DateTime.Parse(date);
}
returnList.Add(new KeyValuePair<string, decimal>("EUR", 1));
return returnList;
}
But http://www.webservicex.net/ doesn't support AZN (Azerbaijani Manat) to usd and vice versa
So? Calculate a cross rate going through another currency.
AZN is likely a fringe currency with very limited volume or exposure. Asking OANDA (http://www.oanda.com) I am getting some quotes, including a USD conversion (http://www.oanda.com/currency/cross-rate/result?quotes=GBP&quotes=EUR&quotes=JPY&quotes=CHF&quotes=USD&quotes=AZN&go=Get+my+Table+%3E)
Likely webservicesx.net just has no prices for something that out of the main currencies.
Use another quote. FXCM and Oanda may have API's you can subscribe to - likely against a price.
Alternative you can see whether you can calculate a cross - go from AZN to another currency if there is a price and from there to USD. This is done frequently in FOREX though - agreeable - the USD mostly is not in the need of a cross rate calculation.
Is there anyway to get it from inside Windows forms application?
When you ask about an API on the internet, then it is totally irrelevant whether it is winforms, webforms, powershell or a vb script, either the API supports it, or not, and the UI Technology you use is irrelevant.
Maybe this will help. I Google'd and I did see some alternative web services, but the ones I looked at did not support AZN. But I didn't spend a ton of time doing that, that is your job. I did find this:
http://www.transfermate.com/en/free_currency_converter.asp
which you can add to your application, maybe by adding a browser control and embedding this on a custom page and retrieving the results to your main form. But ultimately, you answered the question yourself:
Else use written function for conversion (I'VE already written).
If you can't find a solution already out there, build it yourself.
Also try:
https://developers.google.com/finance/ and http://openexchangerates.org/

Categories