Monday, January 28, 2008

C# accessing to fields/object by string

string vStringUnFiltered = Class.GetType().GetField(method_in).GetValue(Class_instance).ToString();

Regex + C# parsing IP into segments a.b.c.d to a./a.b./a.b.c

One of intresting features at C# .NET is Regular Expressions which is very handy and save time (similiar to perl style). It's possible to assign values to search items. Small example is:
void main()
{
.....

SortedList VLans_LIST = new SortedList();
foreach (string CurrRegex in new string[] { "^(?\\d+)\\.", "^(?\\d+\\.\\d+)\\.", "^(?\\d+\\.\\d+\\.\\d+)\\." })
{

string VLanValidated = RegEX_Validate(CurrRegex , "vlan", ipAddress);
if (VLanValidated == null)
{ //do nothing }
else if (!VLans_LIST.Contains(VLanValidated))
{
VLans_LIST.Add(VLanValidated, VLanValidated);
}
}
}

string RegEX_Validate(string RegexString, string RegexValueParam,string StringToVal)
{
Regex objNaturalPattern = new Regex(RegexString);
if (objNaturalPattern.Match(StringToVal).Success )
{
Match VMatch = objNaturalPattern.Match(StringToVal);
return VMatch.Groups[RegexValueParam].Value;
}
else return null;
}