11 Replies - 4723 Views - Last Post: 22 February 2008 - 02:53 PM Rate Topic: -----

#1 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Console to Windows Application

Post icon  Posted 12 February 2008 - 07:45 AM

Hi,

I'm just beginning to learn the C# language, but i've already some 3 years experience with Java (although i'm not an expert) so i tried an example of my book.

It's a server application waiting for a request... it's made for a console application:

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Text;

namespace Chatserver
{
	class Program
	{
		static void Main(string[] args)
		{
			Encoding ASCII = Encoding.ASCII;
			// Een listener creŽren op poort 8227
			TcpListener myListener = new TcpListener(8227);
			// Start de listener
			myListener.Start();
			Console.WriteLine("Wacht op een aanvraag");
			// Programmablocks op Accept() tot een client verbinding maakt
			Socket mySocket = myListener.AcceptSocket();
			Console.WriteLine("Een aanvraag ontvangen");
			Byte[] RecvBytes = new Byte[256];
			// Ontvang de page en doorloop de lus tot alle bytes ontvangen zijn
			Int32 bytes = mySocket.Receive(RecvBytes, RecvBytes.Length, 0);
			string s = ASCII.GetString(RecvBytes, 0, bytes);
			if (s == "GetDate")
			{
				// De actuele datum en tijd ophalen
				DateTime now = DateTime.Now;
				String strDateLine = now.ToShortDateString() + " " + now.ToLongTimeString();
				// Converteer naar een byte-array en verstuur
				Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine.ToCharArray());
				mySocket.Send(byteDateLine, byteDateLine.Length, 0);
			}
			else
			{
				Console.WriteLine("Onbekende opdracht: {0}", s);
			}
			myListener.Stop();
		}
	}
}



My problem now is: I wanted to create the same in a Windows Application, so the text it normally prints in the console, it then can print in a textbox (in the form).

I've tried different things, but it didn't work... tried to use the code in form1.cs, no error, but somehow i didn't see the form when i started it?

btw, i use Microsoft Visual C# 2005 Express Edition.

Is This A Good Question/Topic? 0
  • +

Replies To: Console to Windows Application

#2 killnine  Icon User is offline

  • D.I.C Head

Reputation: 19
  • View blog
  • Posts: 161
  • Joined: 12-February 07

Re: Console to Windows Application

Posted 12 February 2008 - 09:55 AM

View Postnbarten, on 12 Feb, 2008 - 07:45 AM, said:

Hi,

I'm just beginning to learn the C# language, but i've already some 3 years experience with Java (although i'm not an expert) so i tried an example of my book.

It's a server application waiting for a request... it's made for a console application:

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Text;

namespace Chatserver
{
	class Program
	{
		static void Main(string[] args)
		{
			Encoding ASCII = Encoding.ASCII;
			// Een listener creŽren op poort 8227
			TcpListener myListener = new TcpListener(8227);
			// Start de listener
			myListener.Start();
			Console.WriteLine("Wacht op een aanvraag");
			// Programmablocks op Accept() tot een client verbinding maakt
			Socket mySocket = myListener.AcceptSocket();
			Console.WriteLine("Een aanvraag ontvangen");
			Byte[] RecvBytes = new Byte[256];
			// Ontvang de page en doorloop de lus tot alle bytes ontvangen zijn
			Int32 bytes = mySocket.Receive(RecvBytes, RecvBytes.Length, 0);
			string s = ASCII.GetString(RecvBytes, 0, bytes);
			if (s == "GetDate")
			{
				// De actuele datum en tijd ophalen
				DateTime now = DateTime.Now;
				String strDateLine = now.ToShortDateString() + " " + now.ToLongTimeString();
				// Converteer naar een byte-array en verstuur
				Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine.ToCharArray());
				mySocket.Send(byteDateLine, byteDateLine.Length, 0);
			}
			else
			{
				Console.WriteLine("Onbekende opdracht: {0}", s);
			}
			myListener.Stop();
		}
	}
}



My problem now is: I wanted to create the same in a Windows Application, so the text it normally prints in the console, it then can print in a textbox (in the form).

