Tuple contains tow list in c# - c#

I want to create a function with c# who return for me a list of ip and port the function is like that:
public Tuple<string,int> loadSocks()
{
var listip = new List<string>();
var listprt = new List<int>();
var input = Path.GetFullPath(Path.Combine(Application.StartupPath, "Exploit1/socks-list.txt"));
var r = new Regex(#"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})");
foreach (Match match in r.Matches(input))
{
string ip = match.Groups[1].Value;
int port = Convert.ToInt32(match.Groups[2].Value);
listip.Add(ip);
listprt.Add(port);
Tuple<List<string>, List<int>> tplLst = new Tuple<List<string>, List<int>>(listip, listprt);
Tuple<string, int> tplSum = Add(tplLst);
}
return tplLst;
}
I use tuple , I add tow list in this tuple but he give me the error in Tuple tplSum = Add(tplLst); in Add(tplLst).
What I should do ?

I recommend to simplfy your code. Instead of using a tuple which often decrease readability I would create a type for your purpose.
public class BiningInfo
{
public IPAddress IpAddress { get; set;}
public int Port { get; set;}
}
public List<BiningInfo> loadSocks()
{
var result = new List<BiningInfo>();
var input = Path.GetFullPath(Path.Combine(Application.StartupPath, "Exploit1/socks-list.txt"));
var r = new Regex(#"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})");
foreach (Match match in r.Matches(input))
{
string ip = match.Groups[1].Value;
int port = Convert.ToInt32(match.Groups[2].Value);
BiningInfo bi = new BiningInfo();
bi.IpAddress = IPAddress.Parse(ip);
bi.Port = port;
}
return result;
}

I believe you are trying to return a list of tuples. Change the signature of your function to return a list. Initialize a variable to hold the result. Then add each ip/port combination to it. Finally return the result.
public List<Tuple<string,int>> loadSocks()
{
var result = new List<Tuple<string, int>>();
var input = Path.GetFullPath(Path.Combine(Application.StartupPath, "Exploit1/socks-list.txt"));
var r = new Regex(#"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})");
foreach (Match match in r.Matches(input))
{
string ip = match.Groups[1].Value;
int port = Convert.ToInt32(match.Groups[2].Value);
result.Add(new Tuple<string,int>(ip, port));
}
return result;
}

I hope I've got your point. I think the following code is what you're looking for :
public List<Tuple<string, int>> loadSocks()
{
List<Tuple<string, int>> result = new List<Tuple<string, int>>();
var input = Path.GetFullPath(Path.Combine(Application.StartupPath, "Exploit1/socks-list.txt"));
var r = new Regex(#"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})");
foreach (Match match in r.Matches(input))
{
string ip = match.Groups[1].Value;
int port = Convert.ToInt32(match.Groups[2].Value);
result.Add(new Tuple<string,int>(ip,port));
}
return result;
}

Related

Delete duplicate elements from list by Identifier string (C#)

I have method to add elements to list
Here is code
public static List<InputDevice> GetAudioInputDevices()
{
var inputs = new List<InputDevice>();
var enumerator = new MMDeviceEnumerator();
var devicesAudio = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
foreach (var device in devicesAudio)
{
inputs.Add(new InputDevice()
{
Name = device.FriendlyName,
Status = device.State.ToString(),
DeviceId = device.ID,
Identifier = device.FriendlyName.Replace(" ", "").ToUpper()
});
}
return inputs;
}
But sometimes I can have duplicates in Identifier
How I can return list without duplicates on return?
There's a few ways to accomplish this, you could just skip the Adding of the item if it's already in the list:
foreach (var device in devicesAudio)
{
string identifier = device.FriendlyName.Replace(" ", "").ToUpper();
if (inputs.Any(input => input.Identifier == identifier))
continue;
inputs.Add(new InputDevice()
{
Name = device.FriendlyName,
Status = device.State.ToString(),
DeviceId = device.ID,
Identifier = identifier
});
}
Or you could group the list by the identifier after the foreach, something like this:
inputs = inputs.GroupBy(i => i.Identifier)
.Select(i => new InputDevice()
{
Identifier = i.Key,
Status = i.First().Status,
DeviceId = i.First().DeviceId,
Name = i.First().Name
}).ToList();
It really depends on what you need to do with the duplicated ones.
Hope it helps!
To make it faster you can use HashSet (complexity of Contains for HashSet is o(1)) and ask on each loop whether there already is a specific identifier in inputs List.
public static List<InputDevice> GetAudioInputDevices()
{
var inputs = new List<InputDevice>();
var enumerator = new MMDeviceEnumerator();
var devicesAudio = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
var usedIdentifiers = new HashSet<string>();
foreach (var device in devicesAudio)
{
var identifier = device.FriendlyName.Replace(" ", "").ToUpper();
if (usedIdentifiers.Contains(identifier))
continue;
inputs.Add(new InputDevice()
{
Name = device.FriendlyName,
Status = device.State.ToString(),
DeviceId = device.ID,
Identifier = identifier
});
usedIdentifiers.Add(identifier);
}
return inputs;
}
The best way, I thing is this
public static List<InputDevice> GetAudioInputDevices()
{
var inputs = new List<InputDevice>();
var enumerator = new MMDeviceEnumerator();
var devicesAudio = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.All);
inputs = devicesAudio.GroupBy(d => d.FriendlyName.Replace(" ", "").ToUpper()).Select(g => g.First())
.Select(d => new InputDevice()
{
Name = d.FriendlyName,
Status = d.State.ToString(),
DeviceId = d.ID,
Identifier = d.FriendlyName.Replace(" ", "").ToUpper()
}).ToList();
return inputs;
}
Check in website information about HashSet.

Inserting data to .CSV file at the same time using foreach

I am new here and actually very new to c#.
In a nutshell, I am using c# via Visual Studio, I am calling a data from a database and I want to save these data in a .csv file. The problem now is that I want to save these data on two columns at the same time.
My code do write them in a file but shifted not on the right rows.
Dictionary<string, string> elementNames = new Dictionary<string, string>();
Dictionary<string, string> elementTypes = new Dictionary<string, string>();
var nodes = webservice.nepService.GetAllElementsOfElementType(webservice.ext, "Busbar", ref elementNames, ref elementTypes);
Dictionary<string, string> nodeResults = new Dictionary<string, string>();
Dictionary<string, string> nodeResults1 = new Dictionary<string, string>();
foreach (var nodename in elementNames.Values)
{
var nodeRes = webservice.nepService.GetResultElementByName(webservice.ext, nodename, "Busbar", -1, "LoadFlow", null);
var Uvolt = GetXMLAttribute(nodeRes, "U");
nodeResults.Add(nodename, Uvolt);
var Upercentage = GetXMLAttribute(nodeRes, "Up");
nodeResults1.Add(nodename, Upercentage);
StringBuilder strBldr = new StringBuilder();
string outputFile = #"C:\Users\12.csv";
string separator = ",";
foreach (var res in nodeResults)
{
strBldr.AppendLine($"{res.Key}{separator}{res.Value}");
}
foreach (var res1 in nodeResults1)
{
strBldr.AppendLine($"{separator}{separator}{res1.Value}");
}
File.WriteAllText(outputFile, strBldr.ToString());
}
this is the output of the previous code:
https://ibb.co/T4trQC3
I want these shifted values to move up beside the other values like that:
https://ibb.co/4S25v0h
Thank you
if you look to the code you are using AppendLine
strBldr.AppendLine($"{separator}{separator}{res1.Value}");
and if you want to append on same line just use Append
strBldr.Append($"{separator}{separator}{res1.Value}");
EDITED:
in linq you can use Zip function to zip to lists
// using System.Linq;
var results = Results.Zip(Results1, (firstList, secondList) => firstList.Key + "," + firstList.Value + "," + secondList.Value);
Edit Full example
public static IDictionary<string, string> Results { get; set; }
public static IDictionary<string, string> Results1 { get; set; }
private static void Main(string[] args)
{
StringBuilder strBldr = new StringBuilder();
string outputFile = #"D:\12.csv";
Results = new Dictionary<string, string>()
{
{"N1", "20"},
{"N2", "0.399992"},
{"N3", "0.369442"},
{"N4", "0.369976"}
};
Results1 = new Dictionary<string, string>()
{
{"N1", "100"},
{"N2", "99.9805"},
{"N3", "92.36053"},
{"N4", "92.49407"}
};
IEnumerable<string> results = Results.Zip(Results1,
(firstList, secondList) => firstList.Key + "," + firstList.Value + "," + secondList.Value);
foreach (string res1 in results)
{
strBldr.AppendLine(res1);
}
File.WriteAllText(outputFile, strBldr.ToString());
}
for faster code you can try this
HashSet<Tuple<string, string, string>> values = new HashSet<Tuple<string, string, string>>();
var nodes = webservice.nepService.GetAllElementsOfElementType(webservice.ext, "Busbar", ref elementNames, ref elementTypes);
foreach (var nodename in elementNames.Values)
{
var nodeRes = webservice.nepService.GetResultElementByName(webservice.ext, nodename, "Busbar", -1, "LoadFlow", null);
var Uvolt = GetXMLAttribute(nodeRes, "U");
var Upercentage = GetXMLAttribute(nodeRes, "Up");
values.Add(Tuple.Create(nodename, Uvolt, Upercentage));
}
var output = string.Join("\n", values.ToList().Select(tuple => $"{tuple.Item1},{tuple.Item2},{tuple.Item3}").ToList());
string outputFile = #"C:\Users\12.csv";
File.WriteAllText(outputFile, output);
if the rowCount for Results and Results1 are same and the keys are in the same order, try:
for (int i = 0; i < Results.Count; i++)
strBldr.AppendLine($"{Results[i].Key}{separator}{Results[i].Value}{separator}{Results1[i].Value}");
Or, if the rows are not in the same order, try:
foreach (var res in Results)
strBldr.AppendLine($"{res.Key}{separator}{res.Value}{separator}{Results1.Single(x => x.Key == res.Key).Value}");

Need help comparing extracted data and outputting to file

New to C#, and having trouble finding ways to compare data so far collected from conf file, and outputting it to either text or CSV.
I so far have the skeleton of data extraction code from said conf file, however as I'm new to C# and coding overall, I'm having trouble understanding how to reference that data or compare it.
So far have tried File.WriteAllLiness and defining a variable, but not sure which element to parse, or at which point in the code I should introduce it.
Nothing to hide really, so here's the full output so far:
namespace CompareVal
{
class Program
{
static void Main(string[] args)
{
var lines = File.ReadAllLines(#"D:\*\*\Cleanup\Script Project\Test-Raw-Conf.txt");
var ipAddresses = GetIPAddresses(lines);
var routes = GetRoutes(lines);
var ipRules = GetIPRules(lines);
Console.WriteLine ();
}
static Dictionary<string, string[]> GetIPAddresses(string[] lines)
{
var result = new Dictionary<string, string[]>();
foreach (var line in lines)
{
if (!line.StartsWith("add IPAddress"))
{
continue;
}
Match match;
if (line.Contains("Address=\""))
{
match = Regex.Match(line, "add IPAddress (.*?) Address=\"(.*?)\"");
}
else
{
match = Regex.Match(line, "add IPAddress (.*?) Address=(.*?)$");
}
var name = match.Groups[1].Value;
var value = match.Groups[2].Value;
var items = value.Replace(" ", "").Split(',');
result.Add(name, items);
}
return result;
}
static List<Route> GetRoutes(string[] lines)
{
var result = new List<Route>();
string currentRoutingTable = null;
foreach (var line in lines)
{
if (line.StartsWith("cc RoutingTable"))
{
currentRoutingTable = line.Split(' ')[2].Trim();
}
if (line == "cc .." && currentRoutingTable != null)
{
currentRoutingTable = null;
}
if (line.StartsWith(" add Route"))
{
var #interface = Regex.Match(line, "Interface=(.*?) ").Groups[1].Value;
var gateway = Regex.Match(line, "Gateway=(.*?) ").Groups[1].Value;
var network = Regex.Match(line, "Network=(.*?) ").Groups[1].Value;
result.Add(new Route
{
RoutingTable = currentRoutingTable,
Interface = #interface,
Gateway = gateway,
Network = network
});
}
}
return result;
}
static List<IPRule> GetIPRules(string[] lines)
{
var result = new List<IPRule>();
string currentIPRuleSet = null;
foreach (var line in lines)
{
if (line.StartsWith("cc IPRuleSet"))
{
currentIPRuleSet = line.Split(' ')[2].Trim();
}
if (line == "cc .." && currentIPRuleSet != null)
{
currentIPRuleSet = null;
}
if (line.StartsWith(" add IPRule"))
{
var rule = new IPRule
{
IPRuleSet = currentIPRuleSet,
SourceInterface = GetProperty(line, "SourceInterface"),
DestinationInterface = GetProperty(line, "DestinationInterface"),
};
if (line.Contains("SourceNetwork=\""))
{
rule.SourceNetwork = GetQuotedProperty(line, "SourceNetwork").Replace(" ", "").Split(',');
}
else
{
rule.SourceNetwork = GetProperty(line, "SourceNetwork").Replace(" ", "").Split(',');
}
if (line.Contains("DestinationNetwork=\""))
{
rule.DestinationNetwork = GetQuotedProperty(line, "DestinationNetwork").Replace(" ", "").Split(',');
}
else
{
rule.DestinationNetwork = GetProperty(line, "DestinationNetwork").Replace(" ", "").Split(',');
}
result.Add(rule);
}
}
return result;
}
static string GetProperty(string input, string propertyName)
{
return Regex.Match(input, string.Format("{0}=(.*?) ", propertyName)).Groups[1].Value;
}
static string GetQuotedProperty(string input, string propertyName)
{
return Regex.Match(input, string.Format("{0}=\"(.*?)\" ", propertyName)).Groups[1].Value;
}
class Route
{
public string RoutingTable;
public string Interface;
public string Gateway;
public string Network;
}
class IPRule
{
public string IPRuleSet;
public string SourceInterface;
public string DestinationInterface;
public string[] SourceNetwork;
public string[] DestinationNetwork;
}
}
}
I'm hoping to compare values gathered by IPRule, Route and IPAddress classes, and have a method of outputting each associated value in a list. Each IPAddress is contains a unique string name, but can use any numerical IP address. The idea is to determine when the same IP has been used multiple times, regardless of IPAddress string name, and then compare this to routes, and flag when they are used in IPRules.
For reference, here are some samples of source data:
For IPAddresses, they can be formed in 1 of 2 ways - as a direct IP definition, or as a reference to another IPAddress object (or multi-reference):
add IPAddress Test Address=192.168.1.0/24
IPAddress referencing multiple other IPAddresses:
add IPAddress TestGroup Address="Test1, Test2, Test3"
For routes:
add Route Interface=if5 Gateway=if5_gw Network=Test ProxyARPInterfaces=""
And for IPRules:
add IPRule SourceInterface=if5 DestinationInterface=if3 SourceNetwork=Test1 DestinationNetwork=Test2 Service=dns-all Action=Allow
The above definitions will always follow the same pattern, so the data extraction code has been constructed to expect prefixes to each element, and sort them into their own dictionary or list.

How to write search query using OR instead of And

I need to write search based on following criteria:
I need to find all records that match values of
key1 OR key2 OR key 3 values...etc
The number of keys and values is variable
List<KeyValuePair<string, string[]>> filterlist = new List<KeyValuePair<string, string[]>>()
{
new KeyValuePair<string, string[]>("Key1", new []{"jay","bloggs"}),
new KeyValuePair<string, string[]>("Key2", new []{"joe","blog","doe"}),
new KeyValuePair<string, string[]>("Key3", new []{"jon","blog"}),
};
Now my implementation
My current implementation does search but all expressions are "AND" instead of OR. I am not sure how to write it.
public class UserSearcher
{
private List<UserProfile> userProfiles;
public UserSearcher()
{
userProfiles = new List<UserProfile>();
}
public static List<UserProfile> SearchProfiles(List<KeyValuePair<string, string[]>> filterList)
{
var list = new List<UserProfile>();
var query = list.AsQueryable();
// search for each pair inside as or
foreach (KeyValuePair<string, string[]> searchPair in filterList)
{
foreach (string searchString in searchPair.Value)
{
string s = searchString;
// search for each item inside as and (has to contains all search strings
query = query.Where(x => x.PersonName.Contains(s));
}
}
return list = query.ToList();
}
}
The full example except db is:
https://gist.github.com/cpoDesign/acf69bc242ed0755597d
Use Predicate Builder - it works well.
So, if I got it right, you want to get back list of UserProfile where PersonName is inside any string[] of KeyValuePair list.
If so, try with this:
public static List<UserProfile> SearchProfiles(List<KeyValuePair<string, string[]>> filterList)
{
var list = new List<UserProfile>();
return list.Where(profile => filterList.Any(kvp => kvp.Value.Contains(profile.PersonName))).ToList();
}
Test example:
public static Expression<Func<T,bool>>
Or<T>(IEnumerable<Expression<Func<T,bool>>> expList){
ParameterExpression pe = Expression.Parameter(typeof(T));
Expression r = null;
foreach(var exp in expList){
r = r == null ? exp : Expression.Or(r,exp);
}
return Expression.Lambda<Func<T,bool>>(r.Body,pe);
}
var orList = new List<Expression<Func<T,bool>>>();
foreach (KeyValuePair<string, string[]> searchPair in filterList)
{
foreach (string searchString in searchPair.Value)
{
string s = searchString;
// search for each item inside as and
// (has to contains all search strings
orList.Add(x => x.PersonName.Contains(s));
}
}
query = query.Where( Or(expList));

Alternate foreach output

I have this code which grabs the specified text from a webpage:
static void Main(string[] args)
{
using (var client = new WebClient())
{
var pageContent = client.DownloadString("http://www.modern-railways.com");
var regexTitle = new Regex(#"<span class='articleTitle'>(.+?)</span>");
var regexDate = new Regex(#"class='summaryText' data-ajax='false'>(.+?)</a></p><div");
foreach (Match title in regexTitle.Matches(pageContent))
{
var articleTitle = title.Groups[1].Value;
Console.WriteLine(articleTitle);
}
foreach (Match date in regexDate.Matches(pageContent))
{
var articleDate = date.Groups[1].Value;
Console.WriteLine(articleDate);
}
Console.ReadLine();
}
}
As it is now it prints all the articleTitle first and then all the articleDate. How can I get out 1st line ArticleTitle, second line articleDate and so on?
You can use LINQ and Zip method:
var titles = regexTitles.Matches(pageContent).Cast<Match>();
var dates = regexDate.Matches(pageContent).Cast<Match>();
var source = titles.Zip(dates, (t, d) => new { Title = t, Date = d })
foreach (var item in source)
{
var articleTitle = item.Title.Groups[1].Value;
var articleDate = item.Date.Groups[1].Value;
Console.WriteLine(articleTitle);
Console.WriteLine(articleDate);
}

Categories