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();
Related
I have a list of user IP addresses like following:
user 1:
192.168.1.1
192.168.1.2
192.168.1.3
user 2:
192.168.1.1
192.168.1.2
192.168.1.3
172.0.0.1
172.0.0.5
174.5.5.15
Now what I'd like to do here is to filter out all the IP's that are obviously from the same subnet/coming from the same PC/City.
I'm only using local IP's as an example here.
After filtering I would be left with the following:
For user 1 it is enough for me to have only 1 IP from each subnet like following:
192.168.1.1 => all other IP's would be removed, only one would be left
from that specific subnet
For user 2:
192.168.1.1
172.0.0.1
174.5.5.15
For the user 2 I'm left with 3 IP's since 192.168.. and 172.0.. had multiple ip's from that range.
Now my idea is to use a criteria for the first two numbers of the IP to be compared. For example:
192.168.0.1
192.168.0.2
192.168.0.6
These 3 have same first two numbers (192.168), thus I can consider them as duplicates and they should be removed. Which ever 1 of the IP's is left here from these is irrelevant, what matters is is that only 1 is left.
This would result in 1 ip to be left, for example:
192.168.0.1 (again doesn't matter which one is left, just that 1 is left!)
Now onto the part with code. I have a class structure like following:
public class SortedUser
{
public string Email { get; set; }
public List<IpInfo> IPAndCountries = new List<IpInfo>();
}
And IPInfo class looks like this:
public class IpInfo
{
public string Ip { get; set; }
}
Can someone help me out with this now? How can I do it in most easiest way?
If you are looking for only the first two bytes in the list of addresses, you can run a string comparison like so (not tested):
SortedUser user = new SortedUser()
{
Email = "Foo#bar.com",
IPAndCountries = new List<IpInfo>()
{
new IpInfo() {Ip = "192.168.0.1"},
new IpInfo() {Ip = "192.168.1.2"},
new IpInfo() {Ip = "193.168.3.2"},
new IpInfo() {Ip = "8.2.4.5"}
}
};
// Using ToArray to avoid collection modified errors
foreach (IpInfo item in user.IPAndCountries.ToArray())
{
string[] ipSplit = item.Ip.Split('.');
string prefix = $"{ipSplit[0]}.{ipSplit[1]}";
user.IPAndCountries.RemoveAll(info => info.Ip.StartsWith(prefix) && info.Ip != item.Ip);
}
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..
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.
Oki, so im working on outlook .msg templates.
Opening them programmatically, inserting values base on what's in my db.
ex. when i want to add multiple reciepients at "To" field, instead of doing as following,
mailitem.To = a + ";" + b + ";" + c;
i do whats below, which is simpler, especially when i'm doing it in a loop.
mailitem.Recipients.add("a");
mailitem.Recipients.add("b");
mailitem.Recipients.add("c");
My problem is, i also want to add multiple recipients at "CC" field and the function above only works for "To" field. How can i add multiple recipients to "CC" field without having to do string manipulation.
normally i would add recipients to cc like so,
mailitem.CC = a + ";" + b + ";" + c;
im using interop.outlook and creating an mailitem from template.
Thanks in advance.
Suppose If you have two List of recipients, then you can do like this.
Edit: Included full code.
var oApp = new Microsoft.Office.Interop.Outlook.Application();
var oMsg = (MailItem) oApp.CreateItem(OlItemType.olMailItem);
Recipients oRecips = oMsg.Recipients;
List<string> sTORecipsList = new List<string>();
List<string> sCCRecipsList = new List<string>();
sTORecipsList.Add("ToRecipient1");
sCCRecipsList.Add("CCRecipient1");
sCCRecipsList.Add("CCRecipient2");
sCCRecipsList.Add("CCRecipient3");
Recipients oRecips = oMsg.Recipients;
foreach (string t in sTORecipsList)
{
Recipient oTORecip = oRecips.Add(t);
oTORecip.Type = (int) OlMailRecipientType.olTo;
oTORecip.Resolve();
}
foreach (string t in sCCRecipsList)
{
Recipient oCCRecip = oRecips.Add(t);
oCCRecip.Type = (int) OlMailRecipientType.olCC;
oCCRecip.Resolve();
}
oMsg.HTMLBody = "Test Body";
oMsg.Subject = "Test Subject";
oMsg.Send();
Use the Recipients property as documented here (look for the second example). you can add a lot of people to the collection and then change the destination type from to to CC.
I have List that I want to display in my form. But first, I want to move all the non relevant part. This is my List:
===================================================================
Protocol Hierarchy Statistics
Filter:
eth frames:8753 bytes:6185473
ip frames:8753 bytes:6185473
tcp frames:8661 bytes:6166313
http frames:1230 bytes:792126
data-text-lines frames:114 bytes:82636
tcp.segments frames:56 bytes:41270
image-gif frames:174 bytes:109968
tcp.segments frames:57 bytes:37479
image-jfif frames:195 bytes:154407
tcp.segments frames:185 bytes:142340
png frames:35 bytes:30521
tcp.segments frames:20 bytes:15770
media frames:39 bytes:32514
tcp.segments frames:32 bytes:24755
tcp.segments frames:6 bytes:1801
xml frames:5 bytes:3061
tcp.segments frames:1 bytes:960
ssl frames:20 bytes:14610
udp frames:92 bytes:19160
dns frames:92 bytes:19160
===================================================================
I want to display the first column (protocol type) and in the second column only the part after "frames:" without bytes:xxxx
Probably using Regex, something along the lines of:
Regex rgx = new Regex(#"^(?<protocol>[ a-zA-Z0-9\-\.]*)frames:(?<frameCount>[0-9]).*$");
foreach (Match match in rgx.Matches(myListOfProtocolsAsAString))
{
if(match.Success)
{
string protocol = match.Groups[1].Value;
int byteCount = Int32.Parse(match.Groups[2].Value);
}
}
Then you can access the matching groups (protocol & framecount) on the Match instance.
Using the ever popular Linq to Objects
var lines = new string[]
{
"eth frames:8753 bytes:6185473",
"ip frames:8753 bytes:6185473"
};
var values = lines.Select(
line=>line.Split(new string[]{"frames:", "bytes:"}, StringSplitOptions.None))
.Select (items => new {Name=items[0].Trim(), Value=items[1].Trim()});