I've tried different things, but it didn't work... tried to use the code in form1.cs, no error, but somehow i didn't see the form when i started it?

btw, i use Microsoft Visual C# 2005 Express Edition.



I would do this.

1) Start a new solution as a C# Windows Application. This will give you a program.cs and a form1.cs. Put all the code you had above in your form1.cs.

2) Go into the [Design] portion of your windows form and add a text box. Write down what its name is (probably textbox1)

3) Now, any time you see Console.WriteLine(), you are going to want to do something like

textBox1.Text = "What you want";
textBox1.Text += " This appends to your last line";
textBox1.Text += Environment.NewLine; //is the same as a line break



See where that gets you and report back. I think the reason you don't see your form appear is because you never run the routines necessary to do so. When you create a new Windows Application solution, it creates a bunch of initialization routines in the program.cs portion of the project that makes the form appear on startup. If you just added a form to a console project, it wont have the necessary methods yet.

This post has been edited by killnine: 12 February 2008 - 09:57 AM

Was This Post Helpful? 0
  • +
  • -

#3 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: Console to Windows Application

Posted 12 February 2008 - 10:28 AM

I did that already :S unfortunately as i said, it didn't work out. The form just won't show up, but it gives no errors.
Was This Post Helpful? 0
  • +
  • -

#4 Jayman  Icon User is offline

  • Student of Life
  • member icon

Reputation: 418
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: Console to Windows Application

Posted 12 February 2008 - 11:21 AM

Post the code that you are trying to use in your Windows Form. It is not a very difficult transition from console to windows app.
Was This Post Helpful? 0
  • +
  • -

#5 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4300
  • View blog
  • Posts: 12,064
  • Joined: 18-April 07

Re: Console to Windows Application

Posted 12 February 2008 - 11:43 AM

Well going from C# console to C# windows app can be kinda tricky sometimes, the process is usually pretty straight forward. I do cover this topic a bit in my blog at the following URL

Martyr2's Programming Underground - Tips on Converting from Console to GUI

I list some techniques and tips I use for making a successful conversion over. The trickiest part can be how to divide the code in such a way that it will fit inside GUI events. In a console app we may type a number to select and option and in the GUI we may use a button. So how do we make that transition. I cover a bit of this in the blog.

So give it a look see and maybe you will have a better idea of what might be going wrong. Then I am sure we can further assist. :)
Was This Post Helpful? 0
  • +
  • -

#6 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: Console to Windows Application

Posted 12 February 2008 - 12:25 PM

well, all works fine (the form shows up) if i have just this part:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace Chat_Server
{
	public partial class myForm : Form
	{
		public myForm()
		{
			InitializeComponent();
			Encoding ASCII = Encoding.ASCII;
			// Een listener creŽren op poort 8227
			TcpListener myListener = new TcpListener(8227);
			// Start de listener
			myListener.Start();
			textBox1.Text = textBox1.Text + "Wacht op een aanvraag";
		}
	}
}



But after i add the following code after the line 'textBox1.Text = textBox1.Text + "Wacht op een aanvraag";' :

Socket mySocket = myListener.AcceptSocket();



- then the form doesn't show up anymore...
Was This Post Helpful? 0
  • +
  • -

#7 Jayman  Icon User is offline

  • Student of Life
  • member icon

Reputation: 418
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: Console to Windows Application

Posted 12 February 2008 - 01:14 PM

That is because your TcpListener is waiting for a connection from a client. Once it receives a connection it will finish loading the form.

You could run the TcpListener on its own thread to alleviate this problem.
Was This Post Helpful? 0
  • +
  • -

#8 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: Console to Windows Application

Posted 13 February 2008 - 04:56 AM

I tried to make a class in the same namespace as the form class is in to handle the tcplistener, creating a thread for it. It worked (well it gave no errors and the form started) but the line 'textBox1.Text = textBox1.Text + "Wacht op een aanvraag";' didn't work because it couldn't find textBox1?

Tried the same in Program.cs, but same problem.

Also, when i close the form while running, it doesn't close the thread i think... but the problem with not finding the textbox is more important.
Was This Post Helpful? 0
  • +
  • -

