Bug? System.UriFormatException: Invalid URI: The URI scheme is not valid - c#

The strings are identical but when passed as a variable it is not valid?
What the hell is going on? Is it a language bug? I'm running this in C# .Net Core
var postUrl = "​http://www.contoso.com";
var postUri = new Uri("http://www.contoso.com"); // works
var uri = new Uri(postUrl); // does not work

If you pulling your hair, then it because there is space after first opening quote in postUrl. Please remove that space & your bug will be begone.

Worked around the problem by using.
var postUrl = "​http://www.contoso.com";
var uriBuilder = new UriBuilder(postUrl);
var uri = uriBuilder.Uri
Still wondering wtf?
Just the daily wtf of a programmer doing his job.

Related

Part of my url get's removed upon adding a relative path

I have a base url http://some.com/url/that/does/something and a relative url this/is/a/specific/path.
Whenever I try to combine the two using new Uri(baseUrl, relativeUrl) some part of the base url gets cropped. The results with above example is
var baseUrl = new Uri("http://some.com/url/that/does/something")
var relativeUrl = "this/is/a/specific/path";
var Url = new Uri(baseUrl, relativeUrl);
// result is = http://some.com/url/that/does/this/is/a/specific/path
As you might have noticed the something disappeared.
How am I supposed to solve this?
I couldn't find any examples by Googling or searching here on Stackoverflow.com.
You were missing /
Here is Your Answer
var baseUrl = new Uri("http://some.com/url/that/does/something/");
var relativeUrl = "this/is/a/specific/path";
var Url = new Uri(baseUrl, relativeUrl);

How to edit URL with Fiddler(script)?

