Sort email list by domain - c#

i wanna actuelly sort a list with email addresses by their domain.
Lets say for an example:
var list = new List<string>();
list.Add(a#hotmail.com);
list.Add(b#aon.at);
list.Add(c#gmail.com);
so the result should be:
b#aon.at
c#gmail.com
a#hotmail.com
is that possible without splitting the email addresses ?

Try this:
var sorted = list.OrderBy(x=>new MailAddress(x).Host).ToList();
it will sort your email addresses by mail host

You could use linq for this. However it is absolutely necessary that you split the email address:
list.OrderBy(email => email.Split('#')[1]).ToList();

You can use Regex to get domain of the emails:
var listSorted = list.OrderBy(email => Regex.Match(email, "#.*").Value)
.ToList();
because:
var temp = Regex.Match("a#hotmail.com", "#.*").Value;
tells: take everything after # sign (including # sign) so temp will be #hotmail.com in this case.

Related

How to update NSG rule in C# with multiple ip addresses

I have C# code to update the ip address for an NSG rule:
var nsg = azure.NetworkSecurityGroups.GetByResourceGroup("rg", "testnsg");
var nsgrule = nsg.SecurityRules["testrule"];
nsg.Update().UpdateRule("testrule").ToAddress(IpAddress1);
nsg.Update().UpdateRule("testrule").ToAddress(IpAddress2);
nsg.Update().Apply();
The second ip address overwrites the first one.
I have also tried this:
nsg.Update().UpdateRule("testrule").ToAddress(IpAddress1 + ',' + IpAddress2);
But that gives an error that only one ip address is allowed.
Is there a way in C# to specify multiple ip addresses for the nsg rule?
This works:
var nsg = azure.NetworkSecurityGroups.GetByResourceGroup("rg", "testnsg");
var nsgrule = nsg.SecurityRules["testrule"];
List<string> ips = new List<string>();
ips.Add(IpAddress1);
ips.Add(IpAddress2);
nsgrule.Inner.DestinationAddressPrefixes = ips;
nsg.Update().Apply();

validating multiple occurence of e-mails in string in most efficient way

I have string coming in this format as shown bellow:
"mark345345#test.com;rtereter#something.com;terst#gmail.com;fault#mail"
What would be the most efficient way to validate each of these above and fail if it is not valid e-mail?
you can use EmailAddressAttribute class of System.ComponentModel.DataAnnotations namespace for validating the email address. Before that you need to split up individual mails and check whether it is valid or not. the following code will help you to collect the valid mails and invalid mails seperately.
List<string> inputMails = "mark345345#test.com;rtereter#something.com;terst#gmail.com;fault#mail".Split(';').ToList();
List<string> validMails = new List<string>();
List<string> inValidMails = new List<string>();
var validator = new EmailAddressAttribute();
foreach (var mail in inputMails)
{
if (validator.IsValid(mail))
{
validMails.Add(mail);
}
else
{
inValidMails.Add(mail);
}
}
You can use Regex or you might split the string by ';' and try to create a System.Net.Mail.MailAddress instance for each and every address. FormatException will occur if address is not in a recognized format.
If you're sure, that all e-mails are semi colon separated, you can split it and make a list of all. The best way for me to validate each e-mail is to use a regex pattern. I've used this one:
var emailPattern = #"(?=^.{1,64}#)^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?=.{1,255}$|.{1,255};)(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])(;(?=.{1,64}#)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?=.{1,255}$|.{1,255};)(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9]))*$";
var incomingString = "mark345345#test.com;rtereter#something.com;terst#gmail.com;fault#mail";
var emails = incomingString.Split(';').ToList();
foreach (var email in emails)
{
if (new Regex(emailPattern).IsMatch(email))
{
// your logic here
}
}
Since .Net has out of the box ways to validate an email id, I would not use a regex and rely upon .Net. e.g the EmailAddressAttribute from System.ComponentModel.DataAnnotations.
A clean way to use it would be something like:
var emailAddressAttribute = new EmailAddressAttribute();
var groups = yourEmailsString.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.GroupBy(emailAddressAttribute.IsValid);
This will give you 2 groups, the one with the Key == true will be valid email ids
var validEmailIds = groups.Where(group => group.Key)
.SelectMany(group => group);
the one with Key == false will be invalid email ids
var invalidEmailIds = groups.Where(group => !group.Key)
.SelectMany(group => group);
You could also run up a for loop after grouping, according to your needs..

c# mongodb case sensitive search

I have a collection in which I store Email and password of user.
I obviously don't want to require the user to insert his email case sensitive and to be exactly as when he first registered.
I'm using mongodb 2.0 c# driver, I'm repeating it because I saw solutions to queries written with regex but I'm afraid I cant user it in here.
my query looks like
var filter = Builders<ME_User>.Filter.And(
Builders<ME_User>.Filter.Eq(u => u.Email, email),
Builders<ME_User>.Filter.Eq(u => u.Password, password));
ME_User foundUser = null;
var options = new FindOptions<ME_User>
{
Limit = 1
};
using (var cursor = await manager.User.FindAsync(filter, options))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (ME_User user in batch)
foundUser = user;
}
}
I have an issue with disorder, kill me, but I cant allow myself save this data again with lower case and have 2 copies of the same thing. Also, I want the email to be saved EXACTLY like the user inserted it.
Filtering on string fields in Mongodb is case sensitive without using regular expressions. Why exactly you cannot use regular expressions?
Your query can be edited like this:
var filter = Builders<ME_User>.Filter.And(
Builders<ME_User>.Filter.Regex(u => u.Email, new BsonRegularExpression("/^" + email + "$/i"),
Builders<ME_User>.Filter.Eq(u => u.Password, password));
Notice the "^" and "$" signs to specify a complete word search and most important the case-insensitive operator at the end of the regular expression ("/i").
Another way vould be the Text search, that requires the creation of a text index and is case insensitive for latin alphabet: http://docs.mongodb.org/manual/reference/operator/query/text/#match-operation
In C#, you will use with the Text Filter:
var filter = Builders<ME_User>.Filter.And(
Builders<ME_User>.Filter.Text(email),
Builders<ME_User>.Filter.Eq(u => u.Password, password));
With a text index query in an OR clause, you will need to create an index on Password field as well, otherwise the OR query will produce an error:
Other non-TEXT clauses under OR have to be indexed as well
I'd prefer using Linq.
var match = theCollection.AsQueryable().SingleOrDefault(x =>
x.Email.ToLower() == emailToSearchFor.ToLower());
For the c# driver 2.1 (MongoDB 3.0)
By default its case-sensitive.
To case-insensitive just add of "i" in BsonRegularExpression. please refer below
var filter = Builders<Users>.Filter.Regex(k=>k.Name, new BsonRegularExpression(name, "i"));
var users = await _mongoDbContext.Users.Find(filter).ToListAsync();

Find all string parts starting with [ and ends with ] in long string

I have an interesting problem for which I want to find a best solution I have tried my best with regex . What I want is to find all the col_x values from this string using C# using regular expression or any other method.
[col_5] is a central heating boiler manufacturer produce boilers under [col_6]
brand name . Your selected [col_7] model name is a [col_6] [col_15] boiler.
[col_6] [col_15] boiler [col_7] model [col_10] came in production untill
[col_11]. [col_6] model product index number is [col_1] given by SEDBUK
'Seasonal Efficiency of a Domestic Boiler in the UK'. [col_6] model have
qualifier [col_8] and GCN [col_9] 'Boiler Gas Council No'. [col_7] model
source of heat for a boiler combustion is a [col_12].
The output expected is an array
var data =["col_5","col_10","etc..."]
Edit
my attempt :
string text = "[col_1]cc[col_2]asdfsd[col_3]";
var matches = Regex.Matches(text, #"[[^#]*]");
var uniques = matches.Cast<Match>().Select(match => match.Value).ToList().Distinct();
foreach(string m in uniques)
{
Console.WriteLine(m);
}
but no success.
Try something like this:
string[] result = Regex.Matches(input, #"\[(col_\d+)\]").
Cast<Match>().
Select(x => x.Groups[1].Value).
ToArray();
I think that's what you need:
string pattern = #"\[(col_\d+)\]";
MatchCollection matches = Regex.Matches(input, pattern);
string[] results = matches.Cast<Match>().Select(x => x.Groups[1].Value).ToArray();
Replace input with your input string.
I hope it helps
This is a little hacky but you could do this.
var myMessage =#"[col_5] is a central heating boiler..."; //etc.
var values = Enumerable.Range(1, 100)
.Select(x => "[col_" + x + "]")
.Where(x => myMessage.Contains(x))
.ToList();
Assuming there is a known max col_"x" in this case I assumed 100, it just tries them all by brute force returning only the ones that it finds inside the text.
If you know that there are only so many columns to hunt for, I would try this instead of Regex personally as I have had too many bad experiences burning hours on Regex.

C# Linq String[] list minus from String[] list

Let's say
string[] admins = "aron, mike, bob";
string[] users = "mike, katie, sarah";
How can I take the users and strip out anyone from the admins.
the result should be "katie, sarah"; (mike was removed)
Is there a nice Linq way to do this?
// as you may know, this is the right method to declare arrays
string[] admins = {"aron", "mike", "bob"};
string[] users = {"mike", "katie", "sarah"};
// use "Except"
var exceptAdmins = users.Except( admins );
users.Except(admins);
See more set operations:
http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
The easiest would to be use IEnumerable<T>.Except:
var nonAdmins = users.Except(admins);

Categories