|
Hi all,
I want to raise an event with delegates
my code is like this:
delcaration:
public delegate void ButtonClickedDelegate(string path);
public event ButtonClickedDelegate ButtonClicked;
call:
GetData(path);
raise:
private void GetData(string path)
{
try
{
if (ButtonClicked!= null)
ButtonClicked(path);
}
catch
{
}
}
But I am getting ButtonClicked = null
at the line
if (ButtonClicked!= null)
so that
ButtonClicked(path);
is not getting executed....
Do anybody have idea what is the wrong with the code?
|
|
|
|
|
That's because you've just declared a event handler, not created it.
try something like:
ButtonClicked += new System.EventHandler(GetData);
regards
|
|
|
|
|
Hi,
you need to wire a handler to your event, as in ButtonClicked += new ButtonClickedDelegate(handler);
Compare with what Visual Designer adds to myForm.designer.cs when you wire a handler interactively.
Luc Pattyn [Forum Guidelines] [My Articles]
DISCLAIMER: this message may have been modified by others; it may no longer reflect what I intended, and may contain bad advice; use at your own risk and with extreme care.
|
|
|
|
|
Getting 'System.StackOverflowException'
at line
void OnButtonClicked()
{}
when I do
ButtonClicked += OnButtonClicked;
...
void OnButtonClicked(...) {
...
}
|
|
|
|
|
Let me guess: in the OnButtonClicked code, you are raising the ButtonClicked event?
If yes, doing so casue the OnButtonClicked code to be recursively called non-stop, quickly filling the avaliable stack memory.
In your OnButtonClicked, you have to put logic to handle the event, not to raise it.
|
|
|
|
|
Where is the handler to the event?
Guess you are missing that.
|
|
|
|
|
ButtonClicked will be null if there are no subscribers to the event (therefore the delegate's InvocationList is empty).
This example shows you how to do it. The ButtonClicked event here is initiated by the public PerformButtonClicked method being called on a class instance and in turn calling the OnButtonClicked method, but obviously in the real world the OnButtonClicked method would be called by the instance itself on response to a MouseDown or something.
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
TestClass test;
public Form1()
{
InitializeComponent();
test = new TestClass();
test.ButtonClicked += new TestClass.ButtonClickedDelegate(test_ButtonClicked);
test.PerformButtonClicked(@"C:\Windows");
}
void test_ButtonClicked(string path)
{
MessageBox.Show(path);
}
}
public class TestClass
{
public delegate void ButtonClickedDelegate(string path);
public event ButtonClickedDelegate ButtonClicked;
protected virtual void OnButtonClicked(string path)
{
ButtonClickedDelegate handler = ButtonClicked;
if (handler != null)
handler(path);
}
public void PerformButtonClicked(string path)
{
OnButtonClicked(path);
}
}
}
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn) Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia) Why are you using VB6? Do you hate yourself? (Christian Graus)
|
|
|
|
|
|
daffy_2003 wrote: Hi. I just join this community.
Weclome. You may want to read the posting guidelines. 'can anyone help me' does not make a good subject, it doesn't tell anyone what you want.
What tools did the person who asked you to do this task provide ?
Christian Graus
Driven to the arms of OSX by Vista.
"! i don't exactly like or do programming and it only gives me a headache." - spotted in VB forums.
I can do things with my brain that I can't even google. I can flex the front part of my brain instantly anytime I want. It can be exhausting and it even causes me vision problems for some reason. - CaptainSeeSharp
|
|
|
|
|
Christian Graus wrote: What tools did the person who asked you to do this task provide ?
A course syllabus given six weeks ago with the assignment due next week.
only two letters away from being an asset
|
|
|
|
|
Well, I doubt that a course would tell him/her to write code to export to PDF. It sounds more like a rentacoder job gone wrong. If it's a paid job, if he's an employee, then he should run for his life. Either way, if he's new to C#, and has paid work to do this task, it's plain wrong, and it's everything that's wrong with our industry today. But, if he's not the one taking the freelancing work, then he's working for people who are also clueless.
Either way, I was trying to get a feel for his situation before explaining that he needs a PDF library, and to either tell his client to find someone who knows what they are doing, or if he's part of a team, to get out of there as soon as he can.
Christian Graus
Driven to the arms of OSX by Vista.
"! i don't exactly like or do programming and it only gives me a headache." - spotted in VB forums.
I can do things with my brain that I can't even google. I can flex the front part of my brain instantly anytime I want. It can be exhausting and it even causes me vision problems for some reason. - CaptainSeeSharp
|
|
|
|
|
Damn - I thought I was as polite as I could possibly be. He still deleted his post.
Christian Graus
Driven to the arms of OSX by Vista.
"! i don't exactly like or do programming and it only gives me a headache." - spotted in VB forums.
I can do things with my brain that I can't even google. I can flex the front part of my brain instantly anytime I want. It can be exhausting and it even causes me vision problems for some reason. - CaptainSeeSharp
|
|
|
|
|
Hi, is this better compare to the previous one?
The person did not tell me what tools to use except for C# but for the merging of pdf, he said try using iTextSharp.
|
|
|
|
|
OK, so at least they've told you what library to use. I'm confused then why you asked us without saying you wanted to use that library. It bothers me that there are people who are told by their supervisors to do tasks they obviously have no idea how to do, and then sent to try to get someone on the web to do the task for them. If you're new to C#, then you should certainly learn that before you start writing code that people will use, or trying to work with third party libraries. In any case, the documentation for iTextSharp is your best bet, followed by any forums they have. Only because, everyone there USES iTextSharp, and will therefore be able to help you. Some people here may use it, but you sure want to put iTextSharp in your header, and generally explain that's what you're using.
Christian Graus
Driven to the arms of OSX by Vista.
"! i don't exactly like or do programming and it only gives me a headache." - spotted in VB forums.
I can do things with my brain that I can't even google. I can flex the front part of my brain instantly anytime I want. It can be exhausting and it even causes me vision problems for some reason. - CaptainSeeSharp
|
|
|
|
|
Im sorry if i did not mention about it. I just wanna see is there any suggestion to it and not trying to get someone to do the task.
But still, thanks for your advice.
|
|
|
|
|
Well, there's plenty of PDF libraries, but most of them cost money. I don't think there's too many free ones, and I'd never use a free library for a commercial task. If you didn't write the code, and someone paid for it, they should expect better support than you can give by trying to debug a library you did not write.
Christian Graus
Driven to the arms of OSX by Vista.
"! i don't exactly like or do programming and it only gives me a headache." - spotted in VB forums.
I can do things with my brain that I can't even google. I can flex the front part of my brain instantly anytime I want. It can be exhausting and it even causes me vision problems for some reason. - CaptainSeeSharp
|
|
|
|
|
Here is my first attempt at writing a multi-threaded class.
The purpose of this class is to allow you to connect to a remote registry without things going bad if the remote machine doesn't respond. It also holds open remote connections for a predefined period before destroying the connection to allow for reuse.
I'd really like some feedback on the threading. Is it thread safe? Have I made any errors that might make it blow up in certain circumstances?
Many thanks!
using Microsoft.Win32;
using System;
using System.Threading;
using System.Collections.Generic;
namespace JacksTools
{
public class RemoteRegistryHandler
{
private class RegistryStub
{
private RegistryKey _reference;
private int _timeout;
private DateTime _lastAccessed;
public RegistryKey Reference
{
get {
_lastAccessed = System.DateTime.Now;
return _reference;
}
}
public Boolean TimedOut
{
get
{
return (_lastAccessed.AddMilliseconds(_timeout) < System.DateTime.Now);
}
}
public RegistryStub(int timeout, RegistryKey reference)
{
_lastAccessed = System.DateTime.Now;
_timeout = timeout;
_reference = reference;
}
}
Dictionary<String, RegistryStub> _store = new Dictionary<string,RegistryStub>();
private int _timeout;
private Thread _cleaner;
private Boolean _closingDown = false;
private class AttemptGet
{
private String _machineName;
private RegistryHive _hive;
public RegistryKey ResultKey;
public Exception Error;
public void Attempt()
{
try
{
ResultKey = RegistryKey.OpenRemoteBaseKey(_hive, _machineName);
}
catch (Exception e) {
Error = e;
Console.WriteLine("The following exception occured when attempting to connect a remote registry (" + _hive.ToString() + " on " + _machineName + ")\n" +
e.ToString());
}
}
public AttemptGet(String machineName, RegistryHive hive)
{
_machineName = machineName; _hive = hive;
}
}
public RegistryKey GetRemoteKey(String machineName, RegistryHive hive, int timeout)
{
lock (_store)
{
String key = machineName + hive.ToString();
if (_store.ContainsKey(key))
{
if (!_store[key].TimedOut)
{
return _store[key].Reference;
}
else
{
_store.Remove(key);
Console.WriteLine("RemoteRegistryHandler cleaned " + machineName + hive.ToString());
}
}
AttemptGet ag = new AttemptGet(machineName, hive);
Thread attemptThread = new Thread(new ThreadStart(ag.Attempt));
attemptThread.Name = "Attempting connection to registry " + hive.ToString() + " on " + machineName;
attemptThread.IsBackground = true;
attemptThread.Start();
attemptThread.Join(timeout);
RegistryKey reference = ag.ResultKey;
if (attemptThread.IsAlive) throw new TimeoutException();
if (reference == null) throw ag.Error;
RegistryStub newStub = new RegistryStub(_timeout, reference);
_store.Add(key, newStub);
Console.WriteLine("RemoteRegistryHandler added " + key);
if (_store.Count == 1)
{
_cleaner = new Thread(new ThreadStart(cleaner));
_cleaner.Start();
}
return newStub.Reference;
}
}
public void cleaner()
{
while (!_closingDown)
{
try
{
Thread.Sleep(_timeout);
lock (_store)
{
List<String> keys2Del = new List<String>();
foreach (KeyValuePair<String, RegistryStub> pair in _store)
{
if (pair.Value.TimedOut)
{
keys2Del.Add(pair.Key);
}
}
foreach (String key in keys2Del)
{
_store.Remove(key);
Console.WriteLine("RemoteRegistryHandler cleaned " + key);
}
}
if (_store.Count == 0) break;
}
catch (ThreadInterruptedException e)
{
if (_closingDown)
{
foreach (KeyValuePair<String, RegistryStub> pair in _store)
{
Console.WriteLine("RemoteRegistryHandler cleaned " + pair.Key);
}
_store.Clear();
}
}
}
}
public RemoteRegistryHandler(int timeout)
{
_timeout = timeout;
}
public void Close()
{
_closingDown = true;
if (_cleaner != null)
{
try
{
_cleaner.Interrupt();
_cleaner.Join();
}
catch (NullReferenceException e) { }
}
}
}
}
|
|
|
|
|
Just realised that the Cleaner method should be private
|
|
|
|
|
if (_store.Count == 0) break; in cleaner is outside the lock, may be a problem.
|
|
|
|
|
Thank you for the link. I'm now stock here please I need help on this.
SqlCommand myCommand= new SqlCommand("INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)", myConnection);
The values is given me problem. How do I get the value from textbox before it can be inserted into batabase. I have design my form and i need to get information from user through the textbox whenever they click the save button on the form.
Thanks for your help.
Ademola
|
|
|
|
|
Adekolurejo wrote: How do I get the value from textbox before it can be inserted into batabase.
To get the value in the TextBox you use something like this (assuming your TextBox is called myTextBox )
myStringValue = myTextBox.Text;
Your SQL needs a little bit of work too. Try this:
SqlCommand myCommand= new SqlCommand("INSERT INTO table (Column1, Column2) " +
"Values (@firstParam, @secondParam)", myConnection);
myCommand.Parameters.AddWithValue("@firstParam", myStringValue);
myCommadn.Parameters.AddWithValue("@secondParam", myIntValue);
myCommand.ExecuteNonQuery();
The use of parameters means that you are not dangerously concatenating strings which can lead to SQL Injection Attacks.
Man who stand on hill with mouth open wait long time for roast duck to drop in
|
|
|
|
|
Thanks Colins.
this line of code "Values (@firstParam, @secondParam)",
@firstParam will this be the name of the first textbox and @secondParam the name of the second textbox etc.
Also myCommand.Parameters.AddWithValue("@firstParam", myStringValue); myStringValue will be if am getting string from the textbox.
myCommadn.Parameters.AddWithValue("@secondParam", myIntValue); myIntValue will be if am getting intgervalue from the textbox.
Am just learning c# on my own pleas help.
Thanks
Ademola.
|
|
|
|
|
Adekolurejo wrote: this line of code "Values (@firstParam, @secondParam)",
@firstParam will this be the name of the first textbox and @secondParam the name of the second textbox etc.
In the SQL String @firstParam and @secondParam match up with whatever parameters you add to the Parameters collection. This can be anything you define. It doesn't have to be values from user controls. (See the lines with Parameters.AddWithValue)
Adekolurejo wrote: Also myCommand.Parameters.AddWithValue("@firstParam", myStringValue); myStringValue will be if am getting string from the textbox.
myStringValue is just a string value, it doesn't have to come from a control. The database command doesn't know anything about controls (like, for example, a text box). It just knows about data.
You can create a string and populate it with the value from a textbox if that's what you need it to be.
Okay - Let's step back and show the whole thing from text box to database. NOTE: that this example shows everything in one place. This is generally considered poor practice, but as you are only just starting I'll not burden you with the principles of layered archtecture and the single responsiblity principle and so on. (Just be aware they exist and one day you'll have to learn about them)
So, let's say you have a form with two text boxes, one for a name, and one for an age. Lets call them NameTB and AgeTB .
The user can enter information in these text boxes and press a button that addes them to the database.
First, we need to get the data from the text boxes into a form we can use.
string name = NameTB.Text;
int age = Convert.ToInt32(AgeTB.Text);
Since text boxes only deal with strings we have to convert the string into a number (an Int32 - a 32bit integer)
Now, we need to set up the database connection and command in order to insert this. I'll assume you already have a connections string to your database, I've called it myConnectionString for this example.
SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand("INSERT Person(NameField, AgeField) "+
VALUES (@nameParam, @ageParam)", myConnection);
I've now set up the SQL Command with an insert statement. I've assumed there is a table called Person and it has two columns called NameField and AgeField . I'm also going to insert the values via parameters, which I've indicated with @nameParam and @ageParam . SQL Server requires that all parameter names start with an @ symbol. Other databases may vary.
myCommand.Parameters.AddWithValue("@nameParam", name);
myCommand.Parameters.AddWithValue("@ageParam", age);
I've now added the parameters into the SQL command. I've given it each parameter with the value we got earlier. Finally:
myConnection.Open();
myComment.ExecuteNonQuery();
myConnection.Close();
This opens the connection, runs the INSERT statement and closes the connection again. I'm using ExecuteNonQuery because we don't expect any results back from SQL Server. If we were expecting data back (e.g. because we were using a SELECT statement) we could use ExecuteReader (for many rows/columns) or ExecuteScalar (for a single value).
I hope this helps.
Man who stand on hill with mouth open wait long time for roast duck to drop in
|
|
|
|
|
Thank you colins. I think I have to read and understand this before any futher questions.
Ademola
|
|
|
|
|
it seems to me there is no difference between generics Dictionary<> and
SortedList<>.
but since they are defined, there should be some difference.
then what is the difference then?
thanks.
|
|
|
|