Creating an own class and start it - c#

I want my own Class to start but it seems not to be working.
My Class is:
namespace Ts3_Movearound
{
class TS3_Connector
{
public class ccmove : EventArgs
{
public ccmove(int clid, int cid)
{
this.clid = clid;
this.cid = cid;
}
public int clid;
public int cid;
}
public event EventHandler runningHandle;
public event EventHandler stoppedHandle;
public event EventHandler RequestMove;
bool running = true;
public Main()
{
using (QueryRunner queryRunner = new QueryRunner(new SyncTcpDispatcher("127.0.0.1", 25639))) // host and port
{
this.runningHandle(this, new EventArgs());
while (running == true)
{
this.RequestMove(this, new EventArgs());
System.Threading.Thread.Sleep(1000);
}
this.stoppedHandle(this, new EventArgs());
}
Console.ReadLine();
}
}
}
and i call it this way:
private void button1_Click(object sender, EventArgs e)
{
TS3_Connector conn = new TS3_Connector();
conn.runningHandle += new EventHandler(started);
conn.stoppedHandle += new EventHandler(stopped);
}
but it seems that the Class never starts correctly. The runningEvent never gehts fired, also the stopped and the Request. How can i run this Class now?

The lifespan of your conn object ends when button1_Click has returned. You should declare conn in the class scope.
TS3_Connector conn = null;
private void button1_Click(object sender, EventArgs e)
{
conn = new TS3_Connector();
conn.runningHandle += new EventHandler(started);
conn.stoppedHandle += new EventHandler(stopped);
}
TS3_Connector itself does nothing. You should explicitly call main() (please rename the function to something understandable)

Related

C# EventHandler returns null when called

I have a two classes.In one class i am creating and raising an event as follows :
CustomerAdd Class
public class CustomerAdd
{
public delegate void Done(object Sender, EventArgs e);
public event Done ListUpdated;
public void UpdateNewList()
{
//adding items to a generic List<T>,code removed as not relevant to post
//and raising the event afterwards
if (ListUpdated != null)
{
ListUpdated(this, EventArgs.Empty);
}
}
}
MyWindow Class
public class MyWindow
{
private void SaveToDisk()
{
CustomerAdd cuss = new CustomerAdd();
cuss.ListUpdated += new CustomerAdd.Done(DisplayDetails);
cuss.UpdateNewList();
}
private void DisplayDetails()
{
//other codes here
}
}
Now, when i call the SaveToDisk method from MyWIndow class,(as i am subscribing DisplayDetails method to the ListUpDated event) , DisplayDetails is not called. The debugger shows that ListUpdated is null. I have searched for hours and failed to come up with a solution.I followed this link but still ListUpdated is null. Any guidance/help would be highly appreciated.
It works:
using System;
namespace ConsoleApp2
{
class Program
{
public class CustomerAdd1
{
public delegate void Done(object Sender, EventArgs e);
public event Done ListUpdated;
public void UpdateNewList()
{
//adding items to a generic List<T>,code removed as not relevant to post
//and raising the event afterwards
if (ListUpdated != null)
{
ListUpdated(this, EventArgs.Empty);
}
}
}
public class CustomerAdd
{
public void SaveToDisk()
{
CustomerAdd1 cuss = new CustomerAdd1();
cuss.ListUpdated += new CustomerAdd1.Done(DisplayDetails);
cuss.UpdateNewList();
}
private void DisplayDetails(object Sender, EventArgs e)
{
Console.WriteLine("Test");
}
}
static void Main(string[] args)
{
var c = new CustomerAdd();
c.SaveToDisk();
Console.ReadLine();
}
}
}
Try this:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
CustomerReceive cr = new CustomerReceive();
cr.SaveToDisk();
}
}
public class CustomerAdd
{
public delegate void Done(object Sender, EventArgs e);
public event Done ListUpdated;
public void UpdateNewList()
{
//adding items to a generic List<T>,code removed as not relevant to post
//and raising the event afterwards
if (ListUpdated != null)
{
ListUpdated.Invoke(this, EventArgs.Empty);
}
}
}
public class CustomerReceive
{
public void SaveToDisk()
{
CustomerAdd cuss = new CustomerAdd();
cuss.ListUpdated += new CustomerAdd.Done(DisplayDetails);
cuss.UpdateNewList();
}
private void DisplayDetails(object Sender, EventArgs e)
{
int k = 0;
}
}
}
You need to do a good read on delegates and events because this is not working when there are more listeners

Create EventHandler and listen to Event from another class

