Get location of client machine using ip address - c#

I am trying to get the location of client machine using ip address. Client can access the internet only if
he/she provide the proxy authenication.
Let us say client need to access the 'www.google.com' on the browser then immediately Authenication Required
prompt window open and then client enter his/her username and password. But it is possible the few users does
not required the provide the authenication in order to access internet.
This segment of code does not helped me...
string url = "http://freegeoip.net/xml/";
WebClient wc = new WebClient();
WebProxy proxyObj = new WebProxy("http://freegeoip.net/xml/");
proxyObj.Credentials = CredentialCache.DefaultCredentials;
Uri uri = new Uri(url);
MemoryStream ms = new MemoryStream(wc.DownloadData(uri));
XmlTextReader rdr = new XmlTextReader(url);
XmlDocument doc = new XmlDocument();
ms.Position = 0;
doc.Load(ms);
ms.Dispose();
In the above code if i add network credential instance with username, password and domain then it's work perfectly
Instead of providing the default net credential in code itself, I need to get the username and password from the users(client
machine).
My question is how to prompt the Authentication Required Window and get the username and password to load the download from url
I would be glad if someone throw light on this issue...
Edit: Somehow basic authentication window prompt and now i can get the username and password which can use for credential
try
{
var reg = HttpContext.Current.Request;
if (!String.IsNullOrEmpty(reg.Headers["Authorization"]))
{
var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(Request.Headers["Authorization"].Substring(6))).Split(':');
var user = new { Name = cred[0], Pass = cred[1] };
string url = "http://freegeoip.net/xml/";
WebClient wc = new WebClient();
WebProxy wProxy = new WebProxy();
ICredentials crd;
crd = new NetworkCredential("'" + cred[0] + "'", "'" + cred[1] + "'");
wProxy = new WebProxy("myproxy", true, null, crd);
wc.Proxy = wProxy;
Uri uri = new Uri(url);
string content = wc.DownloadString(uri);
}
else
{
try
{
//var reg = HttpContext.Current.Request;
if (String.IsNullOrEmpty(reg.Headers["Authorization"]))
{
var res = HttpContext.Current.Response;
res.StatusCode = 401;
res.AddHeader("WWW-Authenticate", "Basic realm = \"freegeoip\"");
//res.End();
}
}
catch (Exception ex)
{
}
}
}
catch(Exception ex)
{
}
But Still It throwing the "Unable to connect to the remote server"

Related

SSIS webClient.UploadString 401 Unauthorized Error

