HttpUtility.ParseQueryString missing some characters - c#

I'm trying to extract en email with the + special character but for some reason the ParseQueryString skips it:
namespace ParsingProblem
{
class Program
{
static void Main(string[] args)
{
var uri = new System.Uri("callback://gmailauth/#email=mypersonalemail15+1#gmail.com");
var parsed = System.Web.HttpUtility.ParseQueryString(uri.Fragment);
var email = parsed["#email"];
// Email is: mypersonalemail15 1#gmail.com and it should be mypersonalemail15+1#gmail.com
}
}
}

The + symbol in a URL is interpreted as a space character. To fix that, you need to URL encode the email address first. For example:
var urlEncodedEmail = System.Web.HttpUtility.UrlEncode("mypersonalemail15+1#gmail.com");
var uri = new System.Uri($"callback://gmailauth/#email={urlEncodedEmail}");
var parsed = System.Web.HttpUtility.ParseQueryString(uri.Fragment);
var email = parsed["#email"];

Related

How to remove backslash from url when returning from c# code?

public Uri GetCrmUrl(string phone,string organisationid,string server)
{
string _URL = string.Empty;
string clienturl = #"https://petsolutions.crm8.dynamics.com/nga/engagementhub.aspx?org="+organisationid+"&server="+server;
Uri x = new Uri(clienturl,UriKind.Absolute);
return x;
}
I am trying to returning this url directly on html .
But the value returning is like:
https:\/\/petsolutions.crm8.dynamics.com\/nga\/engagementhub.aspx?org=dkejverv&server=dfvfevf
while the expected output is:
https://petsolutions.crm8.dynamics.com/nga/engagementhub.aspx?org=dkejverv&server=dfvfevf
How can i remove those slashes from my URL ?
In C# code, code is returning correct values but at the time of HTML Rendering there are some backslashes there. Check Image Here
Maybe you should try the String.Replace() method:
string test = clienturl.Replace(#"\", string.empty);
Uri x = new Uri(test ,UriKind.Absolute);
return x;
I don't know where you are looking for your string but this example works just the way you want:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Uri test = GetCrmUrl("00000", "orgid", "server");
Console.WriteLine(test);
Console.ReadKey();
}
public static Uri GetCrmUrl(string phone, string organisationid, string server)
{
string clienturl = #"https://petsolutions.crm8.dynamics.com/nga/engagementhub.aspx?org=" + organisationid + "&server=" + server;
Uri x = new Uri(clienturl, UriKind.Absolute);
return x;
}
}
}
Returns:
https://petsolutions.crm8.dynamics.com/nga/engagementhub.aspx?org=orgid&server=server
No need to remove slashes at all.
try this :
return new Uri(HttpUtility.HtmlDecode(clienturl).ToString());

Get host from email string .net core

