How to suggest new computer domain name - c#

I'm trying to write a program that search our domain by entered name of groups of computers (for example for IT users computer name beginns with DITXX, where XX is number of computer) and suggest new computer name. For example we have computers:
DIT01
DIT02
..
DIT10
DIT11
..
DIT156
I have TextBox where i enter group name, then i get a list of computers containing this name and i'm putting them to List and to Array. But how to get last used name and suggest new (here program should suggest name DIT157 beacuse of last name DIT156)? Should i use natural sort? Or trim name DIT to have only numbers, sort them and then just find last, add 1 and then show trimmed name + this number?
Code fragments:
string name = textBox1.Text;
DirectoryEntry domain = new DirectoryEntry("LDAP://*****.****.**.**");
DirectorySearcher search = new DirectorySearcher(domain);
search.Filter = ("(&(ObjectCategory=computer)(cn=") + name + ("*))");
List<string> temp = new List<string>();
richTextBox1.Text = "";
List<string> ComputerList = new List<string>();
foreach (SearchResult c in search.FindAll())
{
var tmp = (c.GetDirectoryEntry().Name.ToString());
richTextBox1.Text = richTextBox1.Text + (tmp.Replace("CN=", "")) + (Environment.NewLine);
//listView1.Items.Add(tmp.Replace("CN=", ""),2);
temp.Add (tmp.Replace("CN=", ""));
ComputerList.Add(tmp.Replace("CN=", ""));
}
ComputerList.Sort((x, y) =>
{
int ix, iy;
return int.TryParse(x, out ix) && int.TryParse(y, out iy)
? ix.CompareTo(iy) : string.Compare(x, y);
});
string[] Computers = ComputerList.ToArray();
Array.Sort(Computers);
foreach (var item in Computers)
{
listView1.Items.Add(item);
Console.WriteLine(item.ToString());
}

For random computer name generation I personally would try something other than query/sort, like use Random. Or perhaps append the result of Path.GetRandomFileName() to your prefix (strip out the '.') and limit the total length to 15.
If you choose to do the query and sort I would strip off the text and sort by the number alone, because your example computer names have different lengths. Sorting by string would cause DIT11 and DIT110 to be next to each other in the list. And if you write a sorting algorithm you will end up stripping off the text anyway.

Related

How to prewrite header before list all data in text file with c#

