How to generate hierachy from treeview - c#

I have populated a treeview using this code:
private void updateTree()
{
treeView1.Nodes.Clear();
List<TreeNode> graphicsNodes = new List<TreeNode>();
foreach (Graphic graphic in graphics)
{
List<TreeNode> templateNodes = new List<TreeNode>();
foreach (Template template in graphic.templates)
{
List<TreeNode> aliasNodes = new List<TreeNode>();
foreach(Alias alias in template.aliases)
{
aliasNodes.Add(new TreeNode(alias.aliasName + ": " + alias.aliasValue));
}
templateNodes.Add(new TreeNode(template.templateName, aliasNodes.ToArray()));
}
graphicsNodes.Add(new TreeNode(graphic.fileName.Replace(".g", ""), templateNodes.ToArray()));
}
treeView1.Nodes.Add(new TreeNode("Graphics", graphicsNodes.ToArray()));
}
After manipulating, renaming and deleting some of these elements in the TreeView, is it possible to rebuild my Grapics structure with the new values?
This structure is built so that each Graphic has many Templates and each Template has many Aliases, this code is defined as follows:
public class Graphic
{
public string filePath;
public string fileName;
public List<Template> templates;
public Graphic(List<Template> _templates, string fpath, string fName)
{
templates = _templates;
fileName = fName;
filePath = fpath;
}
}
public class Template
{
public List<Alias> aliases;
public string templateName;
public Template(string instString, string userdataString)
{
templateName = (instString.Replace("inst ", "").Replace(" 0 0", "")).Replace(" ","");
aliases = new List<Alias>();
string[] aliasStrings = userdataString.Replace("\"","").Split(new string[1] { "text_alias" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string segment in aliasStrings)
{
if (segment.Contains("userdata")) { continue; }
string aliasString = "text_alias" + segment;
string[] sections = aliasString.Split('^');
aliases.Add(new Alias(sections[0].Replace("text_alias=", ""), (sections[1].Replace("text_exp_flag=", "") == "1"), sections[2].Replace("alias_new_name=", ""), sections[3].Replace("alias_value=", ""))); //Sorry!
}
}
}
public class Alias
{
public string aliasName;
public string aliasValue;
public string newName;
public bool expectedFlag;
public Alias(string name, bool expected, string nName, string value)
{
aliasName = name;
aliasValue = value;
newName = nName;
expectedFlag = expected;
}
}
If this is not easily achievable, what would be the best way to approach this from a different angle?
Thanks in advance!

Try this,
for (int i = 0; i <= dst.Tables[0].Rows.Count - 1; i++)
{
nodeTables.Nodes.Add(dst.Tables[0].Rows[i]["SchemaName"].ToString() + "." + dst.Tables[0].Rows[i]["TableName"].ToString());
nodeTables.Nodes[i].ImageIndex = 2;
nodeTables.Nodes[i].Nodes.Add("Columns");
//Filling the Column Names
DataSet dstCol = new DataSet();
dstCol = common.GetColumns(Convert.ToInt32(dst.Tables[0].Rows[i]["object_Id"]));
for (int col = 0; col <= dstCol.Tables[0].Rows.Count - 1; col++)
{
nodeTables.Nodes[i].Nodes[0].ImageIndex = 0;
nodeTables.Nodes[i].Nodes[0].Nodes.Add(dstCol.Tables[0].Rows[col]["name"].ToString());
nodeTables.Nodes[i].Nodes[0].Nodes[col].ImageIndex = 1;
}
}

Related

C# retrieve parent-child url from full url using recursively

I need your help in getting parent-child URL list from full URL, maybe using recursively.
For example, below is URL in flat structure. I have to parse in parent-child form with inner level of child structure.
https://domain/UrlA/UrlA_L1/UrlA_L1_L2
https://domain/UrlA/UrlA_L1/UrlA2_L1_L2
https://domain/UrlB/UrlB_L1/UrlB_L1_L2
https://domain/UrlC/UrlC_L1/UrlC_L1_L2
https://domain/UrlD/UrlD_L1/UrlD_L1_L2/UrlD_L1_L2_L3
https://domain/UrlE/UrlE_L1/UrlE_L1_L2/UrlE_L1_L2_L3
https://domain/UrlF/UrlF_L1/UrlF_L1_L2/UrlF_L1_L2_L3
into a list of URL with child-parent relationship.
public class HtmlSiteMap
{
public string Url { get; set; }
public string PageTitle { get; set; }
public int UrlLevel { get; set; }
public List<HtmlSiteMap> Childrens { get; set; }
}
my expected output
{
Url: https://domain/UrlA,
PageTitle : UrlA,
UrlLevel : 0 ,
Childrens : {
Url : https://domain/UrlA/UrlA_L1,
PageTitle : UrlA_L1,
UrlLevel : 1,
Childrens : {
Url : https://domain/UrlA/UrlA_L1/UrlA_L1_L2,
PageTitle : UrlA_L1_L2,
UrlLevel : 2,
Childrens : null
},
{
Url : https://domain/UrlA/UrlA_L1/UrlA2_L1_L2,
PageTitle : UrlA2_L1_L2,
UrlLevel : 2,
Childrens : null
}
},
Url: https://domain/UrlB,
PageTitle : UrlB,
UrlLevel : 0 ,
Childrens : {
Url : https://domain/UrlB/UrlB_L1,
PageTitle : UrlB_L1,
UrlLevel : 1,
Childrens : {
Url : https://domain/UrlB/UrlB_L1/UrlB_L1_L2,
PageTitle : UrlB_L1_L2,
UrlLevel : 2,
Childrens : null
}
}
.................
.................
..................
}
I have tried to achieve by splitting and recursively. But unable to get a result. Your help will be appreciated.
Here is another reverse solution. I am working on preordered list, constructing nodes from roots to leaves. This code looks more readable and understandable by beginners in recursion.
static void Main(string[] args)
{
var input = new[]
{
new Uri("https://domain/UrlA/UrlA_L1/UrlA_L1_L2"),
new Uri("https://domain/UrlA/UrlA_L1/UrlA2_L1_L2"),
new Uri("https://domain/UrlB/UrlB_L1/UrlB_L1_L2"),
new Uri("https://domain/UrlC/UrlC_L1/UrlC_L1_L2"),
new Uri("https://domain/UrlD/UrlD_L1/UrlD_L1_L2/UrlD_L1_L2_L3"),
new Uri("https://domain/UrlE/UrlE_L1/UrlE_L1_L2/UrlE_L1_L2_L3"),
new Uri("https://domain/UrlF/UrlF_L1/UrlF_L1_L2/UrlF_L1_L2_L3")
};
var rows = input.Select(u => u.AbsolutePath.Substring(1))
.OrderBy(s => s).Select(s => s.Split('/')).ToList();
var rootNodes = new List<HtmlSiteMap>();
ProcessNodes(rootNodes, rows,
input.Select(u => $"{u.Scheme}://{u.Host}/").Distinct().FirstOrDefault(), 0);
foreach (var node in rootNodes)
Console.WriteLine(node.ToString());
}
static void ProcessNodes(List<HtmlSiteMap> children, List<string[]> rows, string prefix, int level)
{
if (rows.Count == 0)
return;
HtmlSiteMap currentNode = null;
var subRows = new List<string[]>();
foreach (var parts in rows)
{
if (parts.Length == 0)
continue;
subRows.Add(parts.Skip(1).ToArray());
if (currentNode != null && currentNode.PageTitle == parts[0])
continue;
if(currentNode != null)
ProcessNodes(currentNode.Children, subRows, prefix + currentNode.PageTitle + "/", level + 1);
currentNode = new HtmlSiteMap
{
Url = prefix + parts[0],
PageTitle = parts[0],
UrlLevel = level
};
children.Add(currentNode);
subRows.Clear();
}
if(currentNode != null && subRows.Count > 0)
ProcessNodes(currentNode.Children, subRows, prefix + currentNode.PageTitle + "/", level + 1);
}
public class HtmlSiteMap
{
public string Url { get; set; }
public string PageTitle { get; set; }
public int UrlLevel { get; set; }
//Also renamed this from Childrens to Children
public List<HtmlSiteMap> Children { get; set; }
public HtmlSiteMap()
{
Children = new List<HtmlSiteMap>();
}
//Borrowed this from previous answer
public override string ToString()
{
var shift = new string(' ', UrlLevel);
var sb = new StringBuilder();
sb.AppendLine(shift + $"Url: {Url},");
sb.AppendLine(shift + $"PageTitle: {PageTitle},");
sb.AppendLine(shift + $"UrlLevel: {UrlLevel},");
sb.AppendLine(shift + "Children:");
if (Children.Count == 0)
{
sb.AppendLine(shift + "-");
}
else
{
foreach (var child in Children)
{
sb.AppendLine(child.ToString());
}
}
return sb.ToString();
}
}
A base version (without errors handling) may look like this:
static void Main(string[] args)
{
var input = new List<string>
{
"https://domain/UrlA/",
"https://domain/UrlA/UrlA_L1/",
"https://domain/UrlA/UrlA_L1/UrlA_L1_L2",
"https://domain/UrlA/UrlA_L1/UrlA2_L1_L2",
"https://domain/UrlB",
"https://domain/UrlB/UrlB_L1",
"https://domain/UrlB/UrlB_L1/UrlB_L1_L2",
"https://domain/UrlC/UrlC_L1/UrlC_L1_L2",
"https://domain/UrlD/UrlD_L1/UrlD_L1_L2/UrlD_L1_L2_L3",
"https://domain/UrlE/UrlE_L1/UrlE_L1_L2/UrlE_L1_L2_L3",
"https://domain/UrlF/UrlF_L1/UrlF_L1_L2/UrlF_L1_L2_L3"
};
var output = new List<HtmlSiteMap>();
foreach (var url in input)
{
var parts = url.Split(#"/", StringSplitOptions.RemoveEmptyEntries);
var current = new HtmlSiteMap
{
Url = url,
PageTitle = parts[^1]
};
var parentName = parts[^2];
static HtmlSiteMap FindParent(List<HtmlSiteMap> score, string name)
{
foreach (var item in score)
{
if (item.PageTitle == name)
{
return item;
}
var inChild = FindParent(item.Childrens, name);
if (inChild != null)
{
return inChild;
}
}
return null;
}
var parent = FindParent(output, parentName);
if (parent == null)
{
current.UrlLevel = 1;
output.Add(current);
}
else
{
current.UrlLevel = parent.UrlLevel + 1;
parent.Childrens.Add(current);
}
}
foreach (var current in output)
{
Console.WriteLine(current.ToString());
}
Console.ReadLine();
}
public class HtmlSiteMap
{
public string Url { get; set; }
public string PageTitle { get; set; }
public int UrlLevel { get; set; }
public List<HtmlSiteMap> Children { get; set; }
public HtmlSiteMap()
{
Children = new List<HtmlSiteMap>();
}
public override string ToString()
{
var shift = new string(' ', UrlLevel);
var sb = new StringBuilder();
sb.AppendLine(shift + $"Url: {Url},");
sb.AppendLine(shift + $"PageTitle: {PageTitle},");
sb.AppendLine(shift + $"UrlLevel: {UrlLevel},");
sb.AppendLine(shift + "Children:");
if (Children.Count == 0)
{
sb.AppendLine(shift + "-");
}
else
{
foreach (var child in Children)
{
sb.AppendLine(child.ToString());
}
}
return sb.ToString();
}
}

Own class object attribute get overridden

I have created an object with the attributes String, and the other is a List<String>.
I have also created a static List<MyObject> where i add then all my Objects.
Now my Problem is the second attribute is getting overridden.
For example I have 3 Objects:
Object1: "Name"; List with 3 Strings
Object2: "Name2"; List with 2 Strings
Object3: "Name3"; List with 5 Strings
If i add them now to my Object List, it looks like so
Name; List with 5 Strings
Name2; List with 5 Strings
Name3; List with 5 Strings
It override the second attributes to all the other Objects in the List.
Code:
for (int i = 0; i < 100; i++)
{
if (elo.ReadObjMask(i) > 0)
{
var iRet = elo.PrepareObjectEx(0, 0, i);
maskenname = elo.ObjMName();
if (maskenname != "")
{
for (int e = 0; e < 50; e++)
{
string eigenschaft = elo.GetObjAttribName(e);
if (eigenschaft != "" && eigenschaft != "-")
{
eigenschaften.Add(eigenschaft);
}
}
allMasks.Add(maskenname);
}
else
{
// Do nothing
}
EloMask emask = new EloMask(maskenname, eigenschaften);
staticVariables.allMask.Add(emask);
eigenschaften.Clear();
}
}
Here is my object class:
public class EloMask
{
public string name;
public List<String> eigenschaften;
public EloMask(string iname, List<String> ieigenschaften)
{
name = iname;
eigenschaften = ieigenschaften;
}
}
The List<string> always points to the same instance because you are passing a reference to the list, not a copy. As a result, the list is cleared and filled again for each EloMask that you pass that list into.
To fix your issue, create a new list instead:
if (elo.ReadObjMask(i) > 0)
{
var iRet = elo.PrepareObjectEx(0, 0, i);
maskenname = elo.ObjMName();
// create a new list here!!!
var eigenschaften = new List<string>();
if (maskenname != "")
{
for (int e = 0; e < 50; e++)
{
string eigenschaft = elo.GetObjAttribName(e);
if (eigenschaft != "" && eigenschaft != "-")
{
eigenschaften.Add(eigenschaft);
}
}
allMasks.Add(maskenname);
}
EloMask emask = new EloMask(maskenname, eigenschaften);
staticVariables.allMask.Add(emask);
// clearing the list is no longer needed
}
Here is an example how you can do what you want:
public static List<Person> PersonsList = new List<Person>();
public static Random rd = new Random();
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
List<string> tmpAbilities = new List<string>() {((char)rd.Next(255)).ToString(), ((char)rd.Next(255)).ToString() , ((char)rd.Next(255)).ToString() };
Person tmpPerson = new Person("TmpName_"+i,tmpAbilities);
PersonsList.Add(tmpPerson);
}
foreach (var persona in PersonsList)
{
Console.WriteLine(persona);
}
}
public class Person
{
public string Name { get; set; }
public List<string> Abilities;
public Person(string name,List<string> abilities)
{
Name = name;
Abilities = abilities;
}
public override string ToString()
{
string retVal = $"Name: {Name}\n";
foreach (var ability in Abilities)
{
retVal += $"Ability : {ability}\n";
}
return retVal;
}
}
for (int i = 0; i < 100; i++)
{
if (elo.ReadObjMask(i) > 0)
{
// Create a new listin here
eigenschaften = new List<string>();
var iRet = elo.PrepareObjectEx(0, 0, i);
maskenname = elo.ObjMName();
if (maskenname != "")
{
for (int e = 0; e < 50; e++)
{
string eigenschaft = elo.GetObjAttribName(e);
if (eigenschaft != "" && eigenschaft != "-")
{
eigenschaften.Add(eigenschaft);
}
}
allMasks.Add(maskenname);
}
else
{
// Do nothing
}
EloMask emask = new EloMask(maskenname, eigenschaften);
staticVariables.allMask.Add(emask);
}
}