#9 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5747
  • View blog
  • Posts: 12,555
  • Joined: 16-October 07

Re: Console to Windows Application

Posted 13 February 2008 - 04:53 PM

As noted by others, listener.AcceptSocket(); is a show stopper. It's a method that waits. It will continue to wait, nothing else will be done.

You MUST give it its own thread. It simply isn't going to work otherwise. There are two steps to this, one is the get those Console writes out, you'll want a way to redirect the output. The other is a thread.

Here's a way to approach this.

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

class Server {
	public enum State { Stopped, Started, Ready }
	private int port;
	private Thread serverThread;
	private TcpListener listener = null;
	private State currentState = State.Stopped;
	
	public Server(int port) { this.port = port; }

	public void Start() {
		currentState = State.Started;
		StopListener();
		StopThread();
		this.serverThread = new Thread(new ThreadStart(this.ThreadProcess));
		this.serverThread.Start();
	}
	
	public void Stop() {
		StopListener();
		StopThread();
		currentState = State.Stopped;
	}
	
	public State CurrentState { get { return this.currentState; } }
	
	protected void StopThread() {
		if (this.serverThread!=null) {
			this.serverThread.Abort();
			this.serverThread = null;
		}
	}
	
	protected void StopListener() {
		if (this.listener!=null) {
			this.listener.Stop();
			this.listener = null;
		}
	}
	
	protected virtual void WriteLine(object obj) {
	Console.Write("Server: ");
		Console.WriteLine(obj.ToString());
	}
	
	protected void ThreadProcess() {
		try {
			this.listener = new TcpListener(this.port);
			this.listener.Start();
			WriteLine("Listening on port: " + this.port);
			WriteLine("Wacht op een aanvraag");
			currentState = State.Ready;
			while(true) {
				Socket mySocket = this.listener.AcceptSocket();
				if(mySocket.Connected) {
					WriteLine("Een aanvraag ontvangen");
					Byte[] RecvBytes = new Byte[256];
					Int32 bytes = mySocket.Receive(RecvBytes, RecvBytes.Length, 0);
					string s = System.Text.Encoding.ASCII.GetString(RecvBytes, 0, bytes);
					WriteLine(s);
					if (s == "GetDate") {
						DateTime now = DateTime.Now;
						String strDateLine = now.ToShortDateString() + " " + now.ToLongTimeString();
						Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine.ToCharArray());
						mySocket.Send(byteDateLine, byteDateLine.Length, 0);
					} else {
						WriteLine(string.Format("Onbekende opdracht: {0}", s));
					}
				} else {
					WriteLine("oops, not connected.");
				}
			}
		} finally {
			StopListener();
			currentState = State.Stopped;
		}
	}
}




Note we have two public methods, start and stop. You probably wont bother with stop. You original code is inside the main thread process, mostly unchanged.

Here's how a console program might work:
public static void Main(string[] args) {
	int port = 8333;
	Server server = new Server(port);
	server.Start();
	while (server.CurrentState==Server.State.Started ) {
		Thread.Sleep(500);
	}
	Console.WriteLine("Server:" + server.CurrentState);
	if (server.CurrentState==Server.State.Ready) {
		Console.WriteLine("Server started in own thread.");
		Console.WriteLine("Lets talk to it.");
		Client client = new Client(port);
		client.SendRequest("GetDate");
	}
	
	Console.WriteLine("Processing Done");
	server.Stop();
}



Now that you have your threading in place, just need to adjust the code slightly for a form. Perhaps something like this:
class ServerOnForm : Server {
	private Control outputControl;
	
	public Server(int port, Control outputControl) : base(port) {
		this.outputControl = outputControl;
		this.outputControl.Text = "";
	}
	
	protected override void WriteLine(object obj) {
		this.outputControl.Text += obj.ToString() + "\n";
	}
}



This is really not about forms so much is making your server multithreaded, something it would need to be if it were a regular server anyway.

Hope this helps.
Was This Post Helpful? 0
  • +
  • -

#10 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: Console to Windows Application

