i hope you can give me a hint for my problem i have with my code.
I have a DataGridView which got its Data from an Excelfile.
Now to get structure in it, i want to make groups (keyword in dsdslls) and add valueNames (value of dsdslls and keyword in dslls) to that groups and add that content (value of dslls) to valueNames as KeyValuePair.
My Problem is not to add all that stuff, but to get it back.
here is the code (add stuff):
internal Dictionary<String, Dictionary<String, LinkedList<String>>> BuildList(DataGridView dgv)
{
//create the main Dictionary
Dictionary<String, Dictionary<String, LinkedList<String>>> dsdslls = new Dictionary<String, Dictionary<String, LinkedList<String>>>();
String groupName = "Project data", value = "", valueName = "", text = "";
//run through the whole list
for (int i = 0; i < dgv.RowCount - 1; i++)
{
//create new Dictionary for the Content
Dictionary<String, LinkedList<String>> dslls = new Dictionary<String, LinkedList<String>>();
//check if the String at i is a groupName, if so add it to groupName
if (isGroupName(dgv, i))
{
groupName = dgv.Rows[i].Cells[0].Value.ToString();
text = "Adding in group: " + groupName + " to value: ";
}
//now go forward in the list until you next Cell is empty or the list ended
do
{
//check if the String at i is a valueName, if so add it to valueName
if (isValueName(dgv, i))
{
//create the LinkedList for units and values
LinkedList<String> lls = new LinkedList<String>();
valueName = dgv.Rows[i].Cells[0].Value.ToString();
//check if group and valuename are NOT the same
if (isNotSame(valueName, groupName))
{
//now run the colums for units and values and add them to the List until you reach the end of used columns
int j = 0;
do
{
value = dgv.Rows[i].Cells[1 + j].Value.ToString();
lls.AddLast(value);
if (j == 0)
{
text += "\n" + valueName + " in (" + lls.First.Value.ToString() + "): ";
}
else
{
text += lls.Last.Value.ToString();
}
j++;
} while (j < dgv.Rows[i].Cells.Count - 1);
//add the valueName and List as new keyvaluepair to the dictionary.
dslls.Add(valueName, lls);
}
}
i++;
} while (!isStringEmpty(dgv.Rows[i].Cells[0].Value.ToString()) && i < dgv.RowCount - 1);
//show added content
MessageBox.Show(text);
//check if main dictionary contains the latest groupname, if not add the groupName and the last dictionary to the main dictionary
if (!dsdslls.ContainsKey(groupName))
{
dsdslls.Add(groupName, dslls);
}
}
MessageBox.Show("Building successfully finished.");
return dsdslls;
}
I'm not getting the right content back to the specified groupName... for example:" groupName = "Project Data" i got back the content of the group:" Electrical Network" which is the next keyword in the maindictionary
now the code to get the Data:
internal void /*Dictionary<String, LinkedList<String>>*/ GetGroupContent(Dictionary<String, Dictionary<String, LinkedList<String>>> dsdslls, String groupName)
{
//Dictionary<String, LinkedList<String>> dslls = new Dictionary<String, LinkedList<String>>();
String groupN = "", text = "";
//Check if Dictionary contains groupName
if (dsdslls.ContainsKey(groupName))
{
//run through the dictionary
foreach (var s in dsdslls)
{
//give back the keyword (just for the MessageBox)
if (s.Key == groupName)
{
groupN = s.Key;
}
else
{
//run throught the little dictionary to get the keywords from it.
foreach (var t in s.Value)
{
text += t.Key + "\n";
}
}
}
MessageBox.Show("Content of Group " + groupN + ": \n" + text);
text = "";
}
//return dslls;
}
Kind regards
Mirko
It is hard to understand what you expect from this code as the main problem is not well described.
Anyway, it seems that there might be problem in your data retrieval logic.
If you want to get data of group with matching name, then you have to move else part of your if statement. You need to do text concatenation only when group with correct name is found.
...
//give back the keyword (just for the MessageBox)
if (s.Key == groupName)
{
groupN = s.Key;
//run throught the little dictionary to get the keywords from it.
foreach (var t in s.Value)
{
text += t.Key + "\n";
}
}
...
Related
I have created a Dictionary called 'sGC' that has a string key and a value of a Tuple containing 2 lists of strings.
Dictionary<string, Tuple<List<string>, List<string>>> sGC = new Dictionary<string, Tuple<List<string>, List<string>>>();
I want to add new keys to this dictionary that are concatenated strings from a DataTable DataRow (DR). If a certain criteria is met then a string from the DR goes in either Item1 or Item2 of the Tuple.
This code is being executed in a foreach loop iterating through the DataTable, stopping on certain rows if the row meets an if statement criteria.
var dicTup = new Tuple<List<string>,List<string>>(new List<string>(), new List<string>());
dicTup.Item2.Add(DR["PupilID"].ToString());
sGC.Add(DR["CSN"].ToString() + DR["AW2"].ToString(), dicTup);
Is this the best way to add new dynamically named keys to the dictionary?
I believe the top answer from this JavaScript thread is an answer that I am looking for in C#: How to create dictionary and add key–value pairs dynamically?
Full code below.
foreach (DataRow DR in MainData.DataTable.Rows)
{
//Rows containing a symbol mark score
if ((DR["CN"].ToString() == "LC") && (DR["AW2"].ToString() != ""))
{
//Store male results
//If the Subject Name + Level Code is already a key in the dictionary, append to Tuple List 1
//If key does not exist in Dictionary, create new DictKey and value
if (DR["PG"].ToString() == "Male")
{
if (sGC.ContainsKey(DR["CSN"].ToString() + DR["AW2"].ToString()))
{
sGC[DR["CSN"].ToString() + DR["AW2"].ToString()].Item1.Add(DR["PID"].ToString());
}
else
{
var dicTup = new Tuple<List<string>,List<string>>(new List<string>(), new List<string>());
dicTup.Item1.Add(DR["PID"].ToString());
sGC.Add(DR["CSN"].ToString() + DR["AW2"].ToString(), dicTup);
}
}
//Store female results
//If the Subject Name + Level Code is already a key in the dictionary, append to Tuple List 2
//If key does not exist in Dictionary, create new DictKey and value
if (DR["PG"].ToString() == "Female")
{
if (sGC.ContainsKey(DR["CSN"].ToString() + DR["AW2"].ToString()))
{
sGC[DR["CSN"].ToString() + DR["AW2"].ToString()].Item2.Add(DR["PID"].ToString());
}
else
{
var dicTup = new Tuple<List<string>,List<string>>(new List<string>(), new List<string>());
dicTup.Item2.Add(DR["PupilID"].ToString());
sGC.Add(DR["CSN"].ToString() + DR["AW2"].ToString(), dicTup);
}
}
}
Newly edited and formatted code:
private void storeMarkSheetData()
{
if (MainData.DataTable != null)
{
if(subjectGradeCounts.Count == 0)
{
foreach (DataRow DR in MainData.DataTable.Rows)
{
string cN = DR["ColumnName"].ToString();
string aW2 = DR["AssessmentAwarded2"].ToString();
string cSN = DR["ClassSubjectName"].ToString();
string pID = DR["PupilID"].ToString();
string pG = DR["PupilGender"].ToString();
//Rows containing a symbol mark score
if ((cN == "Level Code") && (aW2 != ""))
{
//Check to see if the dictionary contains the key, adds it if not
if(!subjectGradeCounts.ContainsKey(cSN + aW2))
{
subjectGradeCounts.Add(cSN+aW2, new
Tuple<List<string>, List<string>>(new List<string>(), new
List<string>()));
}
//Now that the key exists, if it didn't previously
//If male add to list 1, else list 2 (for female)
if(pG == "Male")
{
subjectGradeCounts[cSN + aW2].Item1.Add(pID);
}
else
{
subjectGradeCounts[cSN + aW2].Item2.Add(pID);
}
}
}
}
}
}
Thank you all.
Here I simplified what you have to just check if the key exists, if not it adds it with new initialized lists, then does one if else for if male add to list 1 else (female) add to list 2, from the code you posted this is what I came up with
foreach (DataRow DR in MainData.DataTable.Rows)
{
//Rows containing a symbol mark score
if ((DR["CN"].ToString() == "LC") && (DR["AW2"].ToString() != ""))
{
//Check to see if your dictionary contains the key, if not, add it
if(!sGC.ContainsKey(DR["CSN"].ToString() + DR["AW2"].ToString()))
{
sGC.Add(DR["CSN"].ToString() + DR["AW2"].ToString(), new
Tuple<List<string>,List<string>>(new List<string>(), new
List<string>()));
}
//Now that the key exists, if it didn't previously
//If male add to list 1, else list 2 (for female)
if(DR["PG"].ToString() == "Male")
{
sGC[DR["CSN"].ToString() + DR["AW2"].ToString()].Item1.Add(DR["PupilID"].ToString());
}
else
{
sGC[DR["CSN"].ToString() + DR["AW2"].ToString()].Item2.Add(DR["PupilID"].ToString());
}
}
}
Major Edit: I am doing a bad job of explaining :(
I have two classes:
public class UserDefinitions// a list of 'Items', each'group of items belong to a user. I handle User logic elsewhere, and it works flawlessly.
{
public List<Item> items { get; set; }
}
public class Item //the User definitions. A user could have 1 or 15 of these. They would all be a single 'line' from the CSV file.
{
public string definitionKey { get; set; }
public string defName { get; set; }
public string defValue { get; set; }
}
Which I wanna build with a CSV File. I build this CSV File, so I make it using the same parameters every time.
I run SQL on my company's DB to generate results like so: http://i.imgur.com/gS1UJot.png
Then I read the file like so:
class Program
{
static void Main(string[] args)
{
var userData = new UserDefinitions();
var csvList = new List<Item>();
string json = "";
string fPath = #"C:\test\csvTest.csv";
var lines = File.ReadAllLines(fPath);
Console.WriteLine(lines);
List<string> udata = new List<string>(lines);
foreach (var line in udata)
{
string[] userDataComplete = line.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);// this cleans any empty cells from the CSV
csvList.Add(new Item { definitionKey = userDataComplete[1], defName = userDataComplete[2], defValue = userDataComplete[3] });
}
json = JsonConvert.SerializeObject(csvList); //everything below is for debugging/tracking progress
Console.WriteLine(json);
Console.ReadKey();
StreamWriter sw = new StreamWriter("C:\\test\\testjson.txt");
sw.WriteLine(json);
sw.Close();
}
}
This ALMOST does what I want. The output json is from the first 'column' of the csv data
[{"definitionKey":"uuid1","defName":"HairColor","defValue":"Brown"},{"definitionKey":"uuid1","defName":"HairColor","defValue":"Blonde"},{"definitionKey":"uuid1","defName":"HairColor","defValue":"Blue"}]
When using the screen shot as an example, the wanted output should be
[{"attributeDefinitionKey":"uuid1","name":"HairColor","value":"Brown"},{"definitionKey":"uuid2","defName":"FreckleAmount","defValue":"50"}]
[{"attributeDefinitionKey":"uuid1","name":"HairColor","value":"Blonde"},{"definitionKey":"uuid2","defName":"FreckleAmount","defValue":"null"}]
[{"attributeDefinitionKey":"uuid1","name":"HairColor","value":"Blue"},{"definitionKey":"uuid3","defName":"Tattoos","defValue":"5"}]
I can't pick out certain aspects at will, or apply them to Items. For example there maybe 10 users or 5000 users, but the definitionKey will always be the [1], and adding '3' will get every subsequent defintionKey. Just like the defName will always be in the [2] spot and adding 3 will get every subsequent defName if there are any, this is all per line.
I know I have to add some +3 logic, but not quite sure how to incorporate that. Maybe a for loop? a nested for loop after a foreach loop? I feel I am missing something obvious!
Thanks again for any help
This reads the csv line for line and converts each row to json, while adapting to the change in the amount of columns.
This only works if the CSV follows your rules:
one userId and
x amount of "Things" with 3 columns per "Thing".
private static void Main(string[] args)
{
var file = new StreamReader(#"C:\test\csvTest.csv");
string line;
var itemsJson = new List<string>();
file.ReadLine();
while ((line = file.ReadLine()) != null)
{
var sb = new StringBuilder();
var fields = line.Split(',');
sb.Append(GetKeyValueJson("UserId", fields[0]));
for (var i = 1; i < fields.Length; i += 3)
{
var x = (i + 3) / 3;
sb.Append(GetKeyValueJson($"Thing {i + x} ID", fields[i]));
sb.Append(GetKeyValueJson($"Thing {i + x} ID", fields[i + 1]));
sb.Append(i + 3 == fields.Length
? GetKeyValueJson($"Thing {i + x} ID", fields[i + 2], true)
: GetKeyValueJson($"Thing {i + x} ID", fields[i + 2]));
}
itemsJson.Add(WrapJson(sb.ToString()));
}
var json = WrapItems(itemsJson);
Console.ReadLine();
}
private static string GetKeyValueJson(string id, string value, bool lastPair = false)
{
var sb = new StringBuilder();
sb.Append('"');
sb.Append(id);
sb.Append('"');
sb.Append(':');
sb.Append('"');
sb.Append(value);
sb.Append('"');
if (!lastPair)
sb.Append(',');
return sb.ToString();
}
private static string WrapJson(string s)
{
var sb = new StringBuilder();
sb.Append('{');
sb.Append(s);
sb.Append('}');
return sb.ToString();
}
private static string WrapItems(List<string> jsonList)
{
var sb = new StringBuilder();
sb.Append('"');
sb.Append("Items");
sb.Append('"');
sb.Append(':');
sb.Append('[');
sb.Append(jsonList.Aggregate((current, next) => current + "," + next));
sb.Append(']');
return WrapJson(sb.ToString());
}
}
It's not pretty and sorting would be tough, but it should adapt to the column amount as long as it is in 3's.
My current code is looping through a list containing saved strings in an array. Currently it looks for all strings in that array. I want to change this so that it only goes through (searching, looking) for strings within "log[1]"
Sorry, i dont know the word for "log[1]". Im new to programming. Keep reading and i think you will understand.
This is how i want to do it:
foreach (string[] item[1] in loggbok)
item[1] being log[1]. Number 1 is very important because I want to search only within log[1].
This is my current code for saving the whole array in my list:
List<string[]> loggbok = new List<string[]> { };
string[] log = new string[3]; //date, title, post
DateTime date = DateTime.Now;
log[0] = "\n\tDate: " + date.ToLongDateString() + " Kl: " + date.ToShortTimeString();
Console.WriteLine(log[0]);
Console.Write("\tTitle: ");
log[1] = "\tTitle: " + Console.ReadLine();
Console.Write("\tPost: ");
log[2] = "\tPost: " + Console.ReadLine();
loggbok.Add(log);
log = new string[3];
I save "log[1],log[2],log[3]"
The following code i want to make a search function which goes through my list and recognise all the strings within log[1] aka titles. If a string title is containing the users keyword all logs should join and the log will be printed.
As of now. I solved this by searching through all logs(1,2,3). This means that my program is searching currently for strings within (titles, date, posts). This makes it so that you can search for messages or "post" when i want the user to be restricted by only searching for titles.
So i thought maby if in my foreach loop i make "item" to "item[1]". Will that make my code to only look for "log[1]". I did not get that far though becouse writing "item[1]" is invalid syntax.
Current search function:
string key;
Console.Write("\n\tSearch: ");
key = Console.ReadLine();
//Searching through all log[] in loggbok.
//I want to change this line to item[1]
foreach (string[] item in loggbok)
{
//goes deeper and looks for all strings within log[].
foreach (string s in item)
{
//if a string is found containing key word, this block will run.
if (s.Contains(key))
{
foundItem = true;
Console.WriteLine(String.Join("\r\n", item));
index++;
}
}
}
Probably you can do it like this:
var result = loggbok.FirstOrDefault(x=> x.Any(s=> s.Contains(key));
Console.WriteLine(result?? "No record found");
You don't even need to loop, so what you need to do is retrieve the item from loggbok by the index.
// assign loggbokx of index 1, to variable item.
string[] item = loggbok[1];
// item will then have the 2nd (index=1) logbook.
// Note that index starts from 0.
// If you want to have the first one, then it should be loggbox[0]
// to make it even simpler you can write
// var item = loggbok[1];
// and the rest is the same...
//goes deeper and looks for all strings within log[].
foreach (string s in item)
{
//if a string is found containing key word, this block will run.
if (s.Contains(key))
{
foundItem = true;
Console.WriteLine(String.Join("\r\n", item));
index++;
}
}
Let's do it right!
Create a model class for your log:
class LogEntry
{
public DateTime Date { get; set; }
public string Title { get; set; }
public string Post { get; set; }
public override string ToString()
{
return "Date: " + Date.ToLongDateString() + " Kl: " + Date.ToShortTimeString()
+ "\tTitle: " + Title + "\tPost: " + Post;
}
}
Now we can comfortably use this model.
Let's populate the list with more records:
List<LogEntry> loggbok = new List<LogEntry>();
for (int i = 0; i < 5; i++)
{
LogEntry entry = new LogEntry();
entry.Date = DateTime.Now;
entry.Title = "title" + i;
entry.Post = "post" + i;
loggbok.Add(entry);
}
Let's print it:
foreach (var entry in loggbok)
Console.WriteLine(entry);
Due to the ToString method overload output looks out nice.
Let's find something:
string key = "title3";
var found = loggbok.Find(log => log.Title == key);
Console.WriteLine("Found:\n" + found);
We can use different methods of the List class, and LINQ extension methods.
If you need to save your data to a file and then read them from there, you can use json serialization.
For example, let's use the JavaScriptSerializer (don't forget to add a reference to the assembly):
JavaScriptSerializer jss = new JavaScriptSerializer();
// Save
File.WriteAllText("test.txt", jss.Serialize(loggbok));
// Load
loggbok = jss.Deserialize<List<LogEntry>>(File.ReadAllText("test.txt"));
This is the solution if anyone finds it intressting.
foreach (string[] item in loggbok)
{
foreach (string s in item)
{
//This was the magic line.
string searchTitle = item[1].ToLower();
if (searchTitle.Contains(titleKey.ToLower()))
{
Console.WriteLine("\n\tSearch hit #" + index);
foundItem = true;
Console.WriteLine(String.Join("\r\n", item));
index++;
break;
}
}
}
Receiving the error:
CS0029: Cannot implicitly convert type 'System.Collections.Generic.List' to 'int'
Not sure how to fix.
I am using:
Microsoft .NET Framework Version:2.0.50727.5477;
ASP.NET Version:2.0.50727.5479
Section that's giving me trouble is at:
{
debugStr = debugStr + "-a=noattributesadd";
CartItem item = new CartItem(context);
item.ProductId = product.ProductId;
item.Quantity = qty;
items.Add(item);
}
Specifically, the item.Quantity = qty; portion
Complete code is:
CartItemCollection items = new CartItemCollection();
Cart cart = Core.GetCartObject();
string skus = "";
string debugStr = "";
Product product = null;
List<int> qty = new List<int>();
foreach (string item in HttpContext.Current.Request.Form.GetValues("quantity_input"))
{
qty.Add(int.Parse(item));
}
try
{
string[] productNumbers = HttpContext.Current.Request.Form.GetValues("ProductNumber");
foreach (string productNumber in productNumbers)
{
debugStr = debugStr + "-p=" + productNumber;
if(!string.IsNullOrEmpty(productNumber.Trim()) && !productNumber.StartsWith("Enter Product #"))
{
try
{ //redirect if no product found
product = Core.GetProductObjectByProductNumber(productNumber);
}
catch (Exception e)
{
debugStr = debugStr + "-e=noproductfound";
continue; //do nothing, process the next user input
}
//check if we have a valid product object, allow virtual and other type(s) for adding directly to cart which may need special handling
if(product != null)
{
debugStr = debugStr + "-t=" + product.ProductTypeName;
if(!product.ProductTypeName.Equals("NORMAL"))
{
//assume VIRTUAL (or other type) and redirect for selecting child/group products or other special handling
form.Redirect("product.aspx?p=" + product.ProductNumber);
}
else
{
debugStr = debugStr + "-a=noattributesadd";
CartItem item = new CartItem(context);
item.ProductId = product.ProductId;
item.Quantity = qty;
items.Add(item);
}
skus = skus + ";" + productNumber;
product = null; //reset the product object in case the next product number submitted is invalid
} //product not null
} //sanity check for empty or default data
} //iterate on each product submitted
cart.AddItems(items);
form.Redirect("cart.aspx?skus=" + skus);
}
catch (Exception e)
{
form.AddError("*** ProductNumber provided was not found ***");
form.Redirect("quickorder.aspx?qo=2&e=" + e.Message);
return;
}
Essentially, this is the logic for a Quick Order form. I'm trying to add the qty of each item to the Cart.
You problem is in this line:
item.Quantity = qty;
item.Quantity is an int and qty is a List<int>
A guess at how to solve (assume all lists are in the same order and enumeration will read them in the same order):
int index = 0; // add this line
foreach (string productNumber in productNumbers)
{
// all the stuff you have already till:
item.Quantity = qty[index];
// all the stuff you have already
index = index + 1;
} //iterate on each product submitted
NOTE: I HATE THIS SOLUTION. But it will probably work.
A good solution would be to create a data structure that holds both the productnumber and the quantity in the same list.
I'm hoping someone can help. A long time windows forms/aspx user, moving to WPF.
Not expecting a coded answer to this, but any pointers on a different way to approach would be greatly appreciated - I am probably approaching this in a very backward way.
So the objective is to have an ObservableCollection with sub ObservableCollection "childen" within to then bind to my WPF treeview control.
I can bind my collection to the treeview without issues, and have styled it with checkboxes images as desired, frustratingly, its the ObservableCollection with children of children of children I am having trouble generating in the first place.
I have a table in SQL with LDAP Paths, and various other information I'm storing against that LDAP path, which I read into my ObservableCollection.
Single level, no problem, the bit I'm struggling with is sorted the sub objects of sub objects by LDAP Path, so when I bind to the treeview is presented as AD OU's are structured.
EG:
TopOU
Users
Front Office Users
Helpdesk Users
Example LDAP Paths in my DB
LDAP://OU=Front Office Users,OU=Users,OU=TopOU,DC=dev,DC=local
LDAP://OU=Helpdesk Users,OU=Users,OU=TopOU,DC=dev,DC=local
LDAP://OU=OU=Users,OU=TopOU,DC=dev,DC=local
LDAP://OU=OU=TopOU,DC=dev,DC=local
private ObservableCollection<AssignmentData> OUTreeAssignmentsCollection = new ObservableCollection<AssignmentData>();
public class AssignmentData : INotifyPropertyChanged
{
public Int32 AssignmentID { get; set; }
public String AssignmentName { get; set; }
public AssignmentTypes AssignmentType { get; set; }
//other stuff....
//For TreeView all sub nodes
public ObservableCollection<AssignmentData> Children { get; set; }
}
I then start to read from my db in a rather nasty way, and this is where it all goes wrong, and I could use some pointers.
cmd = new SqlCommand("SELECT UserGroups.UserGroupID, UserGroups.Name, UserGroups.LDAPPath FROM UserGroups WHERE UserGroups.TypeID=1", DBCon);
reader = cmd.ExecuteReader();
while (reader.Read())
{
String strLDAPHierarchical = GetLDAPHierarchical(reader[2].ToString());
AssignmentData newItem = new AssignmentData()
{
AssignmentID = Convert.ToInt32(reader[0]),
AssignmentName = reader[1].ToString(),
AssignmentImage = ouIcon,
AssignmentLDAPPath = reader[2].ToString(),
AssignmentCNPath = GetCNFromLDAPPath(reader[2].ToString()),
AssignmentTooltip = GetADSLocationTooltip(reader[2].ToString()),
AssignmentType = AssignmentTypes.UserOU,
AssignmentLDAPHierarchical = strLDAPHierarchical
};
if (strLDAPHierarchical.Contains(","))
{
//Now check all the root nodes exist to continue
String strLDAPHierarchicalCheckPath = strLDAPHierarchical;
String[] SplitLDAPHierarchical = strLDAPHierarchical.Split(new Char[] { ',' });
Int32 reverseI = SplitLDAPHierarchical.Length - 1;
String prevPath = "";
for (int i = 0; i < SplitLDAPHierarchical.Length; i++)
{
String path = SplitLDAPHierarchical[reverseI];
//now check if this node is already there and if not look it up and create it
if (path != "")
{
if (i == 0) { strLDAPHierarchicalCheckPath = path; }
else { strLDAPHierarchicalCheckPath = path + "," + prevPath; }
WriteLog("CHECK:" + strLDAPHierarchicalCheckPath);
LookupItemByLDAPHierarchical(strLDAPHierarchicalCheckPath, newItem);
if (i == 0) { prevPath = path; }
else { prevPath = path + "," + prevPath; }
reverseI = reverseI - 1;
}
}
}
else
{
//is top level object, so create at the root of the collection
UserOUCollection.Add(newItem);
}
Function to add sub items :-/
internal AssignmentData LookupItemByLDAPHierarchical(String strLDAPHierarchical, AssignmentData fromItem)
{
AssignmentData currentItem = null;
foreach (AssignmentData d in UserOUCollection)
{
if (d.AssignmentLDAPHierarchical == strLDAPHierarchical) { currentItem = d; break; }
if (d.Children != null)
{
currentItem = CheckChildNodesByLDAPHierarchical(d, strLDAPHierarchical);
if (currentItem != null) { break; }
}
}
String strMessage = "null";
if (currentItem != null) { strMessage = currentItem.AssignmentLDAPPath; }
if (currentItem == null)
{
String strWhere = "LDAPPath LIKE 'LDAP://" + strLDAPHierarchical + "%'";
SqlConnection DBCon = new SqlConnection(SQLString);
DBCon.Open();
SqlCommand cmd = new SqlCommand("SELECT UserGroupID, Name, LDAPPath FROM UserGroups WHERE " + strWhere + " AND TypeID=1", DBCon);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
strLDAPHierarchical = GetLDAPHierarchical(reader[2].ToString());
AssignmentData newItem = new AssignmentData()
{
AssignmentID = Convert.ToInt32(reader[0]),
AssignmentName = reader[1].ToString(),
AssignmentImage = ouIcon,
AssignmentLDAPPath = reader[2].ToString(),
AssignmentCNPath = GetCNFromLDAPPath(reader[2].ToString()),
AssignmentTooltip = GetADSLocationTooltip(reader[2].ToString()),
AssignmentType = AssignmentTypes.UserOU,
AssignmentLDAPHierarchical = strLDAPHierarchical
};
String strLDAPHierarchicalCheckPath = strLDAPHierarchical;
foreach (String path in strLDAPHierarchical.Split(new Char[] { ',' }))
{
//now check if this node is already there and if not look it up and create it
if (path != "")
{
strLDAPHierarchicalCheckPath = strLDAPHierarchicalCheckPath.Replace(path + ",", "");
currentItem = LookupItemByLDAPHierarchical(strLDAPHierarchicalCheckPath, currentItem);
if (null == currentItem)
{
UserOUCollection.Add(newItem); //new root item
}
else
{
if (currentItem.Children == null)
{
//add new child
currentItem.Children = new ObservableCollection<AssignmentData> { newItem };
}
else
{
//add more children to exisiting
currentItem.Children.Add(newItem);
}
}
currentItem = null;
}
}
//Find a current Item to add the node to
//currentItem = LookupItemByLDAPHierarchical(strLDAPHierarchical);
}
reader.Close();
reader.Dispose();
DBCon.Close();
DBCon.Dispose();
}
return currentItem;
}
With my current solution, I get a treeview, with sub nodes of sub nodes, but they are wrong/lots of duplication etc. I have spent literally days trying to fix my probably overcomplicated attempt above - but have come to the conclusion I'm probably going about it the wrong way.
Any help greatly appreciated!
Just having a peruse ;) through your code. Think I can see why you have lots of duplications. Looks like your first SQL query get's all parent/child records. Then the second query will go and get some of those records again, if that makes sense.
One approach would be to only get the top level items in your first query. Possibly by getting SQL to count the number of commas.
SELECT UserGroups.UserGroupID, UserGroups.Name, UserGroups.LDAPPath,
LENGTH(LDAPPath) - LENGTH(REPLACE(LDAPPath, ',', '')) as CommaCount
FROM UserGroups
WHERE UserGroups.TypeID=1
AND CommaCount = 2
Since you asked for different approach id say it's not very efficient to repeatedly query the database in a loop. When I'm building a tree of parent child objects I'd normally get all parent/child records in one query. Build a flat dictionary of all the objects. Then loop through it and make the parent/child associations.
The dictionary can also be useful to lookup your objects later on either directly by key or to loop through without having to make a recursive function that crawls the tree.
So I'd suggest that you break it down into 2 blocks of code.
First block: Using your existing query that get's all of the items, create a flat Dictionary with everything in.
They key of each item should probably be the result from GetLDAPHierarchical().
Second block: Next loop through the dictionary and create the hierarchy. Add anything with no parent directly to the UserOUCollection
foreach(AssignmentData d in myDictionary.Values)
{
String parentKey = GetParentLDAPKey(d.AssignmentLDAPHierarchical);
if (myDictionary.ContainsKey(parentKey))
{
myDictionary(parentKey).children.Add(d);
}
else
{
UserOUCollection.Add(d);
}
}
GetParentLDAPKey() will need to produce the same key as it's parent by removing the first part of the LDAP Path.
Hope that points you in the right direction.
H
(SMASH)
Thanks so much to hman, who pointed me in a much more logical direction. I used LDAPPath as my dictionary key.
Dictionary<String, AssignmentData> OUDictionary = new Dictionary<String, AssignmentData>();
//Read from DB
cmd = new SqlCommand("SELECT UserGroups.UserGroupID, UserGroups.Name, UserGroups.LDAPPath FROM UserGroups WHERE UserGroups.TypeID=1", DBCon);
reader = cmd.ExecuteReader();
while (reader.Read())
{
AssignmentData newItem = new AssignmentData()
{
AssignmentID = Convert.ToInt32(reader[0]),
AssignmentName = reader[1].ToString(),
AssignmentImage = ouIcon,
AssignmentLDAPPath = reader[2].ToString(),
AssignmentCNPath = GetCNFromLDAPPath(reader[2].ToString()),
AssignmentTooltip = GetADSLocationTooltip(reader[2].ToString()),
AssignmentType = AssignmentTypes.UserOU,
};
UserOUDictionary.Add(reader[2].ToString(), newItem);
}
reader.Close();
reader.Dispose();
//Now Read OU List into TreeView Collection
foreach (AssignmentData d in UserOUDictionary.Values)
{
String parentKey = GetParentLDAPPath(d.AssignmentLDAPPath);
if (UserOUDictionary.ContainsKey(parentKey))
{
AssignmentData parentItem = UserOUDictionary[parentKey];
if (parentItem.Children == null) { parentItem.Children = new ObservableCollection<AssignmentData> { d }; } //add first child
else { parentItem.Children.Add(d); } //add more children to exisiting
}
else
{
UserOUCollection.Add(d); //add to root of control
}
}
private String GetParentLDAPKey(String strLDAPPath)
{
String retParentKey = strLDAPPath;
if (strLDAPPath.Contains(","))
{
retParentKey = retParentKey.Replace("LDAP://", "");
retParentKey = retParentKey.Remove(0, retParentKey.IndexOf(",") + 1);
retParentKey = "LDAP://" + retParentKey;
}
return retParentKey;
}