Get host from email string .net core - c#

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);
}

Related

HttpUtility.ParseQueryString missing some characters

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"];

How to translate name using Google Translate in C#?

I'm working on a project (Names Translator ) in C#.
This is my code:
public String Translate(String word)
{
var toLanguage = "en";//English
var fromLanguage = "ar";//Deutsch
var url = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={fromLanguage}&tl={toLanguage}&dt=t&q={HttpUtility.UrlEncode(word)}";
var webClient = new WebClient
{
Encoding = System.Text.Encoding.UTF8
};
var result = webClient.DownloadString(url);
try
{
result = result.Substring(4, result.IndexOf("\"", 4, StringComparison.Ordinal) - 4);
return result;
}
catch
{
return "Error";
}
and it works for most names,
but sometimes Google Translate translates the names literally,
for example
string result=Translate("خوله محمد احمد");
The result will be
He was authorized by Mohamed Ahmed
"خوله" =he was authorized
On the Google Translate website it gives me the same wrong translation:
But as you notice from the picture "khwlh muhamad ahmad" next to red arrow is what I want!
How can I achieve this?

Regex to validate multiple email addresses

I have tried this code to validate multiple email addresses:
string email = "kamilar#recruit12.com; test#minh.com; test2#yahoo.com";
REGEX_EMAIL_ADDRESS_MULTI = #"^\s*([a-zA-Z0-9_%+~=$&*!#?\-\'](\.)?)*[a-zA-Z0-9_%+~=$&*!#?\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*((,|;)\s*([a-zA-Z0-9_%+~=$&*!#?\-\'](\.)?)*[a-zA-Z0-9_%+~=$&*!#?\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*)*$";
Regex reg = new Regex(REGEX_EMAIL_ADDRESS_MULTI);
var isOk = reg.IsMatch(email);
But it does not match - why?
Note that it matches with single address with this following expression:
#"^\s*([a-zA-Z0-9_%\-\'](\.)?)*[a-zA-Z0-9_%\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*$"
Any help?
UPDATED:
I do NOT want to split the string to validate one by one! That's why I need to ask on Stack Overflow!
As others have noted, you should be validating them one at a time.
string email = "kamilar#recruit12.com; test#minh.com; test2#yahoo.com";
string[] emailAddresses = email.Split(';').Select(x=>x.Trim()).ToArray();
string REGEX_EMAIL_ADDRESS_MULTI = #"^\s*([a-zA-Z0-9_%+~=$&*!#?\-\'](\.)?)*[a-zA-Z0-9_%+~=$&*!#?\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*((,|;)\s*([a-zA-Z0-9_%+~=$&*!#?\-\'](\.)?)*[a-zA-Z0-9_%+~=$&*!#?\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*)*$";
bool isOk = true;
foreach (string emailAddress in emailAddresses)
{
Regex reg = new Regex(REGEX_EMAIL_ADDRESS_MULTI);
if (!reg.IsMatch(email))
{
isOk = false;
break;
}
}
split the string at the ';'
string email = "kamilar#recruit12.com; test#minh.com; test2#yahoo.com";
string[] emails = email.Split(';');
then create a method that returns the validity
private bool CheckAddress(string address){
REGEX_EMAIL_ADDRESS_MULTI = #"^\s*([a-zA-Z0-9_%+~=$&*!#?\-\'](\.)?)*[a-zA-Z0-9_%+~=$&*!#?\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*((,|;)\s*([a-zA-Z0-9_%+~=$&*!#?\-\'](\.)?)*[a-zA-Z0-9_%+~=$&*!#?\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*)*$";
Regex reg = new Regex(REGEX_EMAIL_ADDRESS_MULTI);
return reg.IsMatch(email);
}
now just loop through the addresses
for(int i = 0; i > emails.Length; i++){
var isOK = CheckAddress(emails[i]);
}
This address is bad an invalidates the address string
These addresses are OK and the string is allowed
It is my fault as the first email address does not passed the single email regex test so the multiple email regex test should fail.
Thanks.

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
}

C# equivalent of file_get_contents (PHP)

As a follow-up to (OAuthException) (#15) The method you are calling must be called with an app secret signed session I want to know what is the equivalent of file_get_contents(). I tried the following but I got illegal characters in path error.
public ActionResult About()
{
var fb = new FacebookWebClient(FacebookWebContext.Current);
var tokenUrl = "https://graph.facebook.com/oauth/access_token?client_id=" + FacebookWebContext.Current.Settings.AppId + "&client_secret=" + FacebookWebContext.Current.Settings.AppSecret + "&grant_type=client_credentials";
var objReader = new StreamReader(tokenUrl);
string sLine = "";
var arrayList = new ArrayList();
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null)
arrayList.Add(sLine);
}
objReader.Close();
var appToken = arrayList.ToString();
dynamic result = fb.Post(string.Format("{0}/accounts/test-users", FacebookWebContext.Current.Settings.AppId),
new { installed = false, permissions = "read_stream", access_token = appToken });
return Content(result.ToString());
}
I also tried System.IO.File.ReadAllText(tokenUrl) and I got the same error. Is there anything I can do?
I'm not even sure it's going to work, but at least I can try...
You can use WebClient.DownloadString to download text from a URL. The WebClient also supports authentication.
Also, to split your string into lines you can use:
string test;
string[] lines = test.Split('\n');
To use oauth/access_token or any methods related to oauth stuffs use FacebookOAuthClient not FacebookClient or FacebookClient.
FacebookOAuthClient.GetApplicationAccessToken(..)
FacebookOAuthClient.ExchangeCodeForAccessToken(..)

Categories