I've created event as bellow and want to listen to it and execute method in another class when it fires
but saveEvent always comes to be null and it doesn't fire
I don't know what I've missed
here's my first class has button
internal partial class OpenSaveReportWizardForm : Form
{
public event EventHandler saveEvent;
private void saveButton_Click(object sender, EventArgs e)
{
saveEvent?.Invoke(this, e);
}
}
and here's the second class where I want to listen to saveEvent
internal class Database
{
public Database()
{
Program._wizardForm.saveEvent += (sender, e) => HandleSaveMethod( );
}
public void HandleSaveMethod()
{
// do something
}
here's where I open the form
internal class Program
{
public static OpenSaveReportWizardForm _wizardForm;
private static void Main()
{
OpenFileCommandHandler();
}
void OpenFileCommandHandler()
{
_wizardForm = new OpenSaveReportWizardForm( );
_wizardForm.ShowDialog();
}
}
Because you disposed wizardForm, after that event is cleared.
You should write next code:
internal class Database
{
private bool _isDisposed;
private OpenSaveReportWizardForm _wizardForm;
public Database()
{
_wizardForm = new OpenSaveReportWizardForm(m_Opening,m_ConnectionProperties,m_ColumnProperties))
_wizardForm.saveEvent += (sender, e) => HandleSaveMethod( );
}
public void HandleSaveMethod()
{
// do something
}
public void Dispose()
{
if(_isDisposed)
return;
_isDisposed = true;
_wizardForm.saveEvent -= HandleSaveMethod;
_wizardForm.Dispose();
}

How to go back to the previous directory using ftp web request via button back in c# winform?

I am using c# Windows Form Application and ftpWebRequest, I am doing a directory listing. I have a listbox that will display folders, by using the event DoubleClick in my listbox, the double clicked folder or item in my listbox will show its content. And now my problem is I don't know how to go back to the previous directory by using back button.
Here is my Code File:
namespace myFTPClass
{
public class myFTP
{
public string user;
public string pass;
public delegate void cThread1(string thread1);
public event EventHandler EH;
public List<string> myDIR = new List<string>();
public void getDirectoryList(string getDirectory)
{
try
{
FtpWebRequest fwr = FtpWebRequest.Create(getDirectory) as FtpWebRequest;
fwr.Credentials = new NetworkCredential(user, pass);
fwr.UseBinary = true;
fwr.UsePassive = true;
fwr.KeepAlive = true;
fwr.Method = WebRequestMethods.Ftp.ListDirectory;
StreamReader sr = new StreamReader(fwr.GetResponse().GetResponseStream());
while (!sr.EndOfStream)
{
myDIR.Add(sr.ReadLine());
}
}
catch(Exception we)
{
myDIR.Clear();
string msg = we.Message;
}
}
void myCallBackMethod(IAsyncResult ar)
{
cThread1 myThread = (cThread1)((System.Runtime.Remoting.Messaging.AsyncResult)ar).AsyncDelegate;
myThread.EndInvoke(ar);
if (EH != null) EH(this, null);
}
public void Async_getDirectoryList(string dir)
{
AsyncCallback ac = new AsyncCallback(myCallBackMethod);
cThread1 myThread = new cThread1(getDirectoryList);
myThread.BeginInvoke(dir, ac, null);
}
}
}
And Here is my Form1:
namespace my_ftp_v0._01
{
public partial class Form1 : Form
{
myFTP ftp = new myFTP();
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
btn_connect.Click += new EventHandler(btn_connect_Click);
listBox1.DoubleClick += new EventHandler(listBox1_DoubleClick);
btn_back.Click += new EventHandler(btn_back_Click);
ftp.EH += new EventHandler(ftp_EH);
}
void btn_back_Click(object sender, EventArgs e)
{
}
void listBox1_DoubleClick(object sender, EventArgs e)
{
string forward = "ftp://127.0.0.1/" + listBox1.SelectedItem.ToString();
listBox1.Items.Clear();
ftp.myDIR.Clear();
ftp.Async_getDirectoryList(forward);
}
void Form1_Load(object sender, EventArgs e)
{
txt_dir.Text = "ftp://127.0.0.1/";
txt_pass.PasswordChar = '‡';
}
void ftp_EH(object sender, EventArgs e)
{
if (InvokeRequired)
{
EventHandler eh = new EventHandler(ftp_EH);
this.Invoke(eh, new object[] { sender, e });
return;
}
for (int i = 0; i < ftp.myDIR.Count; i++)
{
listBox1.Items.Add(ftp.myDIR[i]);
}
}
void btn_connect_Click(object sender, EventArgs e)
{
ftp.Async_getDirectoryList(txt_dir.Text);
ftp.user = txt_user.Text;
ftp.pass = txt_pass.Text;
}
}
}
Move your SetDirectoryList to its own method
Add a Stack object to your class to track your requests
When the user double clicks add the request to the stack and then set the directory.
When the user hits the back
button, check if the stack has a request, if it does, pop it off and
call the set directory method.
Something like this...
public partial class Form1 : Form
{
myFTP ftp = new myFTP();
Stack _requestStack = new Stack();//Stack to store requests
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
btn_connect.Click += new EventHandler(btn_connect_Click);
listBox1.DoubleClick += new EventHandler(listBox1_DoubleClick);
btn_back.Click += new EventHandler(btn_back_Click);
ftp.EH += new EventHandler(ftp_EH);
}
void btn_back_Click(object sender, EventArgs e)
{
if(_requestStack.Count > 0)
{
string directoryPath = (string)_requestStack.Pop();
SetDirectoryList(directoryPath);
}
}
void listBox1_DoubleClick(object sender, EventArgs e)
{
string directoryPath = listBox1.SelectedItem.ToString();
_stack.Push(directoryPath);
SetDirectoryList(directoryPath);
}
void SetDirectoryList(string directoryPath)
{
string forward = "ftp://127.0.0.1/" + directoryPath;
listBox1.Items.Clear();
ftp.myDIR.Clear();
ftp.Async_getDirectoryList(forward);
}
void btn_back_Click(object sender, EventArgs e)
{
create.server = create.server.TrimEnd('/');
create.server = create.server.Remove(create.server.LastIndexOf('/')+1);
listBox1.Items.Clear();
ftp.myDIR.Clear();
ftp.Async_getDirectoryList("");
}
I've already done this code to my back button and it works properly.