A thousand apologies if this question has been posted already, but I am getting a "The remote server returned an error: (401) Unauthorized" error when attempting to upload a string to a remote server via a web request in SSIS (Visual Studio) by means of a script task - the external company to whom I am sending the data are certain that my public IP and the user credentials I am using to authenticate all have access to the server.
My code looks like this;
public void Main()
{
string proxyServer = (string)Dts.Variables["$Project::ProxyServer"].Value;
int proxyPort = (int)Dts.Variables["$Project::ProxyPort"].Value;
string username = Convert.ToString(Dts.Variables["$Project::UserName"].Value);
string password = Convert.ToString(Dts.Variables["$Project::Password"].GetSensitiveValue());
Uri TargetSite = new Uri((string)Dts.Variables["$Project::TargetSite"].Value);
string datatosend = (string)Dts.Variables["User::RequestBody"].Value;
if (datatosend != "")
{
string result;
using (WebClient webClient = new WebClient())
{
webClient.Proxy = new WebProxy(proxyServer, proxyPort); // Connect via the proxy
var bytes = Encoding.UTF8.GetBytes(username + ":" + password);// Build a means to authenticate
var auth = "Basic " + Convert.ToBase64String(bytes);
NetworkCredential myCreds = new NetworkCredential(username, password);
webClient.Credentials = myCreds;
webClient.Headers[HttpRequestHeader.Authorization] = string.Format("Basic ", credentials);
//webClient.Headers[HttpRequestHeader.Authorization] = auth; // Add the authorization header
webClient.Headers[HttpRequestHeader.ContentType] = "text/json"; // Add information about the content
ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
try
{
result = webClient.UploadString(TargetSite, datatosend); // Issue the request
}
catch (WebException ex)
{
Dts.Events.FireError(0, "", "UnableToSendData: " + ex.Message.ToString() + ex.StackTrace, string.Empty, 0);
return;
}
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
Everything works until the request is issued - that's when I am hit with the 401 error and the response from the Uri is null;
I am at a loss because I am told my public IP is on their permissions list, so not sure why the request fails.
Any assistance would be greatly appreciated.
Many thanks in advance.

How to use a proxy with in HtmlAgilityPack

I need to use a proxy with HtmlAgilityPack.
I give a link to my app RefURL. After that I want the app get url from a proxy address. For instance "101.109.44.157:8080"
I searched and found out this:
WebClient wc = new WebClient();
wc.Proxy = new WebProxy(host,port);
var page = wc.DownloadString(url);
and used it like this.
RefURL = new Uri(refLink.Text);
WebClient wc = new WebClient();
wc.Proxy = new WebProxy("101.109.44.157:8080");
var page = wc.DownloadString(RefURL);
RefURL.ToString();
HtmlWeb web = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load(RefURL.ToString());
but it does not work!
The proxy IP is not responding but also you're not passing web proxy in this code line:
HtmlAgilityPack.HtmlDocument doc = web.Load(RefURL.ToString());
Should be:
HtmlAgilityPack.HtmlDocument doc = web.Load(RefURL.ToString(),"GET", webProxy);
First step is finding "fresh proxy IP" list, for example:
https://geonode.com/free-proxy-list/
https://free-proxy-list.net/uk-proxy.html
https://hidemy.name/en/proxy-list/
http://free-proxy.cz
http://nntime.com
Most of these addresses would work for few hours. Check out how to set proxy IP in a browser. If the proxy is anonymous, this page should be unable to detect your location and IP.
Once you have a proxy IP and port that works, you can create webProxy object or simply pass IP and port.
string RefURL = "https://www.whatismyip.com/";
string myProxyIP = "119.81.197.124"; //check this is still available
int myPort = 3128;
string userId = string.Empty; //leave it blank
string password = string.Empty;
try
{
HtmlWeb web = new HtmlWeb();
var doc = web.Load(RefURL.ToString(), myProxyIP, myPort, userId, password);
Console.WriteLine(doc.DocumentNode.InnerHtml);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Download File From SharePoint 365

string remoteUri = "http://www.contoso.com/library/homepage/images/";
string fileName = "ms-banner.gif", myStringWebResource = null;
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
// Concatenate the domain with the Web resource filename.
myStringWebResource = remoteUri + fileName;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource,fileName);
Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource);
Console.WriteLine("\nDownloaded file saved in the following file system folder:\n\t" + Application.StartupPath);
I'am Using this code from MSDN Web Site
But I have coming across the error: 403 forbidden
Can someone Help me Put this working ?
I was facing the same issue and tried the answer suggested by Vadim Gremyachev. However, it still kept giving 403 error. I added two extra headers to force form based authentication like below:
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add("User-Agent: Other");
After this it started working. So the full code goes like below:
const string username = "username#tenant.onmicrosoft.com";
const string password = "password";
const string url = "https://tenant.sharepoint.com/";
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
var credentials = new SharePointOnlineCredentials(username, securedPassword);
DownloadFile(url,credentials,"/Shared Documents/Report.xslx");
private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl)
{
using(var client = new WebClient())
{
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add("User-Agent: Other");
client.Credentials = credentials;
client.DownloadFile(webUrl, fileRelativeUrl);
}
}
This error occurs since the request is not authenticated. In order to access resource in Office/SharePoint Online you could utilize SharePointOnlineCredentials class from SharePoint Server 2013 Client Components SDK (user credentials flow).
The following example demonstrates how to download a file from SPO:
const string username = "username#tenant.onmicrosoft.com";
const string password = "password";
const string url = "https://tenant.sharepoint.com/";
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
var credentials = new SharePointOnlineCredentials(username, securedPassword);
DownloadFile(url,credentials,"/Shared Documents/Report.xslx");
private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl)
{
using(var client = new WebClient())
{
client.Credentials = credentials;
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.DownloadFile(webUrl, fileRelativeUrl);
}
}

Authentication in wp8

I'm developing WP8 application. I need to add data in the url by using the E-mail id and password. I am using webclient(), but I don't know how to do it. Can anyone help me to complete the task?
Thanks in advance.
My URL format:
http://xx.xx.xxx.xxx/main/content/api/data/pagename?email=abcd#abcd.com&sig=abcd
This is my url structure. I need to add data for the user above.
My Form Design:
![enter image description here][1]
When I click the log-in button I should verify the emailid and password from the above mentioned url structure.
The code below works for posting the data, but I need to know how to post the data by using email and password.
public T Post<T>(string servicePath, string result)
{
string serviceURL = REST_URI + servicePath;
Uri URI = new Uri(serviceURL);
System.Net.WebClient webClient = new WebClient();
webClient.Headers["ContentType"] = "application/json";
webClient.Headers["Accept"] = "application/json";
webClient.UploadStringCompleted += this.sendPostCompleted;
webClient.UploadStringAsync(URI, HTTP_POST, result);
return default(T);
}
Try this , here I'm retrieving username and password from text box,
var username = uname.Text;
var password = pass.Password;
var postData = "email=" + username + "&password=" + password;
WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
var uri = new Uri("Your URL here", UriKind.Absolute);
webClient.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
webClient.AllowWriteStreamBuffering = true;
webClient.Encoding = System.Text.Encoding.UTF8;
webClient.UploadStringAsync(uri, "POST", postData);
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(postComplete);

get html source through proxy

Hi how do I get the source of an html page through a proxy. When I use the code below I get an error saying "Proxy Authentication Required." and I have to go through a proxy.
Dim client As New WebClient()
Dim htmlCode As String = client.DownloadString("http://www.stackoverflow.com")
Then use a proxy that does not need authentication
see here for more info
http://msdn.microsoft.com/en-us/library/system.net.webclient.proxy.aspx
string source = GetPageSource("http://www.stackoverflow.com");
private string GetPageSource(string url)
{
string htmlSource = string.Empty;
try
{
System.Net.WebProxy myProxy = new System.Net.WebProxy("Proxy IP", 8080);
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.Proxy = myProxy;
client.Proxy.Credentials = new System.Net.NetworkCredential("username", "password");
htmlSource = client.DownloadString(url);
}
}
catch (WebException ex)
{
// log any exceptions
}
return htmlSource;
}

Categories