I have example data like this
FamilyID;name;gender;DOB;Place of birth;status
1;nicky;male;01-01-1998;greenland;married
1;sonia;female;02-02-1995;greenland;married
2;dicky;male;04-01-1995;bali;single
3;redding;male;01-05-1996;USA;single
3;sisca;female;05-03-1994;australia;married
i must separate all data by familyID
i already success to separate the data by family ID
so the result is
File 1:
1;nicky;male;01-01-1998;greenland;married
1;sonia;female;02-02-1995;greenland;married
File 2:
2;dicky;male;04-01-1995;bali;single
File 3:
3;redding;male;01-05-1996;USA;single
3;sisca;female;05-03-1994;australia;married
The problem is , the header is missing, for each file , i expect it to be like
Example for file 1 :
FamilyID;name;gender;DOB;Place of birth;status
1;nicky;male;01-01-1998;greenland;married
1;sonia;female;02-02-1995;greenland;married
etc.
This is the code i write
DateTime date = DateTime.Now;
string tgl = date.Date.ToString("dd");
string bln = date.Month.ToString("d2");
string thn = date.Year.ToString();
string tglskrg = thn + "/" + bln + "/" + tgl;
string filename = ("C:\\Users\\Documents\\My Received Files\\exampledata.txt");
string[] liness = File.ReadAllLines(filename);
string[] col;
var lines = File.ReadAllLines(filename);
// group by first value
var groups = lines.Skip(1)
.Select(x => x.Split(';'))
.GroupBy(x => x[0]).ToArray();
// iterate groups write the joined lines back to a new file with the key name
foreach (var group in groups)
{
Console.WriteLine(group);
File.WriteAllLines(#"C:\\Users\\Documents\\My Received Files\\exampledata_"+group.Key+".txt", group.Select(x => string.Join(";", x)));
}
...//line of code to zip file(already done too)
Maybe there is something i wrong or miss ?
thanks for the help
And i make it in visual express c# 2010, console application

Check whether a string is in a list at any order in C#

If We have a list of strings like the following code:
List<string> XAll = new List<string>();
XAll.Add("#10#20");
XAll.Add("#20#30#40");
string S = "#30#20";//<- this is same as #20#30 also same as "#20#30#40" means S is exist in that list
//check un-ordered string S= #30#20
// if it is contained at any order like #30#20 or even #20#30 ..... then return true :it is exist
if (XAll.Contains(S))
{
Console.WriteLine("Your String is exist");
}
I would prefer to use Linq to check that S in this regard is exist, no matter how the order is in the list, but it contains both (#30) and (#20) [at least] together in that list XAll.
I am using
var c = item2.Intersect(item1);
if (c.Count() == item1.Length)
{
return true;
}
You should represent your data in a more meaningful way. Don't rely on strings.
For example I would suggest creating a type to represent a set of these numbers and write some code to populate it.
But there are already set types such as HashSet which is possibly a good match with built in functions for testing for sub sets.
This should get you started:
var input = "#20#30#40";
var hashSetOfNumbers = new HashSet<int>(input
.Split(new []{'#'}, StringSplitOptions.RemoveEmptyEntries)
.Select(s=>int.Parse(s)));
This works for me:
Func<string, string[]> split =
x => x.Split(new [] { '#' }, StringSplitOptions.RemoveEmptyEntries);
if (XAll.Any(x => split(x).Intersect(split(S)).Count() == split(S).Count()))
{
Console.WriteLine("Your String is exist");
}
Now, depending on you you want to handle duplicates, this might even be a better solution:
Func<string, HashSet<string>> split =
x => new HashSet<string>(x.Split(
new [] { '#' },
StringSplitOptions.RemoveEmptyEntries));
if (XAll.Any(x => split(S).IsSubsetOf(split(x))))
{
Console.WriteLine("Your String is exist");
}
This second approach uses pure set theory so it strips duplicates.

Can I select individual Items from a list?

I have a list of strings and I need to select certain parts of the list to construct a separate string. What I have is:
name,gender,haircolour,car;
or
John,Male,Brown,toyota;
I also have a separate file indicating which parts, and in what order the new string should be constructed.
eg: Index = 0,3,1 would print John,toyota,Male or 1,2,0 would print Male,Brown,John.
I have tried several methods to try and select the index of the items I want, but all the functions that return values only return the contents of the List, and the only return that gives an integer is Count(), which I can't see as being helpful.
I have tried and tried but all I have succeeded in doing is confusing myself more and more. Can anyone help suggest a way to achieve this?
You should be able to do list[i], where i is the index of the element you need. There are some examples here: http://www.dotnetperls.com/list
List<string> list = new List<string> { "John", "Male", "Brown", "toyota" };
List<int> indexList = new List<int> { 0, 3, 1 };
List<string> resultList = new List<string>();
indexList.ForEach(i => resultList.Add(list[i]));
If I am understanding the question correctly, something like this should do the job:
const string data = "John,Male,Brown,toyota";
const string order = "0,3,1";
string[] indexes = order.Split(',');
string result = indexes.Aggregate("", (current, index) => current + data.Split(',')[int.Parse(index)] + ",");
result = result.TrimEnd(',');
If your string data ends with a semicolon ';', as possibly indicated in your question, then change the line to this:
string result = indexes.Aggregate("", (current, index) => current + data.Split(',')[int.Parse(index)].TrimEnd(';') + ",");
Note this solution doesn't check to make sure that the given index exists in the given data string. To add a check to make sure the index doesn't go over the array bounds, do something like this instead:
string result = indexes.Where(z => int.Parse(z) < data.Split(',').Length).Aggregate("", (current, index) => current + data.Split(',')[int.Parse(index)].TrimEnd(';') + ",");

Speedily Read and Parse Data

As of now, I am using this code to open a file and read it into a list and parse that list into a string[]:
string CP4DataBase =
"C:\\Program\\Line Balancer\\FUJI DB\\KTS\\KTS - CP4 - Part Data Base.txt";
CP4DataBaseRTB.LoadFile(CP4DataBase, RichTextBoxStreamType.PlainText);
string[] splitCP4DataBaseLines = CP4DataBaseRTB.Text.Split('\n');
List<string> tempCP4List = new List<string>();
string[] line1CP4Components;
foreach (var line in splitCP4DataBaseLines)
tempCP4List.Add(line + Environment.NewLine);
string concattedUnitPart = "";
foreach (var line in tempCP4List)
{
concattedUnitPart = concattedUnitPart + line;
line1CP4PartLines++;
}
line1CP4Components = new Regex("\"UNIT\",\"PARTS\"", RegexOptions.Multiline)
.Split(concattedUnitPart)
.Where(c => !string.IsNullOrEmpty(c)).ToArray();
I am wondering if there is a quicker way to do this. This is just one of the files I am opening, so this is repeated a minimum of 5 times to open and properly load the lists.
The minimum file size being imported right now is 257 KB. The largest file is 1,803 KB. These files will only get larger as time goes on as they are being used to simulate a database and the user will continually add to them.
So my question is, is there a quicker way to do all of the above code?
EDIT:
***CP4***
"UNIT","PARTS"
"BLOCK","HEADER-"
"NAME","106536"
"REVISION","0000"
"DATE","11/09/03"
"TIME","11:10:11"
"PMABAR",""
"COMMENT",""
"PTPNAME","R160805"
"CMPNAME","R160805"
"BLOCK","PRTIDDT-"
"PMAPP",1
"PMADC",0
"ComponentQty",180
"BLOCK","PRTFORM-"
"PTPSZBX",1.60
"PTPSZBY",0.80
"PTPMNH",0.25
"NeedGlue",0
"BLOCK","TOLEINF-"
"PTPTLBX",0.50
"PTPTLBY",0.40
"PTPTLCL",10
"PTPTLPX",0.30
"PTPTLPY",0.30
"PTPTLPQ",30
"BLOCK","ELDT+" "PGDELSN","PGDELX","PGDELY","PGDELPP","PGDELQ","PGDELP","PGDELW","PGDELL","PGDELWT","PGDELLT","PGDELCT","PGDELR"
0,0.000,0.000,0,0,0.000,0.000,0.000,0.000,0.000,0.000,0
"BLOCK","VISION-"
"PTPVIPL",0
"PTPVILCA",0
"PTPVILB",0
"PTPVICVT",10
"PENVILIT",0
"BLOCK","ENVDT"
"ELEMENT","CP43ENVDT-"
"PENNMI",1.0
"PENNMA",1.0
"PENNZN",""
"PENNZT",1.0
"PENBLM",12
"PENCRTS",0
"PENSPD1",100
"PTPCRDCT",0
"PENVICT",1
"PCCCRFT",1
"BLOCK","CARRING-"
"PTPCRAPO",0
"PTPCRPCK",0
"PTPCRPUX",0.00
"PTPCRPUY",0.00
"PTPCRRCV",0
"BLOCK","PACKCLS-"
"FDRTYPE","Emboss"
"TAPEWIDTH","8mm"
"FEEDPITCH",4
"REELDIAMETER",0
"TAPEDEPTH",0.0
"DOADVVACUUM",0
"CHKBEFOREFEED",0
"TAPEARMLENGTH",0
"PPCFDPP",0
"PPCFDEC",4
"PPCMNPT",30
"UNIT","PARTS"
"BLOCK","HEADER-"
"NAME","106653"
"REVISION","0000"
"DATE","11/09/03"
"TIME","11:10:42"
"PMABAR",""
"COMMENT",""
"PTPNAME","0603R"
"CMPNAME","0603R"
"BLOCK","PRTIDDT-"
"PMAPP",1
"PMADC",0
"ComponentQty",18
"BLOCK","PRTFORM-"
"PTPSZBX",1.60
"PTPSZBY",0.80
"PTPMNH",0.23
"NeedGlue",0
"BLOCK","TOLEINF-"
"PTPTLBX",0.50
"PTPTLBY",0.34
"PTPTLCL",0
"PTPTLPX",0.60
"PTPTLPY",0.40
"PTPTLPQ",30
"BLOCK","ELDT+" "PGDELSN","PGDELX","PGDELY","PGDELPP","PGDELQ","PGDELP","PGDELW","PGDELL","PGDELWT","PGDELLT","PGDELCT","PGDELR"
0,0.000,0.000,0,0,0.000,0.000,0.000,0.000,0.000,0.000,0
"BLOCK","VISION-"
"PTPVIPL",0
"PTPVILCA",0
"PTPVILB",0
"PTPVICVT",10
"PENVILIT",0
"BLOCK","ENVDT"
"ELEMENT","CP43ENVDT-"
"PENNMI",1.0
"PENNMA",1.0
"PENNZN",""
"PENNZT",1.0
"PENBLM",12
"PENCRTS",0
"PENSPD1",80
"PTPCRDCT",0
"PENVICT",1
"PCCCRFT",1
"BLOCK","CARRING-"
"PTPCRAPO",0
"PTPCRPCK",0
"PTPCRPUX",0.00
"PTPCRPUY",0.00
"PTPCRRCV",0
"BLOCK","PACKCLS-"
"FDRTYPE","Emboss"
"TAPEWIDTH","8mm"
"FEEDPITCH",4
"REELDIAMETER",0
"TAPEDEPTH",0.0
"DOADVVACUUM",0
"CHKBEFOREFEED",0
"TAPEARMLENGTH",0
"PPCFDPP",0
"PPCFDEC",4
"PPCMNPT",30
... the file goes on and on and on.. and will only get larger.
The REGEX is placing each "UNIT PARTS" and the following code until the NEXT "UNIT PARTS" into a string[].
After this, I am checking each string[] to see if the "NAME" section exists in a different list. If it does exist, I am outputting that "UNIT PARTS" at the end of a textfile.
This bit is a potential performance killer:
string concattedUnitPart = "";
foreach (var line in tempCP4List)
{
concattedUnitPart = concattedUnitPart + line;
line1CP4PartLines++;
}
(See this article for why.) Use a StringBuilder for repeated concatenation:
// No need to use tempCP4List at all
StringBuilder builder = new StringBuilder();
foreach (var line in splitCP4DataBaseLines)
{
concattedUnitPart.AppendLine(line);
line1CP4PartLines++;
}
Or even just:
string concattedUnitPart = string.Join(Environment.NewLine,
splitCP4DataBaseLines);
Now the regex part may well also be slow - I'm not sure. It's not obvious what you're trying to achieve, whether you need regular expressions at all, or whether you really need to do the whole thing in one go. Can you definitely not just process it line by line?
You could achieve the same output list 'line1CP4Components' using the following:
Regex StripEmptyLines = new Regex(#"^\s*$", RegexOptions.Multiline);
Regex UnitPartsMatch = new Regex(#"(?<=\n)""UNIT"",""PARTS"".*?(?=(?:\n""UNIT"",""PARTS"")|$)", RegexOptions.Singleline);
string CP4DataBase =
"C:\\Program\\Line Balancer\\FUJI DB\\KTS\\KTS - CP4 - Part Data Base.txt";
CP4DataBaseRTB.LoadFile(CP4DataBase, RichTextBoxStreamType.PlainText);
List<string> line1CP4Components = new List<string>(
UnitPartsMatch.Matches(StripEmptyLines.Replace(CP4DataBaseRTB.Text, ""))
.OfType<Match>()
.Select(m => m.Value)
);
return line1CP4Components.ToArray();
You may be able to ignore the use of StripEmptyLines, but your original code is doing this via the Where(c => !string.IsNullOrEmpty(c)). Also your original code is causing the '\r' part of the "\r\n" newline/linefeed pair to be duplicated. I assumed this was an accident and not intentional?
Also you don't seem to be using the value in 'line1CP4PartLines' so I omitted the creation of the value. It was seemingly inconsistent with the omission of empty lines later so I guess you're not depending on it. If you need this value a simple regex can tell you how many new lines are in the string:
int linecount = new Regex("^", RegexOptions.Multiline).Matches(CP4DataBaseRTB.Text).Count;
// example of what your code will look like
string CP4DataBase = "C:\\Program\\Line Balancer\\FUJI DB\\KTS\\KTS - CP4 - Part Data Base.txt";
List<string> Cp4DataList = new List<string>(File.ReadAllLines(CP4DataBase);
//or create a Dictionary<int,string[]> object
string strData = string.Empty;//hold the line item data which is read in line by line
string[] strStockListRecord = null;//string array that holds information from the TFE_Stock.txt file
Dictionary<int, string[]> dctStockListRecords = null; //dictionary object that will hold the KeyValuePair of text file contents in a DictList
List<string> lstStockListRecord = null;//Generic list that will store all the lines from the .prnfile being processed
if (File.Exists(strExtraLoadFileLoc + strFileName))
{
try
{
lstStockListRecord = new List<string>();
List<string> lstStrLinesStockRecord = new List<string>(File.ReadAllLines(strExtraLoadFileLoc + strFileName));
dctStockListRecords = new Dictionary<int, string[]>(lstStrLinesStockRecord.Count());
int intLineCount = 0;
foreach (string strLineSplit in lstStrLinesStockRecord)
{
lstStockListRecord.Add(strLineSplit);
dctStockListRecords.Add(intLineCount, lstStockListRecord.ToArray());
lstStockListRecord.Clear();
intLineCount++;
}//foreach (string strlineSplit in lstStrLinesStockRecord)
lstStrLinesStockRecord.Clear();
lstStrLinesStockRecord = null;
lstStockListRecord.Clear();
lstStockListRecord = null;
//Alter the code to fit what you are doing..

how to get words inside a string

well i am working with xml but it is not important now, the problem is the next
it returns me something so
<xml>blalbalblal asfjñs
fasdf
iduser=dmengelblack; name=angel; lastname=uc;
blablal
iduser=cccarlos; name=carlos; lastname=uc;
how do i get (dmengelblack, angel, uc, carlos, uc)
i want to save every row...
remember all it is inside a string how do i get "dmengelblack", "angel", "uc" save it, everyone in a variable, and save all this in a variable too.. for example
string id="dmengelblack";
string name="angel";
string lastname="uc";
all="dmengelblack angel uc"
and i need to save the other row too, and all rows it can have
what do i know?
i know before than username it is "id="
i know before name it is "name="
i know before lastname it is "lastname="
i kwnow everyone finish with ";"
Simple way in java is to read the file as a stream, iterate through that and get the substring between
iduser= and ;
and
name= and ;
and
lastname= and ;
EDIT: With this code you will get the list of all the filed you want as
OUTPUT:
[iduser=dmengelblack, iduser=cccarlos]
[name=angel, name=carlos]
[lastname=uc, lastname=uc]
So now you interate through these list, split the each entry on =, you will the value you wanted at the second index on split.
CODE:
String str = "<xml>blalbalblal asfjñs" + "fasdf"
+ "iduser=dmengelblack; name=angel; lastname=uc;"
+ "blablal"
+ "iduser=cccarlos; name=carlos; lastname=uc;";
List<String> iduser = new ArrayList<String>();
List<String> name = new ArrayList<String>();
List<String> lastname = new ArrayList<String>();
int i = 1;
while(str.indexOf("iduser=", i) > 0) {
i=str.indexOf("iduser=",i);
iduser.add(str.substring(i, str.indexOf(";", i)));
name.add(str.substring(str.indexOf("name=", i), str.indexOf(";", str.indexOf("name=", i))));
lastname.add(str.substring(str.indexOf("lastname=", i), str.indexOf(";", str.indexOf("lastname=", i))));
i=str.indexOf("lastname=",i);
}
System.out.println(iduser);
System.out.println(name);
System.out.println(lastname);
hope this helps.
I would use RegEx to extract the pattern of key values into a hast table (dictionary), then use a know key mapping to assign it to the variables you have (iteration with a switch statement or something)
In c# (and other languages, but they will have different syntax) you can split a string into an array of strings like this:
string myString = "item1;item2;item3";
string[] separateStrings = myString.Split(';');
This will give you a string array like:
string[0] = "item1";
string[1] = "item2";
string[2] = "item3";
I would also suggest you clean up you tags to only tag what you really care about.

Categories