Posted 22 February 2008 - 01:11 PM

- back from hard work at school.

Well, still have the problem changing from console application to a windows form application.

In the windows application, i put the follow code in program.cs:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WinServerChat
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new Form1());

			int port = 8333;
			Server server = new Server(port);
			server.Start();
			while (server.CurrentState == Server.State.Started)
			{
				Thread.Sleep(500);
			}
			
			//Console.WriteLine("Server:" + server.CurrentState);
			if (server.CurrentState == Server.State.Ready)
			{
				//Console.WriteLine("Server started in own thread.");
				//Console.WriteLine("Lets talk to it.");
				//Client client = new Client(port);
				//client.SendRequest("GetDate");
			}

			//Console.WriteLine("Processing Done");
			server.Stop();
		}
	}

	class Server
	{
		public enum State { Stopped, Started, Ready }
		private int port;
		private Thread serverThread;
		private TcpListener listener = null;
		private State currentState = State.Stopped;

		public Server(int port) { this.port = port; }

		public void Start()
		{
			currentState = State.Started;
			StopListener();
			StopThread();
			this.serverThread = new Thread(new ThreadStart(this.ThreadProcess));
			this.serverThread.Start();
		}

		public void Stop()
		{
			StopListener();
			StopThread();
			currentState = State.Stopped;
		}

		public State CurrentState { get { return this.currentState; } }

		protected void StopThread()
		{
			if (this.serverThread != null)
			{
				this.serverThread.Abort();
				this.serverThread = null;
			}
		}

		protected void StopListener()
		{
			if (this.listener != null)
			{
				this.listener.Stop();
				this.listener = null;
			}
		}

		protected virtual void WriteLine(object obj)
		{
			//Console.Write("Server: ");
			//Console.WriteLine(obj.ToString());
		}

		protected void ThreadProcess()
		{
			try
			{
				this.listener = new TcpListener(this.port);
				this.listener.Start();
				//WriteLine("Listening on port: " + this.port);
				//WriteLine("Wacht op een aanvraag");
				currentState = State.Ready;
				while (true)
				{
					Socket mySocket = this.listener.AcceptSocket();
					if (mySocket.Connected)
					{
						//WriteLine("Een aanvraag ontvangen");
						Byte[] RecvBytes = new Byte[256];
						Int32 bytes = mySocket.Receive(RecvBytes, RecvBytes.Length, 0);
						string s = System.Text.Encoding.ASCII.GetString(RecvBytes, 0, bytes);
						//WriteLine(s);
						if (s == "GetDate")
						{
							DateTime now = DateTime.Now;
							String strDateLine = now.ToShortDateString() + " " + now.ToLongTimeString();
							Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine.ToCharArray());
							mySocket.Send(byteDateLine, byteDateLine.Length, 0);
						}
						else
						{
							//WriteLine(string.Format("Onbekende opdracht: {0}", s));
						}
					}
					else
					{
						//WriteLine("oops, not connected.");
					}
				}
			}
			finally
			{
				StopListener();
				currentState = State.Stopped;
			}
		}
	}
}



My form1.cs code is still standard:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WinServerChat
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
			
		}
	}
}



Well, i get no errors. But i need to change the console output to a textbox.

So instead 'Console.Write("Server: ");' i need something like 'textbox1.Text = "Server: ";'.

My problem is that i cant find/access the textbox1 object. I can only use it in the Form1 constructor in form1.cs... but how to use it in Main?
Was This Post Helpful? 0
  • +
  • -

#11 zakary  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 27
  • View blog
  • Posts: 427
  • Joined: 15-February 05

Re: Console to Windows Application

Posted 22 February 2008 - 01:15 PM

use the code you posted first now make sure you have a reference to System.Windows.Forms then instead of

Console.WriteLine("Server started in own thread.");

use

System.Windows.Forms.MessageBox.Show("Server started in own thread.");
Was This Post Helpful? 0
  • +
  • -

#12 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: Console to Windows Application

Posted 22 February 2008 - 02:53 PM

That's not what i meant... the message must show up in an already existing TextBox (made in the form design).
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1