Here is a question related to a Microsoft Exchange-integration.
I am calling the Microsoft Exchange Services-method ResolveName (string):
I am passing in a username, e.g. myusername , and I get two matches -one match with the username myusername and one with myusername2.
Now the question is: Is there any possibility to do a call that only returns direct matches, so that only matches with the exact username are returned?
Here follows the code:
:
var service = Service.GetService();
username = Regex.Replace(username, ".*\\\\(.*)", "$1", RegexOptions.None);
var resolvedNames = service.ResolveName(username);
foreach (var resolvedName in resolvedNames)
{
mailboxname = resolvedName.Mailbox.Address;
}
That method actually resolves e-mail addresses, so for an exact match you'd need to do something like this.
string username = "myUserName";
string domain = "myDomain.com";
string emailAddress = username + "#" + domain;
NameResolutionCollection resolvedContactList = _service.ResolveName(emailAddress);
If you cannot specify the 'username' any further than myusername (as Amicable's answer assumes you can do) then the only thing to do is write a wrapper around ResolveName that again matches all results against your search string, this time requiring an exact match.
And for doing so you would have to parse the domain name off again, because you get the full primary SMTP email address returned in .Mailbox.Address.
I'm doing the exact same thing in my Delphi code ;-)
Related
I am having a requirement to correctly get the domain/subdomain based on the current url. this is required in order to correctly fetch the data from database and further call web api with correct parameters.
In perticular, I am facing issues with local and production urls. for ex.
In local, i have
http://sample.local.example.com
http://test.dev.example.com
In production, i have
http://client.example.com
http://program.live.example.com
i need
Subdomain as: sample / test / client / program
Domain as: exmpale
So far i tried to use c# with following code to identify the same. It works fine on my local but i am sure this will create an issue on production at some point of time. Basically, for Subdomain, get the first part and for Domain, get the last part before ''.com''
var host = Request.Url.Host;
var domains = host.Split('.');
var subDomain = domains[0];
string mainDomain = string.Empty;
#if DEBUG
mainDomain = domains[2];
#else
mainDomain = domains[1];
#endif
return Tuple.Create(mainDomain, subDomain);
Instead of a regex, I think Linq should help your here. Try:
public static (string, string) GetDomains(Uri url)
{
var domains = url.Host.Substring(0, url.Host.LastIndexOf(".")).Split('.');
var subDomain = string.Join("/", domains.Take(domains.Length - 1));
var mainDomain = domains.Last();
return (mainDomain, subDomain);
}
output for "http://program.live.example.com"
example
program/live
Try it Online!
This regex should work for you:
Match match = Regex.Match(temp, #"http://(\w+)\.?.*\.(\w+).com$");
string subdomain = match.Groups[1].Value;
string domain = match.Groups[2].Value;
http://(\w+)\. matches 1 or more word characters as group 1 before a dot and after http://
.* matches zero or more occurences of any character
\.(\w+).com matches 1 or more word characters as group 2 before .com and after a dot
$ specifies the end of the string
\.? makes the dot optional to catch the case if there is nothing between group 1 and 2 like in http://client.example.com
You are doing the right and you can get the domain name as the second last value in the array.
var host = Request.Url.Host;
var domains = host.Split('.');
string subDomain = domains[0].Split('/')[2];
string mainDomain = domains[domains.Length-2];
return Tuple.Create(mainDomain, subDomain);
If you want all the subdomains you can put a loop here.
I've been trying to make this URL a workable string in C#, but unfortunately using extra "" or "#" is not cutting it. Even breaking it into smaller strings is proving difficult. I want to be able to convert the entire address into a single string.
this is the full address:
<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT="+URLEncode(""+[Material].[Material - Key])+"&lsIZV_MAT=>
I've also tried this:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"+ URLEncode("" +[Material].[Material - Key]) + """"";
string url3 = #"&lsIZV_MAT=";
Any help is appreciated.
The simplest solution is put additional quotes inside string literal and use string.Concat to join all of them into single URL string:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
string resultUrl = string.Concat(url, url2, url3);
NB: You can use Equals method or == operator to check if the generated string matches with desired URL string.
This may be a bit of a workaround rather than an actual solution but if you load the string from a text file and run to a breakpoint after it you should be able to find the way the characters are store or just run it from that.
You may also have the issue of some of the spaces you've added being left over which StringName.Replace could solve if that's causing issues.
I'd recommend first checking what exactly is being produced after the third statement and then let us know so we can try and see the difference between the result and original.
You are missing the triple quotes at the beginning of url2
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
I just made two updates
t&lsMZV_MAT=" to t&lsMZV_MAT="" AND
[Material - Key])+" to [Material - Key])+""
string s = #"<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=""+ URLEncode([Material].[Material - Key])+""&lsIZV_MAT=>";
Console.Write(s);
Console.ReadKey();
I have the following code but it's not quite working... Any ideas where i'm going wrong? It seems to be failing when there is a carriage return in the string? (see fiddles at bottom)
[RegularExpression(#"^((?!([\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*#((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3})))).)*$", ErrorMessage = "Please do not include an email address in your description.")]
Context
People are writing descriptions and also placing email addresses in them, for example:
"Hi there i'm bob, here is my email: example#exampele.com. Hope you
havea great day at my party."
I need to check that string and see that there is an email, and then not allow it to be submitted. (I'm using Entity framework and data annotations alongside the jquery validation in ASP .NET MVC 5... This is why i mentioned Data annotation usage.
Note:
I took the inversion technique from here:
Jquery validation on matching 'password' and 'admin' not working
And the email validation from here:
Best Regular Expression for Email Validation in C#
Attempts:
The following string:
http://pastebin.com/00BE7tUW
will show the error, whereas this will not:
http://pastebin.com/i69uxzRf
So something is a little wrong in the expression considering there is no email in it?
Fiddle:
Not working: https://regex101.com/r/zL7xD7/1
Working: https://regex101.com/r/hJ8fJ9/1
Working with email: https://regex101.com/r/dB3cU2/1
Have you tried something like this:
bool invalid = false;
public bool IsValidEmail(string strIn)
{
invalid = false;
if (String.IsNullOrEmpty(strIn))
return false;
// Use IdnMapping class to convert Unicode domain names.
try {
strIn = Regex.Replace(strIn, #"(#)(.+)$", this.DomainMapper,
RegexOptions.None, TimeSpan.FromMilliseconds(200));
}
catch (RegexMatchTimeoutException) {
return false;
}
if (invalid)
return false;
// Return true if strIn is in valid e-mail format.
try {
return Regex.IsMatch(strIn,
#"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" +
#"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}
catch (RegexMatchTimeoutException) {
return false;
}
}
private string DomainMapper(Match match)
{
// IdnMapping class with default property values.
IdnMapping idn = new IdnMapping();
string domainName = match.Groups[2].Value;
try {
domainName = idn.GetAscii(domainName);
}
catch (ArgumentException) {
invalid = true;
}
return match.Groups[1].Value + domainName;
}
The IsValidEmail method returns true if the string contains a valid email address and false if it does not, but takes no other action.
To verify that the email address is valid, the IsValidEmail method calls the Regex.Replace(String, String, MatchEvaluator) method with the (#)(.+)$ regular expression pattern to separate the domain name from the email address. The third parameter is a MatchEvaluator delegate that represents the method that processes and replaces the matched text.
Then you would check the email address by doing something like:
IsValidEmail(emailAddress)
Does this work for you?
The . needed to be replaced by [\S\s]
[RegularExpression(#"^((?!([\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*#((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))))[\S\s])*$", ErrorMessage = "Please do not include an email address in your field description.")]
source: Regular expression is not matching new lines
I created an winforms application, which creates a small SQLite database for every user. The database name contains the e-mailaddress of the user.
Scenario:
a user with e-mailaddress: test#test.com
uses the application, the following database will be created:
test#test.com.sqlite
I know that there are scenario's that the e-mailaddress converted to a path, will not be converted to a valid path.
the following characters are reserved by path: / \ ? % * : | " < > . and a space
I'm currently using the next method to filter the e-mailaddress:
public string ReturnFilteredUsername(string username)
{
username = username.Replace("<", "x"); username = username.Replace(">", "x"); username = username.Replace(":", "x"); username = username.Replace("\"", "x");
username = username.Replace("/", "x"); username = username.Replace(#"\", "x"); username = username.Replace("|", "x"); username = username.Replace("?", "x");
username = username.Replace("*", "x");
return username;
}
All reserved characters get replaced by an "x" at the moment, I want to convert all invalid characters to "%20". It is possible for me to just replace the "x" with "%20", but I don't think that's a 'clean' method
Can somebody come up with a more 'clean' method?
Thanks in advance!
Rather than using the user's email to name the database, identify each user by a numeric ID, and use that to name the databases.
In addition to always being valid as a file name, this allows users to change their email address without you having to worry about still pointing to the correct database.
Alternately, if you're set on using email addresses for the names, see this answer about which characters are valid in an email address. As long as all of the email address are valid, you only need to worry about escaping those characters that are both valid for emails and invalid for path.
I'd suggest either using a valid-for-path and invalid-for-email character to start an escape sequence (different sequence for each character you'll have to escape), or selecting a less common character valid for both, and using that as an escape character (remembering to escape it as well!).
Example:
Both % and ? are listed as valid for emails and invalid for paths. Assuming we use & to escape (valid for both!), we would create a mapping like this:
"&" = &00;
"%" = &01;
"?" = &02;
You would go through each email address and replace each occurence of invalid characters with their escaped equivalent, making it both as unique as the email address and safe as a path anme.
"a&b?100%#example.com" would becomee "a&00;b&02;100&01;#example.com".
Needing a bit help getting multiple values from a string using Regex. I am fine getting single values from the string but not multiple.
I have this string:
[message:USERPIN]Message to send to the user
I need to extract both the USERPIN and the message. I know how to get the pin:
Match sendMessage = Regex.Match(message, "\\[message:[A-Z1-9]{5}\\]");
Just not sure how to get both of the values at the same time.
Thanks for any help.
Use Named Groups for easy access:
Match sendMessage = Regex.Match(message,
#"\[message:(?<userpin>[A-Z1-9]{5})\](?<message>.+)");
string pin = sendMessage.Groups["userpin"].Value;
string message = sendMessage.Groups["message"].Value;
var match = Regex.Match(message, #"\[message:([^\]]+)\](.*)");
After - inspect the match.Groups with debugger - there you have to see 2 strings that you expect.
You need to use numbered groups.
Match sendMessage = Regex.Match(message, "\\[message:([A-Z1-9]{5})(.*)\\]");
string firstMatch = sendMessage.Groups[1].Value;
string secondMatch = sendMessage.Groups[2].Value;