String to Object Collection

I Have this String
([{"id":"111","name":"Robocop","cover":"3114188e.jpg"},{"id":"222","name":"Eater","cover":"72dpi.jpg"}])
And is there better way to convert to Object Collection, couse now my crappy code looks like this:
var trimer = myString.TrimStart('(', '[').TrimEnd(')', ']');
string[] coll = trimer.Split('{','}');
string content = "";
foreach(string i in coll)
{
if (!string.IsNullOrEmpty(i) && i != "," && i != "")
{
content += i + "\r\n";
}
}
string[] contentData = content.Split(new string[] { "\r\n" }, StringSplitOptions.None);
for (int i = 0; i < contentData.Length - 1; i++)
{
string book = contentData[i].Replace(',','\t').Replace("\"","");
string[] info = book.Split(new string[] { "\t" }, StringSplitOptions.None);
string id = info[0];
string name = info[1];
string cover = info[2];
}
Yes. You actually have a JSON string. You'll need to remove the parenthesis (if they actually exist in the received string) and then you can deserialize it properly. This example uses Json.NET:
public void DeserializeFoo()
{
var json = "[{\"id\":\"111\",\"name\":\"Robocop\",\"cover\":\"3114188e.jpg\"},
{\"id\":\"222\",\"name\":\"Eater\",\"cover\":\"72dpi.jpg\"}]";
var foos = JsonConvert.DeserializeObject<List<Foo>>(json);
foreach (var foo in foos)
{
Console.WriteLine("Id: {0}", foo.Id);
Console.WriteLine("Name: {0}", foo.Name);
Console.WriteLine("Cover: {0}", foo.Cover);
}
}
public class Foo
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("cover")]
public string Cover { get; set; }
}

