I have an hyperlink that throw the exception :
"This operation is not supported for a relative URI"
Code:
Process.Start(e.Uri.AbsolutePath);
I want to enforce it to open the browser even if the uri is something like : "1aabbb3"
How can I do that ?
System.Diagnostics.Process.Start("iexplore"); should open a very specific browser to it's home page.
You can try using Uri.OriginalString
Process.Start("iexplore.exe", e.Uri.OriginalString);
Edited to reflect clarification in comment.
Solution1: check IsAbsoluteUri and use OriginalString
if (uri.IsAbsoluteUri)
Console.WriteLine("Url:{0}", uri.AbsoluteUri);
else
Console.WriteLine("Url:{0}", uri.OriginalString);
Solution2: define the url protocol
url = "http://someRelativeUrl";
uri = new Uri(url);
Console.WriteLine("Url:{0}", uri.AbsoluteUri);
Related
I want to read following URL and it should save the content available in the page to Text file.
I use below code to read page source:
string address = "view-source:http://stackoverflow.com/"; //any web site url
using (WebClient wc = new WebClient())
{
var Text= wc.DownloadString(address);
}
But it is throwing exception "The URI prefix is not recognized."
Any Help Would be Appreciate.
Thanks! in advance.
You're using a feature of Chrome by prepending "view-source:" to that url. The WebClient class probably doesn't know anything about that feature. It's complaining about the "URI prefix" being unrecognized. That's the "view-source:" portion of your string.
So, remove that part of the URL and you will have a valid url.
string userInput = "view-source:http://stackoverflow.com/";
string address = userInput.Replace("view-source:", "");
Note: this may produce different results for web apps that provide additional content after javascript has been run and interpreted. You might not ultimately get what you want.
Edit: after your comment, it sounds like you want to remove the possibility of the url starting with "view-source:" which I have reflected in the answer.
Just in case you're looking for the "post javascript" source. There's a project on github that offers this feature but I've never used it. I only know about it because it's maintained by a guy I work with.
You can also find a working example in this repl
I have an MVC application and I am going through a strange situation right now.
I am allowing users to stare and Display website URL's. I am using the following method to check whether the following URL is correct or not:
if(Uri.TryCreate(urlString, UriKind.Absolute, out uri))
{
// Do something
}
else
{
// Invalid Url
}
This method is not working because when I try URL starting with "www" or directly with the domain name then it does'not work.
I want the first section of If statement to be bullet proof.
Thanks for you help.
Maybe just try to create a new URI in a try-catch block.
Something like:
Uri myUri = new Uri("http://www.stackoverflow.com")
If you get to the catch then it's a wrong URL.
Currently i am using this code to get the above :
Uri baseUri = new Uri(url);
Uri myUri = new Uri(baseUri, strRef);
domain = baseUri.Host;
Console.WriteLine(myUri.ToString());
strRef = myUri.ToString();
if (strRef.Contains(domain))
{
//THIS MEANS IT BELONGS TO SAME DOMAIN...
}
But using this code i am having some issue like suppose we have a main url = http://www.xxx.co.uk
Then the above code also treats a url like http://www.news.xxx.co.uk as external link ? Is this correct should it do that if not any one know a better solution for this?
I think you are in the correct path. But, to grab the latter mentioned URL (http://www.news.xxx.co.uk/) you could do a quick fix like this.
domain = baseUri.Host.Replace("www.", string.Empty);
Cheers!
vote if helpful.
I'm using Selenium on different machines to automate testing of a MVC Web application.
My problem is that I can't get the base url for each machine.
I can get the current url using the following code:
IWebDriver driver = new FirefoxDriver();
string currentUrl = driver.Url;
But this doesn't help when I need to navigate to a different page.
Ideally I could just use the following to navigate to different pages:
driver.Navigate().GoToUrl(baseUrl+ "/Feedback");
driver.Navigate().GoToUrl(baseUrl+ "/Home");
A possible workaround I was using is:
string baseUrl = currentUrl.Remove(22); //remove everything from the current url but the base url
driver.Navigate().GoToUrl(baseUrl+ "/Feedback");
Is there a better way I could do this??
The best way around this would be to create a Uri instance of the URL.
This is because the Uri class in .NET already has code in place to do this exactly for you, so you should just use that. I'd go for something like (untested code):
string url = driver.Url; // get the current URL (full)
Uri currentUri = new Uri(url); // create a Uri instance of it
string baseUrl = currentUri.Authority; // just get the "base" bit of the URL
driver.Navigate().GoToUrl(baseUrl + "/Feedback");
Essentially, you are after the Authority property within the Uri class.
Note, there is a property that does a similar thing, called Host but this does not include port numbers, which your site does. It's something to bear in mind though.
Take the driver.Url, toss it into a new System.Uri, and use myUri.GetLeftPart(System.UriPartial.Authority).
If your base URL is http://localhost:12345/Login, this will return you http://localhost:12345.
Try this regular expression taken from this answer.
String baseUrl;
Pattern p = Pattern.compile("^(([a-zA-Z]+://)?[a-zA-Z0-9.-]+\\.[a-zA-Z]+(:\d+)?/");
Matcher m = p.matcher(str);
if (m.matches())
baseUrl = m.group(1);
I would like to take the original URL, truncate the query string parameters, and return a cleaned up version of the URL. I would like it to occur across the whole application, so performing through the global.asax would be ideal. Also, I think a 301 redirect would be in order as well.
ie.
in: www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media
out: www.website.com/default.aspx
What would be the best way to achieve this?
System.Uri is your friend here. This has many helpful utilities on it, but the one you want is GetLeftPart:
string url = "http://www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media";
Uri uri = new Uri(url);
Console.WriteLine(uri.GetLeftPart(UriPartial.Path));
This gives the output: http://www.website.com/default.aspx
[The Uri class does require the protocol, http://, to be specified]
GetLeftPart basicallys says "get the left part of the uri up to and including the part I specify". This can be Scheme (just the http:// bit), Authority (the www.website.com part), Path (the /default.aspx) or Query (the querystring).
Assuming you are on an aspx web page, you can then use Response.Redirect(newUrl) to redirect the caller.
Here is a simple trick
Dim uri = New Uri(Request.Url.AbsoluteUri)
dim reqURL = uri.GetLeftPart(UriPartial.Path)
Here is a quick way of getting the root path sans the full path and query.
string path = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,"");
This may look a little better.
string rawUrl = String.Concat(this.GetApplicationUrl(), Request.RawUrl);
if (rawUrl.Contains("/post/"))
{
bool hasQueryStrings = Request.QueryString.Keys.Count > 1;
if (hasQueryStrings)
{
Uri uri = new Uri(rawUrl);
rawUrl = uri.GetLeftPart(UriPartial.Path);
HtmlLink canonical = new HtmlLink();
canonical.Href = rawUrl;
canonical.Attributes["rel"] = "canonical";
Page.Header.Controls.Add(canonical);
}
}
Followed by a function to properly fetch the application URL.
Works perfectly.
I'm guessing that you want to do this because you want your users to see pretty looking URLs. The only way to get the client to "change" the URL in its address bar is to send it to a new location - i.e. you need to redirect them.
Are the query string parameters going to affect the output of your page? If so, you'll have to look at how to maintain state between requests (session variables, cookies, etc.) because your query string parameters will be lost as soon as you redirect to a page without them.
There are a few ways you can do this globally (in order of preference):
If you have direct control over your server environment then a configurable server module like ISAPI_ReWrite or IIS 7.0 URL Rewrite Module is a great approach.
A custom IHttpModule is a nice, reusable roll-your-own approach.
You can also do this in the global.asax as you suggest
You should only use the 301 response code if the resource has indeed moved permanently. Again, this depends on whether your application needs to use the query string parameters. If you use a permanent redirect a browser (that respects the 301 response code) will skip loading a URL like .../default.aspx?utm_source=twitter&utm_medium=social-media and load .../default.aspx - you'll never even know about the query string parameters.
Finally, you can use POST method requests. This gives you clean URLs and lets you pass parameters in, but will only work with <form> elements or requests you create using JavaScript.
Take a look at the UriBuilder class. You can create one with a url string, and the object will then parse this url and let you access just the elements you desire.
After completing whatever processing you need to do on the query string, just split the url on the question mark:
Dim _CleanUrl as String = Request.Url.AbsoluteUri.Split("?")(0)
Response.Redirect(_CleanUrl)
Granted, my solution is in VB.NET, but I'd imagine that it could be ported over pretty easily. And since we are only looking for the first element of the split, it even "fails" gracefully when there is no querystring.