|
Hi,
Having a class with parent child relationships is quite common (I think), and I normally traverse such trees using recursion.
Class looks like this:
public class Product {
public List<Product> Parents {get; set;}
public List<Product> Children {get; set;}
public string Name {get; set;}
public override string ToString() { return Name; }
}
Recursion will look like this:
public void Dump(Product p) {
Console.WriteLine(p.ToString());
foreach (var child in p.Children)
Dump(child);
}
However, I was told by someone before that using threads will be faster and less expensive.
Can anyone send me a sample code of how to do this? I'm thinking that I should simply change (1) to a ParameterizedThreadStart ... but maybe there's a better practice?
Thanks in advance.
Rafferty
|
|
|
|
|
In fact, the person that told you this does not know the final step of your application or he tried to impress you
You may have multiple threads in order to travers the tree, but in your case, the problem will be the output (Console.Writeline(....)) which is thread safe, you will have a lock in order to block multiple threads to access the output buffer.
So, except if you are sure that you have a multiple core, in order millions of data (but in this case do not use the Console), I advise you to stay thread safe (1 thread and this one will catch the maximum of CPU) or otherwise you wil have a timce slice handling to do and lock/unlock to manage.
You should have a good start with:
Generic Background Worker[^]
Good luck
|
|
|
|
|
can anyone check this code and tell us what is worring with it ?thanks
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static List<Contact> myContact=new List<Contact>();
struct Contact
{
public int ContactID;
public string FirstName;
public string Surname;
public string Email;
}
static void createMenu()
{
Console.Clear();
Console.WriteLine("===============================");
Console.WriteLine("* *");
Console.WriteLine("* Contact Management Solution *");
Console.WriteLine("* *");
Console.WriteLine("* 1. New Contact *");
Console.WriteLine("* 2. Edit Contact *");
Console.WriteLine("* 3. Remove Contact *");
Console.WriteLine("* 4. View All Contacts *");
Console.WriteLine("* X. Exit *");
Console.WriteLine("* *");
Console.WriteLine("===============================");
}
static void Main(string[] args)
{
string strUserSelect;
do
{
createMenu();
strUserSelect = Console.ReadLine();
if (strUserSelect == "1")
{
NewContact();
}
else if (strUserSelect == "2")
{
EditContact();
}
else if (strUserSelect == "3")
{
RemoveContact();
}
else if (strUserSelect == "4")
{
ViewAllContacts();
}
} while (strUserSelect.ToUpper() != "X");
SaveToFile();
}
static void LoadContacts()
{
string strLineIn;
string[] strArrayIn;
Contact ContactIn;
StreamReader Sr = new StreamReader("c:\\Contacts.txt");
while (!Sr.EndOfStream)
{
strLineIn = Sr.ReadLine();
strArrayIn = strLineIn.Split(',');
ContactIn.ContactID = int.Parse(strArrayIn[0]);
ContactIn.FirstName = strArrayIn[1];
ContactIn.Surname = strArrayIn[2];
ContactIn.Email = strArrayIn[3];
myContact.Add(ContactIn);
}
Sr.Close();
}
static void NewContact()
{
try
{
Contact ContactIn;
Console.Write("Contact ID : ");
ContactIn.ContactID = int.Parse(Console.ReadLine());
Console.Write("First Name : ");
ContactIn.FirstName = Console.ReadLine();
Console.Write("Sure Name : ");
ContactIn.Surname = Console.ReadLine();
Console.Write(" Email : ");
ContactIn.Email = Console.ReadLine();
myContact.Add(ContactIn);
Console.WriteLine("Contact has been saved successfully...");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
static void EditContact()
{
try
{
Contact ContactIn;
Console.Write ("Contact ID :");
int ContactID=int.Parse(Console.ReadLine());
ContactIn =myContact.Find(delegate(Contact Con) { return Con.ContactID.Equals(ContactID); });
if (ContactID != 0)
{
myContact.Remove(ContactIn);
Console.Write("First Name : ");
ContactIn.FirstName = Console.ReadLine();
Console.Write("Sure Name : ");
ContactIn.Surname = Console.ReadLine();
Console.Write(" Email : ");
ContactIn.Email = Console.ReadLine();
myContact.Add(ContactIn);
Console.WriteLine("Contact has been updated...");
}
else
{
Console.WriteLine("Contact not found...");
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
static void RemoveContact()
{
try
{
Console.Write("Contact ID :");
int ContactID = int.Parse(Console.ReadLine());
myContact.RemoveAll(delegate(Contact Con) { return Con.ContactID.Equals(ContactID); });
Console.WriteLine("Contact has been updated...");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
static void ViewAllContacts()
{
for(int i=0;i<myContact.Count;i++)
Console.WriteLine("{0},{1},{2},{3}", myContact[i].ContactID, myContact[i].FirstName, myContact[i].Surname, myContact[i].Email);
Console.ReadLine();
}
static void SaveToFile()
{
File.Delete("C:\\Contacts.txt");
StreamWriter Sw=new StreamWriter("C:\\Contacts.txt");
myContact.ForEach(delegate(Contact Con)
{ Sw.WriteLine("{0},{1},{2},{3}", Con.ContactID, Con.FirstName, Con.Surname, Con.Email); });
Sw.Flush();
Sw.Close();
}
}
}
Console.WriteLine(" Email :");
ContactIn.Email = Console.ReadLine());
myContact.Add(ContactIn);
Console.WriteLine("Contact has saved successfully...");
Console.ReadLine();
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
static void EditContact()
{
try
{
Contact ContactIn;
Console.Write ("Contact ID :");
int ContactID=int.Parse(Console.ReadLine());
ContactIn =myContact.Find(delegate(Contact Con) { return Con.ContactID.Equals(ContactID); });
if (ContactID != 0)
{
myContact.Remove(ContactIn);
Console.Write("First Name : ");
ContactIn.FirstName = Console.ReadLine();
Console.Write("Sure Name : ");
ContactIn.Surname = Console.ReadLine();
Console.Write(" Email : ");
ContactIn.Email = Console.ReadLine();
myContact.Add(ContactIn);
Console.WriteLine("Contact has been updated...");
}
else
{
Console.WriteLine("Contact not found...");
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
static void RemoveContact()
{
try
{
Console.Write("Contact ID :");
int ContactID = int.Parse(Console.ReadLine());
myContact.RemoveAll(delegate(Contact Con) { return Con.ContactID.Equals(ContactID); });
Console.WriteLine("Contact has been updated...");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
static void ViewAllContacts()
{
for(int i=0;i<myContact.Count;i++)
Console.WriteLine("{0},{1},{2},{3}", myContact[i].ContactID, myContact[i].FirstName, myContact[i].Surname, myContact[i].Email);
Console.ReadLine();
}
static void SaveToFile()
{
File.Delete("C:\\Contacts.txt");
StreamWriter Sw=new StreamWriter("C:\\Contacts.txt");
myContact.ForEach(delegate(Contact Con)
{ Sw.WriteLine("{0},{1},{2},{3}", Con.ContactID, Con.FirstName, Con.Surname, Con.Email); });
Sw.Flush();
Sw.Close();
}
}
}
|
|
|
|
|
Instead of just pasting your entire program and asking for someone to debug it for you, narrow down the code to the lines that are relavent to the problem, describe the error, and then maybe someone can help you.
|
|
|
|
|
will do that . thanks. im new to this . thanks again
|
|
|
|
|
im very new to this and i have managed to write this code but it doesn't work!!. anyone can help?
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static List<Contact> myContact=new List<Contact>();
struct Contact
{
public int ContactID;
public string FirstName;
public string Surname;
public string Email;
}
static void createMenu()
{
Console.Clear();
Console.WriteLine("===============================");
Console.WriteLine("* *");
Console.WriteLine("* Contact Management Solution *");
Console.WriteLine("* *");
Console.WriteLine("* 1. New Contact *");
Console.WriteLine("* 2. Edit Contact *");
Console.WriteLine("* 3. Remove Contact *");
Console.WriteLine("* 4. View All Contacts *");
Console.WriteLine("* X. Exit *");
Console.WriteLine("* *");
Console.WriteLine("===============================");
}
static void Main(string[] args)
{
string strUserSelect;
do
{
createMenu();
strUserSelect = Console.ReadLine();
if (strUserSelect == "1")
{
NewContact();
}
else if (strUserSelect == "2")
{
EditContact();
}
else if (strUserSelect == "3")
{
RemoveContact();
}
else if (strUserSelect == "4")
{
ViewAllContacts();
}
} while (strUserSelect.ToUpper() != "X");
SaveToFile();
}
static void LoadContacts()
{
string strLineIn;
string[] strArrayIn;
Contact ContactIn;
StreamReader Sr = new StreamReader("c:\\Contacts.txt");
while (!Sr.EndOfStream)
{
strLineIn = Sr.ReadLine();
strArrayIn = strLineIn.Split(',');
ContactIn.ContactID = int.Parse(strArrayIn[0]);
ContactIn.FirstName = strArrayIn[1];
ContactIn.Surname = strArrayIn[2];
ContactIn.Email = strArrayIn[3];
myContact.Add(ContactIn);
}
Sr.Close();
}
static void NewContact()
{
try
{
Contact ContactIn;
Console.Write("Contact ID : ");
ContactIn.ContactID = int.Parse(Console.ReadLine());
Console.Write("First Name : ");
ContactIn.FirstName = Console.ReadLine();
Console.Write("Sure Name : ");
ContactIn.Surname = Console.ReadLine();
Console.Write(" Email : ");
ContactIn.Email = Console.ReadLine();
myContact.Add(ContactIn);
Console.WriteLine("Contact has saved successfully...");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
static void EditContact()
{
try
{
Contact ContactIn;
Console.Write ("Contact ID :");
int ContactID=int.Parse(Console.ReadLine());
ContactIn =myContact.Find(delegate(Contact Con) { return Con.ContactID.Equals(ContactID); });
if (ContactID != 0)
{
myContact.Remove(ContactIn);
Console.Write("First Name : ");
ContactIn.FirstName = Console.ReadLine();
Console.Write("Sure Name : ");
ContactIn.Surname = Console.ReadLine();
Console.Write(" Email : ");
ContactIn.Email = Console.ReadLine();
myContact.Add(ContactIn);
Console.WriteLine("Contact has been updated...");
}
else
{
Console.WriteLine("Contact not found...");
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
static void RemoveContact()
{
try
{
Console.Write("Contact ID :");
int ContactID = int.Parse(Console.ReadLine());
myContact.RemoveAll(delegate(Contact Con) { return Con.ContactID.Equals(ContactID); });
Console.WriteLine("Contact has been updated...");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
static void ViewAllContacts()
{
for(int i=0;i<myContact.Count;i++)
Console.WriteLine("{0},{1},{2},{3}", myContact[i].ContactID, myContact[i].FirstName, myContact[i].Surname, myContact[i].Email);
Console.ReadLine();
}
static void SaveToFile()
{
File.Delete("C:\\Contacts.txt");
StreamWriter Sw=new StreamWriter("C:\\Contacts.txt");
myContact.ForEach(delegate(Contact Con)
{ Sw.WriteLine("{0},{1},{2},{3}", Con.ContactID, Con.FirstName, Con.Surname, Con.Email); });
Sw.Flush();
Sw.Close();
}
}
}
|
|
|
|
|
please read the "how to ask a question" text on this page, then edit your message accordingly.
describe the problem, and show relevant code using PRE tags. Only then will you get help.
|
|
|
|
|
Luc Pattyn wrote: please read the "how to ask a question" text on this page
Just that text! Not the the entire post, right.
50-50-90 rule: Anytime I have a 50-50 chance of getting something right, there's a 90% probability I'll get it wrong...!!
|
|
|
|
|
im sorry im totaly new to this . will try to resend it again.
|
|
|
|
|
bassam eshteba wrote: im totaly new to this
and that is why there is a "How to get an answer to your question" message a few lines up from here. Read it. Follow it.
bassam eshteba wrote: will try to resend it again.
that does not help unless you learn how to post questions first.
|
|
|
|
|
Hi All
I'm trying to use HTML Agility Pack to get the description text from inside the:
<meta name="description" content="**this is the text i want to extract and store in a string**" />
And someone a little while ago suggested I use HTMLAgilityPack. But I don't know how to use it, and the documentation for it that I've found (including the docs contained in the downloads) all have invalid links and therefor cannot view the documentation.
Can somebody please help me solve this?
Regards,
Jason
|
|
|
|
|
I seem to be able to view the documentation without problems.
/ravi
|
|
|
|
|
Background: C# ASP.Net website
I have a class in my code and about 30 classes derived from it. From a bunch of different points in my code I want to be able to get an instance of one of those derived classes using a string signature. Currently I have a hashtable set up where I put the signature in as the key and an instance of the class as the data. It works great. However, it requires that I have to go to the base class's data initializer and explicitly add the linkage for the signature to the class instance into the hashtable every time I add a new class and this seriously bugs me, especially when I forget to do it and then sadness occurs.
Question: Is there a way, either in the derived classes or as part of the base class, to fire off some code that would add the linkage itself thus removing the need for me to write them out explicitly each time? I had thought that a static constructor would do the job (each derived class has a static constructor that adds the linkage to the hashtable), but apparently in C# static constructors don't fire until you try to instantiate a class the first time (I have tested this and found it to be true), which kind of defeats the purpose for me. In C++ I accomplished this using some wicked nasty global macro stuff at the top of each of the derived class's source file, but the engineer in me tells me there has to be a better way.
Stripped code (the actual classes are hundreds of lines big) for anyone who needs it below. The getClassBySig() function is the sticking point. I need to be able to retrieve a class instance based solely on a string. I don't want to use a giant switch() block to do so, but the current solution isn't a whole lot better from a maintainability standpoint.
public class BaseClass
{
public BaseClass()
{
}
public static void addLink(string pSig, BaseClass pInstance)
{
}
public static void init()
{
addLink("link1", new DerivedClass1());
addLink("link2", new DerivedClass2());
}
public static BaseClass getClassBySig(string pSig)
{
}
}
Thank you very much for any insight you can offer!
|
|
|
|
|
The base class shouldn't know about the derived classes.
And don't use a HashTable unless you're stuck with .net v1.x
I would likely start by writing a static class that would take the place of the static parts of the base class:
public static class Manager
{
private static readonly System.Collections.Generic.Dictionary<string,BaseClass> dic ;
static Manager
(
)
{
dic = new ...
dic [ "link1" ] = new DerivedClass1() ;
...
}
public static BaseClass
this
[
string Key
]
{
get { return ( dic [ Key ] ) ; }
}
}
(Not tested.)
Edit:
KnyteHawkk wrote: retrieve a class instance based solely on a string
I'd prefer to use an enumeration, but then you have to maintain the enumeration as well. Ideally you could use an Attribute to associate a derived class with an enumerated value and then the manager's constructor can fill its Dictionary from the enumeration. Write a derived class, add it to the enumeration, and the manager gets it automatically. The manager could also be made generic.
Further edit:
As soon as I posted it I began to suspect that static classes can't have indexers, and indeed it seems they can't. I have no idea why, maybe in a future version they will be able to.
|
|
|
|
|
Agreed on all points, but that doesn't appear to solve the issue of needing to hand-code each initialization line, which is the true issue I'm trying to solve. Thoughts?
|
|
|
|
|
I'm still thinking about it. Did you read my edit?
|
|
|
|
|
replied before you edited, checking it out now
|
|
|
|
|
You could always delve into reflection... It's a bit hefty, but would only have to happen once.
Iterate through every class in the assembly, filtering out just those that inherit from the base class. Have protected virtual properties that return everything you have to add to the table. Add 'em all in...
And just call that process the first time you do a getClassBySig (Only if it's not already initialized).
If you prefer, you can store a pointer to the constructor instead of an instance of the object for each entry in the dictionary.
EDIT:
To clarify, you would use System.Reflection.Assembly.GetExecutingAssembly().GetTypes() to fetch all of the available types... For each, check IsSubclassOf(typeof(BaseClass)) , then for each type that passes, GetConstructor() .
|
|
|
|
|
I suppose they may not all be in the same Assembly. Plus that seems a bit unwieldy for an ASP page.
|
|
|
|
|
True... Maybe there'd have to be a way to register each assembly with it, so it could crawl each for types. I'm not very familiar with ASP-specific issues, as I generally develop for the desktop, so can't speak to that.
|
|
|
|
|
Ian Shlasko wrote: I generally develop for the desktop
I mostly do Windows Services and batch processing so time spent in application start-up initialization isn't generally a concern.
My understanding of ASP.net pages is that they start and exit very quickly so you don't want to keep initializing a bunch of stuff (especially via Reflection) that takes a lot of time and doesn't even get used. ASP-folk: please correct me if I'm wrong.
I'll have to consider lazy-loading as I ponder this thread further.
|
|
|
|
|
OK, you asked for it... (or maybe you didn't, I don't care, thanks for the challenge anyway)
I now have a lazy-instantiating, generic, enum/attribute-based instance manager with caching.
There is a bunch of Reflection, but it doesn't get performed unless it's requested and then the results are cached for future use.
The main down-side is that Attributes can't be generic and the types of parameters for Attribute constructors is limited.
The result is that you can write a family of business classes and attach instances of them to enumerated values via an Attribute:
public enum DoerRegistry
{
[DoSomethingAttribute( typeof(Yell) , "More, more, more" )]
Rebel
,
[DoSomethingAttribute( typeof(Yell) , "Hey, you" )]
Pink
,
[DoSomethingAttribute( typeof(Whisper) , "Mary" )]
Wind
,
Whatever
}
Ideally, the Attribute could be generic:
[DoSomethingAttribute<Whisper>( "Mary" )]
Another possibility would be if the constructor could accept the instance directly:
[DoSomethingAttribute( new Whisper ( "Mary" ) )]
Although that wouldn't allow for lazy-instantiation.
Yet a third possibility is for the business class to be the Attribute, but I don't think that's a very good design.
You then pass that enumeration to the manager and access the various business class instances with its indexer:
ValueMapManager<DoerRegistry,DoSomethingAttribute,IDoSomething> manager =
new ValueMapManager<DoerRegistry,DoSomethingAttribute,IDoSomething>() ;
manager [ DoerRegistry.Wind ].DoWhatYouDoBest() ;
IDoSomething doer ;
doer = manager [ DoerRegistry.Rebel ] ;
doer.DoWhatYouDoBest() ;
It takes a bit of code to do this, but most of it can be shared among whatever projects/applications require it. The only project-specific code is the classes you need and the enumeration. The interfaces, Attribute, and Manager shouldn't require maintenance.
If this looks like something that you may find useful, let me know and I'll post the code.
|
|
|
|
|
Hi all, I am some graph using zedgraph. I am having problems with any graph labeling Xaxis with 24 hour time.
(i.e am 12, 2,.....12 , 1,2 ,3 .......12 pm)
I am using this site[^]
Basically my question is how to change xaxis label.
thanks
|
|
|
|
|
I don't know the first thing about ZedGraph, however a simple search on the site you provided the link for led to this[^] in 16 seconds. Does that help?
|
|
|
|
|
thaks for your reply, I looked at it but Having some trouble to figure it out. i will look into it more.
thanks
|
|
|
|
|