Object does not create when using one as global variable

I have wrapper class over Thread:
public class ThreadWrapper
{
private bool Terminated = false;
private string threadName;
private Thread _thread;
public bool needToTerminate
{
get
{
lock (this)
{
return Terminated;
}
}
}
public string ThreadName
{
get
{
lock (this)
{
return threadName;
}
}
}
// for override constructor in derived classes
public ThreadWrapper()
{
}
public ThreadWrapper(string threadName)
{
this.threadName = threadName;
}
public virtual void Run()
{
}
public virtual void Terminate()
{
lock (this)
{
Terminated = true;
}
}
public void Start()
{
lock (this)
{
if (_thread == null)
{
_thread = new Thread(Run);
_thread.Start();
}
}
}
}
Then i create derived class from ThreadWrapper:
public delegate void ProcessMessageDelegate(string message);
public class Reader : ThreadWrapper
{
private ProcessMessageDelegate ProcessMessage;
public Reader(ProcessMessageDelegate processMessage)
: base()
{
this.ProcessMessage = processMessage;
}
public override void Run()
{
// Do something
}
}
Also i have Form with two buttons. The first button for start thread, the second button for "self-terminate" thread.
public partial class MainForm : Form
{
private MyReader Reader;
public MainForm()
{
InitializeComponent();
}
// real method for delegate
private void ProcessMessage(string message)
{
// add line to RichEdit
this.AddSpRRecordLog(message);
}
private void buttonRunTest_Click(object sender, EventArgs e)
{
if (MyReader == null)
{
MessageBox.Show("Wrong!");
return;
}
MyReader.Start();
}
private void buttonStopTest_Click(object sender, EventArgs e)
{
if (MyReader == null)
{
MessageBox.Show("Wrong!");
return;
}
MyReader.Terminate();
}
private void MainForm_Load(object sender, EventArgs e)
{
Reader MyReader = new Reader(new ProcessMessageDelegate(ProcessMessage));
}
If i use this way (create MyReader on FormLoad event) - MyReader does not create. If i create read in buttonRunTest_Click then everything is ok, but in this case i can't terminate MyReader.
This declares a local variable called MyReader that hides the MyReader field:
private void MainForm_Load(object sender, EventArgs e)
{
Reader MyReader = new Reader(new ProcessMessageDelegate(ProcessMessage));
}
Instead, just assign to the field:
private void MainForm_Load(object sender, EventArgs e)
{
MyReader = new Reader(new ProcessMessageDelegate(ProcessMessage));
}
(Incidentally, this isn't a global variable in the conventional sense - if another instance of MainForm is created, it would have its own independent MyReader field)

WinForm events in another class .NET2 Simplify delegate

Any way to make this working code simpler ie the delegate { }?
public partial class Form1 : Form
{
private CodeDevice codeDevice;
public Form1()
{
InitializeComponent();
codeDevice = new CodeDevice();
//subscribe to CodeDevice.ConnectionSuccessEvent and call Form1.SetupDeviceForConnectionSuccessSate when it fires
codeDevice.ConnectionSuccessEvent += new EventHandler(SetupDeviceForConnectionSuccessState);
}
private void SetupDeviceForConnectionSuccessState(object sender, EventArgs args)
{
MessageBox.Show("It worked");
}
private void button1_Click(object sender, EventArgs e)
{
codeDevice.test();
}
}
public class CodeDevice
{
public event EventHandler ConnectionSuccessEvent = delegate { };
public void ConnectionSuccess()
{
ConnectionSuccessEvent(this, new EventArgs());
}
public void test()
{
System.Threading.Thread.Sleep(1000);
ConnectionSuccess();
}
}
WinForm event subscription to another class
How to subscribe to other class' events in c#?
If don't think you could simplyfy:
public event EventHandler ConnectionSuccessEvent = delegate { }
even in c#3 + you could only do
public event EventHandler ConnectionSuccessEvent = () => { }
However you could simplify
codeDevice.ConnectionSuccessEvent += new EventHandler(SetupDeviceForConnectionSuccessState);
to
codeDevice.ConnectionSuccessEvent += SetupDeviceForConnectionSuccessState;

Categories