Creating CSV File from string array

I am trying to export data from a list of object to a csv file. I managed to create the file and create the first row, however I need to create some kind of for each loop to loop through each object.
This is my code:
string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = pathDesktop + "\\mycsvfile.csv";
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
string delimter = ",";
string[][] output = new string[][] {
new string[] {"TEST1","TEST2"}
};
int length = output.GetLength(0);
StringBuilder sb = new StringBuilder();
for (int index = 0; index < length; index++)
{
sb.AppendLine(string.Join(delimter, output[index]));
File.AppendAllText(filePath, sb.ToString());
}
Is there any way to create this file and using a loop to loop through all my objects and display them in file.
Here's the solution:
string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = pathDesktop + "\\mycsvfile.csv";
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
string delimter = ",";
List<string[]> output = new List<string[]>();
//flexible part ... add as many object as you want based on your app logic
output.Add(new string[] {"TEST1","TEST2"});
output.Add(new string[] {"TEST3","TEST4"});
int length = output.Count;
using (System.IO.TextWriter writer = File.CreateText(filePath))
{
for (int index = 0; index < length; index++)
{
writer.WriteLine(string.Join(delimter, output[index]));
}
}
Assuming that obj is a List of String I usually use this
System.IO.File.WriteAllLines(stringFilePath, obj.ToArray());
If you want a generic extension that will loop through every item in your list adding it to a new line and loop through every public property with a getter and create a comma separated list of fields per property on the line you can use my extension as per my tip, here or my Gist, here, calling the extension on the List like so:
MyList.ToDelimitedText(",", true);
Full code below
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace Gists.Extensions.ListOfTExtentions
{
public static class ListOfTExtentions
{
/// <summary>
/// Converst this instance to delimited text.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance">The instance.</param>
/// <param name="delimiter">The delimiter.</param>
/// <param name="trimTrailingNewLineIfExists">
/// If set to <c>true</c> then trim trailing new line if it exists.
/// </param>
/// <returns></returns>
public static string ToDelimitedText<T>(this List<T> instance,
string delimiter,
bool trimTrailingNewLineIfExists = false)
where T : class, new()
{
int itemCount = instance.Count;
if (itemCount == 0) return string.Empty;
var properties = GetPropertiesOfType<T>();
int propertyCount = properties.Length;
var outputBuilder = new StringBuilder();
for (int itemIndex = 0; itemIndex < itemCount; itemIndex++)
{
T listItem = instance[itemIndex];
AppendListItemToOutputBuilder(outputBuilder, listItem, properties, propertyCount, delimiter);
AddNewLineIfRequired(trimTrailingNewLineIfExists, itemIndex, itemCount, outputBuilder);
}
var output = TrimTrailingNewLineIfExistsAndRequired(outputBuilder.ToString(), trimTrailingNewLineIfExists);
return output;
}
private static void AddDelimiterIfRequired(StringBuilder outputBuilder, int propertyCount, string delimiter,
int propertyIndex)
{
bool isLastProperty = (propertyIndex + 1 == propertyCount);
if (!isLastProperty)
{
outputBuilder.Append(delimiter);
}
}
private static void AddNewLineIfRequired(bool trimTrailingNewLineIfExists, int itemIndex, int itemCount,
StringBuilder outputBuilder)
{
bool isLastItem = (itemIndex + 1 == itemCount);
if (!isLastItem || !trimTrailingNewLineIfExists)
{
outputBuilder.Append(Environment.NewLine);
}
}
private static void AppendListItemToOutputBuilder<T>(StringBuilder outputBuilder,
T listItem,
PropertyInfo[] properties,
int propertyCount,
string delimiter)
where T : class, new()
{
for (int propertyIndex = 0; propertyIndex < properties.Length; propertyIndex += 1)
{
var property = properties[propertyIndex];
var propertyValue = property.GetValue(listItem);
outputBuilder.Append(propertyValue);
AddDelimiterIfRequired(outputBuilder, propertyCount, delimiter, propertyIndex);
}
}
private static PropertyInfo[] GetPropertiesOfType<T>() where T : class, new()
{
Type itemType = typeof (T);
var properties = itemType.GetProperties(BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public);
return properties;
}
private static string TrimTrailingNewLineIfExistsAndRequired(string output, bool trimTrailingNewLineIfExists)
{
if (!trimTrailingNewLineIfExists || !output.EndsWith(Environment.NewLine)) return output;
int outputLength = output.Length;
int newLineLength = Environment.NewLine.Length;
int startIndex = outputLength - newLineLength;
output = output.Substring(startIndex, newLineLength);
return output;
}
}
}
Examples of calling the code can be found in these tests:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Gists.Extensions.ListOfTExtentions;
namespace Gists_Tests.ExtensionTests.ListOfTExtentionTests
{
[TestClass]
public class ListOfT_ToDelimitedTextTests
{
#region Mock Data
private class SimpleObject
{
public int Id { get; set; }
}
private class ComplextObject : SimpleObject
{
public string Name { get; set; }
public bool Active { get; set; }
}
#endregion
#region Tests
[TestMethod]
public void ToDelimitedText_ReturnsCorrectNumberOfRows()
{
// ARRANGE
var itemList = new List<ComplextObject>
{
new ComplextObject {Id = 1, Name = "Sid", Active = true},
new ComplextObject {Id = 2, Name = "James", Active = false},
new ComplextObject {Id = 3, Name = "Ted", Active = true},
};
const string delimiter = ",";
const int expectedRowCount = 3;
const bool trimTrailingNewLineIfExists = true;
// ACT
string result = itemList.ToDelimitedText(delimiter, trimTrailingNewLineIfExists);
var lines = result.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var actualRowCount = lines.Length;
// ASSERT
Assert.AreEqual(expectedRowCount, actualRowCount);
}
[TestMethod]
public void ToDelimitedText_ReturnsCorrectNumberOfProperties()
{
// ARRANGE
var itemList = new List<ComplextObject>
{
new ComplextObject {Id = 1, Name = "Sid", Active = true}
};
const string delimiter = ",";
const int expectedPropertyCount = 3;
// ACT
string result = itemList.ToDelimitedText(delimiter);
var lines = result.Split(Environment.NewLine.ToCharArray());
var properties = lines.First().Split(delimiter.ToCharArray());
var actualPropertyCount = properties.Length;
// ASSERT
Assert.AreEqual(expectedPropertyCount, actualPropertyCount);
}
[TestMethod]
public void ToDelimitedText_RemovesTrailingNewLine_WhenSet()
{
// ARRANGE
var itemList = new List<ComplextObject>
{
new ComplextObject {Id = 1, Name = "Sid", Active = true},
new ComplextObject {Id = 2, Name = "James", Active = false},
new ComplextObject {Id = 3, Name = "Ted", Active = true},
};
const string delimiter = ",";
const bool trimTrailingNewLineIfExists = true;
// ACT
string result = itemList.ToDelimitedText(delimiter, trimTrailingNewLineIfExists);
bool endsWithNewLine = result.EndsWith(Environment.NewLine);
// ASSERT
Assert.IsFalse(endsWithNewLine);
}
[TestMethod]
public void ToDelimitedText_IncludesTrailingNewLine_WhenNotSet()
{
// ARRANGE
var itemList = new List<ComplextObject>
{
new ComplextObject {Id = 1, Name = "Sid", Active = true},
new ComplextObject {Id = 2, Name = "James", Active = false},
new ComplextObject {Id = 3, Name = "Ted", Active = true},
};
const string delimiter = ",";
const bool trimTrailingNewLineIfExists = false;
// ACT
string result = itemList.ToDelimitedText(delimiter, trimTrailingNewLineIfExists);
bool endsWithNewLine = result.EndsWith(Environment.NewLine);
// ASSERT
Assert.IsTrue(endsWithNewLine);
}
#endregion
}
}
Pass each string array collection to this function and this will return a CSV formatted string that you can either save to a large string buffer or write line by line to a file.
C#
public string CSVout(string[] strArray)
{
string sOut = "";
foreach (void s_loopVariable in strArray) {
s = s_loopVariable;
if (s.Contains(","))
s = Strings.Chr(34) + s + Strings.Chr(34);
sOut += s + ",";
}
if (Strings.Right(sOut, 1) == ",")
sOut = Strings.Left(#out, #out.Length - 1);
return sOut;
}
VB.NET:
Function CSVout(strArray() As String) As String
Dim out As String = ""
For Each s In strArray
If s.Contains(",") Then s = Chr(34) + s + Chr(34)
out &= s + ","
Next
If Strings.Right(out, 1) = "," Then out = Strings.Left(out, out.Length - 1)
Return out
End Function

The specified table does not exist[entity]

I have spent hours trying to figure out why my database cannot find the table I have found numerous examples and none have seemed to help. I have created a separate class to handle the database operations so I can use it on multiple pages.
Here is the code
[Table]
public class MatchItem
{
[Column(IsPrimaryKey = true, CanBeNull=false,IsDbGenerated=true)]
public int MatchID { get; set; }
[Column(CanBeNull = false)]
public string MatchNumber { get; set; }
[Column(CanBeNull = false)]
public string EventName { get; set; }
[Column(CanBeNull = false)]
public DateTime Time { get; set; }
[Column(CanBeNull = false)]
public string[] RedTeams { get; set; }
[Column(CanBeNull = false)]
public string[] BlueTeams { get; set; }
[Column(CanBeNull = false)]
public int RedFinal { get; set; }
[Column(CanBeNull = false)]
public int BlueFinal{ get; set; }
}
Here is the Data context
public class MatchDataContext:DataContext
{
public MatchDataContext(string connectionString) :
base(connectionString)
{
}
public Table<MatchItem> Matches
{
get
{
return this.GetTable<MatchItem>();
}
}
}
I made a class so I could use it on multiple pages
public class MatchDBManager
{
private static string connectionString = #"Data Source=isostore:/DB.sdf";
public MatchDBManager()
{
initialize();
}
public void initialize()
{
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
if (Mchdb.DatabaseExists())
{
Console.WriteLine("DB already exists");
}
else
{
Mchdb.CreateDatabase();
Console.WriteLine("DB created");
}
}
}
public void addMatchData(IList<MatchItem> data)
{
//this.clearData();
//initialize();
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
Mchdb.Matches.InsertAllOnSubmit(data);
Mchdb.SubmitChanges();
}
}
public IList<MatchItem> getTeamData(string teamNum)
{
IList<MatchItem> MatchList = null;
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
IQueryable<MatchItem> mchQuery = from mch in Mchdb.Matches where (mch.RedTeams[0] == teamNum || mch.RedTeams[1] == teamNum || mch.RedTeams[2] == teamNum || mch.BlueTeams[0] == teamNum || mch.BlueTeams[1] == teamNum || mch.BlueTeams[2] == teamNum) select mch;
MatchList = mchQuery.ToList();
}
return MatchList;
}
public IList<MatchItem> getEventData(string eventID)
{
IList<MatchItem> MatchList = null;
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
IQueryable<MatchItem> mchQuery = from mch in Mchdb.Matches where mch.Event == eventID select mch;
MatchList = mchQuery.ToList();
}
return MatchList;
}
private void clearData()
{
using (MatchDataContext Mchdb = new MatchDataContext(connectionString))
{
if (Mchdb.DatabaseExists())
{
Mchdb.DeleteDatabase();
}
}
}
}
I have the error The specified table does not exist[Match].
Added here is where I download
public IList<MatchItem> ParseXML(XmlReader reader)
{
//List<string> save = new List<string>();
List<MatchItem> MatchList= new List<MatchItem>();
XElement matchData;
matchData = XElement.Load(reader);
StringBuilder output = new StringBuilder();
int count = 0;
var matches = from item
in matchData.Elements("match")
select item;
foreach (XElement eachmatch in matches)
{
MatchItem mch = new MatchItem();
string Time = ((eachmatch.Element("pubdate").Value).ToString());
mch.EventName = ((eachmatch.Element("event").Value).ToString());
mch.MatchNumber = ((eachmatch.Element("mch").Value).ToString() + (eachmatch.Element("typ").Value).ToString());
string[] RT = { eachmatch.Element("red1").Value.ToString(), eachmatch.Element("red2").Value.ToString(), eachmatch.Element("red3").Value.ToString() };
string[] BT = { eachmatch.Element("blue1").Value.ToString(), eachmatch.Element("blue2").Value.ToString(), eachmatch.Element("blue3").Value.ToString() };
string RF = ((eachmatch.Element("rfin").Value).ToString());
string BF = ((eachmatch.Element("bfin").Value).ToString());
// Time = Time.Substring(0, (Time.IndexOf("+") - 1));
mch.Time = DateTime.Parse(Time);
mch.RedTeams = RT;
mch.BlueTeams = BT;
mch.RedFinal = int.Parse(RF);
mch.BlueFinal= int.Parse(BF);
mch.MatchID = count;
count += 1;
MatchList.Add(mch);
}
return MatchList;
}
This is where I call this method
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
initializeDB();
if (e.Error == null)
{
XmlReader reader = XmlReader.Create(new StringReader(e.Result));
DownloadInfo di = new DownloadInfo();
IList <MatchItem>data= di.ParseXML(reader);
outputer(data);
addData(data.ToList<MatchItem>());
}
else
{
IList<MatchItem> data = getTeamData(strMyTeam);
outputer(data);
}
}
I ended up removing the DatabaseManager class and putting the functions in the main code
Then I output them to the screen here
public void outputer(IList<MatchItem> mch)
{
for (int i = 0; i < mch.Count; i++)
{
Score sc = new Score();
sc.Width = lsbData.Width;
sc.Height = sc.Height;
sc.Time = mch[i].Time.ToString();
sc.Event = mch[i].EventName;
sc.RT = mch[i].RedTeams[0] + " " + mch[i].RedTeams[1] + " " + mch[i].RedTeams[2];
sc.BT = mch[i].BlueTeams[0] + " " + mch[i].BlueTeams[1] + " " + mch[i].BlueTeams[2];
sc.RF = mch[i].RedFinal.ToString();
sc.BF = mch[i].BlueFinal.ToString();
lsbData.Items.Add(sc);
}
}
*note:score is a custom control that works(and worked) before the database code *
I don't see where you actually create a Match Object.
if you have you need to include that code in the question as well. and if you haven't, that would explain why it doesn't exist.
Addition
in order to add Match Objects to a list you will have to create the objects first then add them to the list, I don't think you can create the whole list of objects before creating each individual object.
more Additional Information
the object still needs to be created before you can add items to it. that is what the error is telling you. you don't have the object to insert data into.
Match Table1 = new Match();
this creates a new Match object which allows you to access the pieces of the object and insert data into the object like this
Table1.MatchNumber = 42
you can't add to something to a memory location until you set aside that memory location for that specific person and give it a name.
when you create that class you can add functions and all sorts of fun stuff to it, but you can't use any of it until you have created a Match Object.
you can't add something to a list that doesn't exist, you have to create the Match Object first, then add it to the list

Categories

Resources