I need to get the host from an email address string.
In .net 4.x I did this
var email1 = "test#test.com";
var email2 = "test2#yea.test.com"
var email1Host = new MailAddress(email1).Host;
var email2Host = new MailAddress(email2).Host;
email1Host prints "test.com"
email2Host prints "yea.test.com"
But now i need only the "test.com" part in both examples.
.Net Standard library 1.6 doesnt have the System.Net.Mail class so I can't do this anymore.
Whats another way of accomplishing the same thing in .net core but I only need the test.com part
I know there is a System.Net.Mail-netcore nuget package, but I really want to avoid installing a nuget just for this
Edit: Sorry for the confusion I forgot to mention that I only need the test.com
More examples were requested
#subdomain1.domain.co.uk => domain.co.uk
#subdomain1.subdomain2.domain.co.uk => domain.co.uk
#subdomain1.subdomain2.domain.com => domain.com
#domain.co.uk => domain.co.uk
#domain.com => domain.com
Using String Split and Regex,
var email1 = "test#test.com";
var email2 = "test2#yea.test.co.uk";
var email1Host = email1.Split('#')[1];
var email2Host = email2.Split('#')[1];
Regex regex = new Regex(#"[^.]*\.[^.]{2,3}(?:\.[^.]{2,3})?$");
Match match = regex.Match(email1Host);
if (match.Success)
{
Console.WriteLine("Email Host1: "+match.Value);
}
match = regex.Match(email2Host);
if (match.Success)
{
Console.WriteLine("Email Host2: "+match.Value);
}
Update: Using regex to get the Domain name
An alternative is to use the System.Uri class and prefix the email with 'mailto'.
class Program
{
static void Main(string[] args)
{
string email = "test#test.com";
string emailTwo = "test2#subdomain.host.com";
Uri uri = new Uri($"mailto:{email}");
Uri uriTwo = new Uri($"mailto:{emailTwo}");
string emailOneHost = uri.Host;
string emailTwoHost = uriTwo.Host;
Console.WriteLine(emailOneHost); // test.com
Console.WriteLine(emailTwoHost); // subdomain.host.com
Console.ReadKey();
}
}
Well, a bit of C# should do the trick:
string email = "test#test.com";
int indexOfAt = email.IndexOf('#');
//You do need to check the index is within the string
if (indexOfAt >= 0 && indexOfAt < email.Length - 1)
{
string host = email.Substring(indexOfAt + 1);
}

Unable to create a new mail with multiple recipients with mailto uri

I am using creating a Windows 8.1 Store App in WinRT.
I am unable to create a new mail with multiple recipients with the mailto uri by separating each email with either comma or semi colon, both gives me the same error.
Invalid URI: The hostname could not be parsed.
the mailto strings looks like this
"mailto:username#mail.com,username2#mail.com"
"mailto:username#mail.com,username2#mail.com,"
"mailto:username#mail.com, username2#mail.com"
"mailto:username#mail.com;username2#mail.com"
"mailto:username#mail.com;username2#mail.com;"
"mailto:username#mail.com; username2#mail.com"
I have tried all these variants an all give me the same error when newing up the uri, like this.
var uri = new Uri(string.Format("mailto:{0}", mails));
I have no idea what I am doing wrong, or in case its not implemented why it wouldn't be?
I created a few unit tests to see if any variations would work, but no..
[TestClass]
public class UriMailToTest
{
private Uri CreateMailToUri(string mail)
{
if (string.IsNullOrEmpty(mail)) throw new ArgumentNullException("mail");
var uriMailTo = string.Format("mailto:{0}", mail);
return new Uri(uriMailTo);
}
[TestMethod]
public void CreateMailToUriTest1()
{
const string mailto = "username#mail.com";
var uri = CreateMailToUri(mailto);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest2()
{
const string mailto = "username#mail.com,username2#mail.com";
var uri = CreateMailToUri(mailto);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest3()
{
const string mailto = "username#mail.com,username2#mail.com,";
var uri = CreateMailToUri(mailto);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest4()
{
const string mailto = "username#mail.com;username2#mail.com";
var uri = CreateMailToUri(mailto);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest5()
{
const string mailto = "username#mail.com;username2#mail.com;";
var uri = CreateMailToUri(mailto);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest6()
{
const string mailto = "username#mail.com, username2#mail.com";
var uri = CreateMailToUri(mailto);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest7()
{
const string mailto = "username#mail.com; username2#mail.com";
var uri = CreateMailToUri(mailto);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest8()
{
var mails = new[] { "username#mail.com", "username2#mail.com"};
var mailto = mails.Select(WebUtility.UrlEncode).Aggregate((c, n) => string.Format("{0},{1}", c, n));
var uri = CreateMailToUri(mailto);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest9()
{
var mails = new[] { "username#mail.com", "username2#mail.com" };
var mailto = mails.Select(WebUtility.UrlEncode).Aggregate((c, n) => string.Format("{0};{1}", c, n));
var uri = CreateMailToUri(mailto);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest10()
{
var mails = new[] { "username#mail.com", "username2#mail.com" };
var mailto = mails.Aggregate((c, n) => string.Format("{0},{1}", c, n));
var urlEncodedMailTo = WebUtility.UrlEncode(mailto);
var uri = CreateMailToUri(urlEncodedMailTo);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest11()
{
var mails = new[] { "username#mail.com", "username2#mail.com" };
var mailto = mails.Aggregate((c, n) => string.Format("{0};{1}", c, n));
var urlEncodedMailTo = WebUtility.UrlEncode(mailto);
var uri = CreateMailToUri(urlEncodedMailTo);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest12()
{
var mails = new[] { "username#mail.com", "username2#mail.com" };
var mailto = mails.Select(WebUtility.UrlEncode).Aggregate((c, n) => string.Format("{0}, {1}", c, n));
var uri = CreateMailToUri(mailto);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest13()
{
var mails = new[] { "username#mail.com", "username2#mail.com" };
var mailto = mails.Select(WebUtility.UrlEncode).Aggregate((c, n) => string.Format("{0}; {1}", c, n));
var uri = CreateMailToUri(mailto);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest14()
{
var mails = new[] { "username#mail.com", "username2#mail.com" };
var mailto = mails.Aggregate((c, n) => string.Format("{0}, {1}", c, n));
var urlEncodedMailTo = WebUtility.UrlEncode(mailto);
var uri = CreateMailToUri(urlEncodedMailTo);
uri.Should().NotBeNull();
}
[TestMethod]
public void CreateMailToUriTest15()
{
var mails = new[] { "username#mail.com", "username2#mail.com" };
var mailto = mails.Aggregate((c, n) => string.Format("{0}; {1}", c, n));
var urlEncodedMailTo = WebUtility.UrlEncode(mailto);
var uri = CreateMailToUri(urlEncodedMailTo);
uri.Should().NotBeNull();
}
}
with Windows Key + R (Run) typing in mailto:username#mail.com;username2#mail.com works great, I'm just not able to create an Uri object with multiple recipients...
According to the mailto:Protocol # msdn i should be able to use the mailto protocol with multiple recipients.
Syntax
mailto:sAddress[sHeaders]
Tokens
sAddress
One or more valid e-mail addresses separated by a semicolon. You must use Internet-safe characters, such as %20 for the space character.
sHeaders
Optional. One or more name-value pairs. The first pair should be prefixed by a "?" and any additional pairs should be prefixed by a "&". The name can be one of the following strings.
subject
Text to appear in the subject line of the message.
body
Text to appear in the body of the message.
CC
Addresses to be included in the "cc" (carbon copy) section of the message.
BCC
Addresses to be included in the "bcc" (blind carbon copy) section of the message.
There is a hack, using the HyperLinkButton (sorry, this is a dirty hack) :
Load an hyperlinkbutton using a XAmlReader,
Retrieve its AutomationPeer,
Launch a click
var uriString = "mailto:username#mail.com,username2#mail.com";
string xamlString = "<HyperlinkButton "
+ "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" "
+ "NavigateUri=\"" + uriString + "\"/>";
var c = (HyperlinkButton)XamlReader.Load(xamlString);
new HyperlinkButtonAutomationPeer(c).Invoke();
Try adding 2 forward slashes after the hostname like this : mailto://
cant you follow this code?
System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();
email.To.Add("abcd#mail.com");
email.CC.add("abcd1#mail.com");
email.CC.add("abcd2#mail.com");
email.CC.add("abcd2#mail.com");

Check if it is root domain in string

I'm new to C#,
lets say I have a string
string testurl = "http://www.mytestsite.com/hello";
if (test url == root domain) {
// do something
}
I want to check if that string "testurl" is the root domain i.e http://www.mytestsite.com or http://mytestsite.com etc.
Thanks.
Use the Uri class:
var testUrl = new Uri("http://www.mytestsite.com/hello");
if (testUrl.AbsolutePath== "/")
{
Console.WriteLine("At root");
}
else
{
Console.WriteLine("Not at root");
}
Which nicely deals with any normalization issues that may be required (e.g. treating http://www.mytestsite.com and http://www.mytestsite.com/ the same)
You may try like this:
string testurl = "http://www.mytestsite.com/hello"
if ( GetDomain.GetDomainFromUrl(testurl) == rootdomain) {
// do something
}
You can also try using URI.HostName property
The following example writes the host name (www.contoso.com) of the server to the console.
Uri baseUri = new Uri("http://www.contoso.com:8080/");
Uri myUri = new Uri(baseUri, "shownew.htm?date=today");
Console.WriteLine(myUri.Host);
If the hostname returned is equal to "http://mytestsite.com" you are done.
string testurl = "http://www.mytestsite.com/hello";
string prefix = testurl.Split(new String[] { "//" })[0] + "//";
string url = testurl.Replace(prefix, "");
string root = prefix + url.Split("/")[0];
if (testurl == root) {
// do something
}

Parse variable URI (RegEx, Uri, String-Functions?) c#

I'm writing a RTSP client module and for this, I need to parse an very variable URI. But I'm completely stuck about which method I should use (most-failsafe) and how to accomplish this.
An example URI could look like this:
rtsp://192.168.1.100:554/videocam/media/1/video/1
\_/ \_______________/\_______/\______________/
| | | |
scheme authority [sub] [mediacontrol]
But also other possibilities:
192.168.1.100/videocam/media/1/video/1
192.168.1.100:6000/media/1/video/1
192.168.1.100:6000/videocam
I need the following information:
IP | how can I recognise this pattern [num].[num].[num].[num]?
Port | easy if the string contains rtsp://, but what about just a number? 1-65555
Sub | Optional subpath, can completely vary!
MediaLevel | Optional MediaLevel (indicator for stream/track),
not to be confused with the path. MediaLevel can be also just like this: track1 or m1s3 or media1/video1.. see?
I can't go for the slash, also the path also can contain multiple slashes
Maybe there's a library for such tasks?
Thank you.
var uri = new Uri("rtsp://192.168.1.100:554/videocam/media/1/video/1");
var host = uri.Host;
var port = uri.Port;
var sub = uri.Segments[1];
var mlevel = uri.Segments.Skip(2).ToArray();
Here is a quick example of how to use the UriBuilder class. It is a bit verbose because it is an example and is not ready for production. If more subs are to be identified then they can be added to the Sub List as shown in the example.
class Program
{
private static string _scheme = string.Empty;
private static string _host = string.Empty;
private static string _sub = string.Empty;
static void Main(string[] args)
{
ParseUri("rtsp://192.168.1.100:554/videocam/media/1/video/1");
ParseUri("192.168.1.100/videocam/media/1/video/1");
ParseUri("192.168.1.100:6000/media/1/video/1");
ParseUri("192.168.1.100:6000/videocam");
// example of adding a new sub
Sub.Add("sample");
ParseUri("192.168.1.100:6000/sample/");
Console.ReadLine();
}
private static void ParseUri(string URI)
{
UriBuilder uri = new UriBuilder(URI);
_scheme = uri.Scheme;
_host = uri.Host;
_sub = string.Empty;
StringBuilder sb = new StringBuilder();
foreach (string s in uri.Uri.Segments)
{
if (Sub.Contains(s.Replace("/","")))
{_sub = s;}
else
{ sb.Append(s); }
}
Console.Out.WriteLine("+++++++++++++");
Console.Out.WriteLine("URI: {0}",URI);
Console.Out.WriteLine("Scheme: {0}", _scheme);
Console.Out.WriteLine("sub: {0}",_sub);
Console.Out.WriteLine("mediaControl: {0}", sb.ToString());
}
private static List<string> Sub
{
get
{
List<string> sub = new List<string>();
sub.Add("videocam");
return sub;
}
}
}
trace("Url : {0}", turl.Text);
var uri = new Uri(turl.Text);
string host = uri.Host;
int port = uri.Port;
string userInfo = uri.UserInfo;
string subStream = "";
string userName = "";
string password = "";
if (uri.Segments?.Any() == true)
{
subStream = string.Join("", uri.Segments);
}
if (!string.IsNullOrEmpty(userInfo))
{
if (userInfo.Contains(":"))
{
string[] data = userInfo.Split(':');
userName = data[0];
password = data[1];
}
else
{
userName = userInfo;
}
}
trace("host : {0}", host);
trace("port : {0}", port);
trace("userName : {0}", userName);
trace("password : {0}", password);
trace("subStream: {0}", subStream);

Categories