I want to edit a URL using fiddler. Doesn't have to be with fiddler script, but heres an approximation of how I'm doing it currently:
if (oSession.url.contains("example.com") {
String oldUrl = oSession.url.ToString();
Regex rgx = new Regex("1.2");
String newUrl = rgx.Replace(oldUrl, "1.0");
}
This code is giving me a compiler error on the regex instantiation line: "The list of attributes does not apply to the current context". I'm not entirely sure what this means.
I'm also unsure how exactly to change the url.
Any ideas?
Just got it:
oSession.url = oSession.url.Replace("1.2","1.0");
You can also use
oSession.PathAndQuery = oSession.PathAndQuery.replace('/test1/', '/changed1/');

URL sometimes not being properly encoded - threading issue?

I am working on a Windows Form application in C# and have a method like the following which is being accessed by multiple threads (precisely, by multiple background workers):
public Uri signURL(OAuthToken token, string url)
{
UriBuilder builder = new UriBuilder(addOAuthParameters(url));
NameValueCollection query = HttpUtility.ParseQueryString(builder.Query);
query.Set("oauth_consumer_key", consumerKey);
/*
* & sometimes not replaced by %26
*/
query.Set("oauth_signature", consumerSecret + "&" + token.Secret);
query.Set("oauth_token", token.Token);
builder.Query = query.ToString();
return builder.Uri;
}
I use this method to sign an arbitrary URL with some required OAuth parameters and afterwards do an HttpWebRequest to retrieve the content.
Edit 1: Here is the content of the addOAuthParameter method:
private Uri addOAuthParameters(string uri)
{
UriBuilder builder = new UriBuilder(uri);
NameValueCollection query = HttpUtility.ParseQueryString(builder.Query);
query.Set("oauth_signature_method", "PLAINTEXT");
query.Set("oauth_timestamp", "" + (int)(DateTime.UtcNow -
new DateTime(1970, 1, 1)).TotalSeconds);
query.Set("oauth_nonce", "" + getNonce());
query.Set("oauth_version", "1.0");
builder.Query = query.ToString();
return builder.Uri;
}
Sometimes, the oauth_signature parameter contains an ampersand although this should be properly encoded with %26 by the NameValueCollection object, and, as result, I get a "401 Unauthorized". I have the feeling this happens when the method is being accessed by multiple background workers (multiple threads?). Is that possible?
Edit 2: Okay, it seems that I've narrowed down the issue. If I do a Debug.Assert(builder.Uri.ToString().Contain("%26") && builder.Uri.PathAndQuery.Contains("%26")); it turns out that builder.Uri.ToString() does not contain the %26 while builder.Uri.PathAndQuery does. Now, why's that?
Debugging the issue turned out to be very hard. Does anyone have any suggestions?
Uri.ToString is for display only the docs state that it returns an un-escaped string.
You want to use Uri.AbsoluteUri, Uri.OriginalString or Uri.GetComponents.
var uri = new Uri("http://example.com/some?query=testing%26other");
Console.WriteLine(uri.ToString());
Console.WriteLine(uri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped));
http://example.com/some?query=testing&other
/some?query=testing%26other
GetComponents has the advantage that the escaping is explicitly specified so there's no ambiguity.
Some simple advice (originally from Keith Brown's blog post, Beware Uri.ToString).
Use Uri.AbsoluteUri to get the value of a URI when you know it’s absolute.
Use Uri.OriginalString to get the value of a URI when it could be either absolute or relative (this method does not throw an InvalidOperationException for a relative URI).
Use Uri.ToString to get the value of a URI only when you really want it to be unescaped (e.g. when you want to display it nicely for a human).
When viewing a URI in the debugger, remember the debugger uses Uri.ToString so what you see may not match exactly what the URI contains.

Problem with to read a file with SharpSVN

I am having an issue with the SharpSVN api. When I try to use SvnClient.Write() or SvnClient.Export(), the following error occurs:
Malformed URL for repository
My code is the following
using(SvnClient client = new SvnClient())
{
MemoryStream ms = new MemoryStream();
client.Authenticator.DefaultCredentials = new NetworkCredential("master","master");
SvnTarget t1 = new SvnUriTarget(new Uri("http://ETAB-APP:81/repositorio/"));
SvnTarget t2 = new SvnUriTarget(new Uri("http://ETAB-APP:81/repositorio/Registro e Controle Acadêmico/Administração/0000/Dossiê do Aluno - ADEMIR JOSPE SANGALLI - (2001193) - Curso (000)/DOC ADICIONAL(264839).pdf"));
client.Write(t2, ms);
client.Export(t2, "C:\\chups");
}
It's driving me insane because if I try to execute this method using t1 as SvnTarget, everything works fine. But the problem is that I can't export all the repository everytime I want to get an especific file.
I tried to put an "#" before the name of URL i.e.
http://#ETAB-APP:81/repositorio/Registro e Controle Acadêmico/Administração/0000/Dossiê do Aluno - ADEMIR JOSPE SANGALLI - (2001193) - Curso (000)/DOC ADICIONAL(264839).pdf
but nothing happens.
What am I doing wrong?
PS: Sorry if I did any mistake, I am brazilian and my english is not very good
What I have found is that if you simply pass an arbitrary URL to the Uri object constructor, it will create an invalid Uri that SVN does not understand. This can be due to foreign characters or escaping of certain characters that does not need to be escaped by the default Uri object constructor.
Break up the Uri into its parts by using the UriBuilder object and then pass the resulting Uri to SVN.
// Build Uri by explicitly specifying the constituent parts.
UriBuilder uriBuilder = new UriBuilder("http", "ETAB-APP", 81, "/repositorio/Registro e Controle Acadêmico/Administração/0000/Dossiê do Aluno - ADEMIR JOSPE SANGALLI - (2001193) - Curso (000)/DOC ADICIONAL(264839).pdf");
using(SvnClient client = new SvnClient())
{
MemoryStream ms = new MemoryStream();
client.Authenticator.DefaultCredentials = new NetworkCredential("master","master");
SvnTarget t2 = new SvnUriTarget(uriBuilder.Uri);
client.Write(t2, ms);
client.Export(t2, "C:\\chups");
}
when I call sharpsvn to get svn info by url (that contains '&',and end of '/').sharp svn throw an exception.
thanks sbrogers :
Do you need to escape the url? The SVN Api may do it for you, but it
might be worth trying running it through
msdn.microsoft.com/en-us/library/… – sbrogers Dec 29 '10 at 14:05
I use this code
SvnUriTarget repos = new SvnUriTarget(myUrlString.TrimEnd(new char[] { '/' }));
my problem is resolved.

How to remove the port number from a url string

I have the following code snippet:
string tmp = String.Format("<SCRIPT FOR='window' EVENT='onload' LANGUAGE='JavaScript'>javascript:window.open('{0}');</SCRIPT>", url);
ClientScript.RegisterClientScriptBlock(this.GetType(), "NewWindow", tmp);
The URL generated by this code include the port number and I think that is happening because port 80 is used by the website and in this code I am trying to load a page from a virtual directory of the website. Any ideas on how to suppress the port number in the URL string generated by this code?
Use the Uri.GetComponents method. To remove the port component you'll have to combine all the other components, something like:
var uri = new Uri( "http://www.example.com:80/dir/?query=test" );
var clean = uri.GetComponents( UriComponents.Scheme |
UriComponents.Host |
UriComponents.PathAndQuery,
UriFormat.UriEscaped );
EDIT: I've found a better way:
var clean = uri.GetComponents( UriComponents.AbsoluteUri & ~UriComponents.Port,
UriFormat.UriEscaped );
UriComponents.AbsoluteUri preservers all the components, so & ~UriComponents.Port will only exclude the port.
UriBuilder u1 = new UriBuilder( "http://www.example.com:80/dir/?query=test" );
u1.Port = -1;
string clean = u1.Uri.ToString();
Setting the Port property to -1 on UriBuilder will remove any explicit port and implicitly use the default port value for the protocol scheme.
A more generic solution (works with http, https, ftp...) based on Ian Flynn idea.
This method does not remove custom port, if any.
Custom port is defined automatically depending on the protocol.
var uriBuilder = new UriBuilder("http://www.google.fr/");
if (uriBuilder.Uri.IsDefaultPort)
{
uriBuilder.Port = -1;
}
return uriBuilder.Uri.AbsoluteUri;
April 2021 update
With newer .NET versions, Uri.AbsoluteUri removes the default ports and retains the custom port by default. The above code-snippet is equivalent to:
var uriBuilder = new UriBuilder("http://www.google.fr/");
return uriBuilder.Uri.AbsoluteUri;
I would use the System.Uri for this. I have not tried, but it seems it's ToString will actually output what you want:
var url = new Uri("http://google.com:80/asd?qwe=asdff");
var cleanUrl = url.ToString();
If not, you can combine the components of the url-members to create your cleanUrl string.
var url = "http://google.com:80/asd?qwe=zxc#asd";
var regex = new Regex(#":\d+");
var cleanUrl = regex.Replace(url, "");
the solution with System.Uri is also possible but will be more bloated.
You can use the UriBuilder and set the value of the port to -1
and the code will be like this:
Uri tmpUri = new Uri("http://LocalHost:443/Account/Index");
UriBuilder builder = new UriBuilder(tmpUri);
builder.Port = -1;
Uri newUri = builder.Uri;
You can also use the properties of URIBuilder for this, it has properties for outputting an url the way you want
Ok, thanks I figured it out...used the KISS principle...
string redirectstr = String.Format(
"http://localhost/Gradebook/AcademicHonestyGrid.aspx?StudentID={0}&ClassSectionId={1}&uid={2}",
studid,
intSectionID,
HttpUtility.UrlEncode(encrypter.Encrypt(uinfo.ToXml())));
Response.Redirect(redirectstr );
works fine for what I am doing which is a test harness

Categories