Click here to Skip to main content
15,886,919 members
Home / Discussions / C#
   

C#

 
GeneralRe: I want to open windows application from image button click of web page. Pin
AtulRane5-Sep-08 20:36
AtulRane5-Sep-08 20:36 
GeneralRe: I want to open windows application from image button click of web page. Pin
WillemM5-Sep-08 20:37
WillemM5-Sep-08 20:37 
GeneralRe: I want to open windows application from image button click of web page. Pin
AtulRane5-Sep-08 20:41
AtulRane5-Sep-08 20:41 
GeneralRe: I want to open windows application from image button click of web page. Pin
AtulRane6-Sep-08 21:44
AtulRane6-Sep-08 21:44 
GeneralRe: I want to open windows application from image button click of web page. Pin
WillemM6-Sep-08 23:45
WillemM6-Sep-08 23:45 
QuestionTCP chat Pin
priyajeni5-Sep-08 19:39
priyajeni5-Sep-08 19:39 
AnswerRe: TCP chat Pin
Blue_Boy5-Sep-08 19:45
Blue_Boy5-Sep-08 19:45 
GeneralRe: TCP chat Pin
priyajeni5-Sep-08 20:18
priyajeni5-Sep-08 20:18 
thanks for u'r reply.. i have inserted the code which i hav done so far below...what i hav done is connecting client and server machine using ip address and port using tcp/ip socket and sending datas so dat it's storing in aserver machine database server but now i need the datas to be stored in a text file in the server machine is it possible.
using System;
using System.Threading;								// Sleeping
using System.Net;									// Used to local machine info
using System.Net.Sockets;							// Socket namespace
using System.Collections;							// Access to the Array list
using System.IO;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace ChatServer
{
	/// <summary>
	/// Main class from which all objects are created
	/// </summary>
	class AppMain
	{
		// Attributes
		private ArrayList	m_aryClients = new ArrayList();	// List of Client Connections
		public  clsMaster  objmaster  = new clsMaster();
		/// <summary>
		/// Application starts here. Create an instance of this class and use it
		/// as the main object.
		/// </summary>
		/// <param name="args"></param>
		/// 
		static void Main(string[] args)
		{
			AppMain app = new AppMain();
			// Welcome and Start listening
			Console.WriteLine( "*** Data Collector Server Started {0} *** ", DateTime.Now.ToString( "G" ) );

/*
			//
			// Method 1
			//
			string strport =System.Configuration.ConfigurationSettings.AppSettings["IPPort"] ;
			Socket client;
			 int nPortListen =Convert.ToInt16 (strport);
			try
			{
				TcpListener listener = new TcpListener(nPortListen );
				Console.WriteLine( "Listening as {0}", listener.LocalEndpoint );
				listener.Start();
				do
				{
					byte [] m_byBuff = new byte[127];
					if( listener.Pending() )
					{
						client = listener.AcceptSocket();
						// Get current date and time.
						DateTime now = DateTime.Now;
						String strDateLine = "Welcome " + now.ToString("G") + "\n\r";

						// Convert to byte array and send.
//						Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes( strDateLine.ToCharArray() );
//						client.Send( byteDateLine, byteDateLine.Length, 0 );
					}
					else
					{
						Thread.Sleep( 100 );
					}
				} while( true );	// Don't use this. 

				//Console.WriteLine ("OK that does it! Screw you guys I'm going home..." );
				//listener.Stop();
			}
			catch( Exception ex )
			{
				Console.WriteLine ( ex.Message );
			}
*/			


			//
			// Method 2 
			//
			string strport =System.Configuration.ConfigurationSettings.AppSettings["IPPort"] ;
			int nPortListen = Convert.ToInt32(strport);
			// Determine the IPAddress of this machine
			IPAddress [] aryLocalAddr = null;
			String strHostName = "";
			try
			{
				// NOTE: DNS lookups are nice and all but quite time consuming.
				strHostName = Dns.GetHostName();
				IPHostEntry ipEntry = Dns.GetHostByName( strHostName );
				aryLocalAddr = ipEntry.AddressList;
			}
			catch( Exception ex )
			{
				Console.WriteLine ("Error trying to get local address {0} ", ex.Message );
			}
	
			// Verify we got an IP address. Tell the user if we did
			if( aryLocalAddr == null || aryLocalAddr.Length < 1 )
			{
				Console.WriteLine( "Unable to get local address" );
				return;
			}
			Console.WriteLine( "Listening on : [{0}] {1}:{2}", strHostName, aryLocalAddr[0], nPortListen );

			// Create the listener socket in this machines IP address
			Socket listener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			listener.Bind( new IPEndPoint( aryLocalAddr[0], nPortListen ) );
			//listener.Bind( new IPEndPoint( IPAddress.Loopback, 399 ) );	// For use with localhost 127.0.0.1
			listener.Listen(10 );

			// Setup a callback to be notified of connection requests
			listener.BeginAccept( new AsyncCallback( app.OnConnectRequest ), listener );

			Console.WriteLine ("Press Enter to exit" );
			Console.ReadLine();
			Console.WriteLine ("OK that does it! Screw you guys I'm going home..." );

			// Clean up before we go home
			listener.Close();
			GC.Collect();
			GC.WaitForPendingFinalizers();		
		}


		/// <summary>
		/// Callback used when a client requests a connection. 
		/// Accpet the connection, adding it to our list and setup to 
		/// accept more connections.
		/// </summary>
		/// <param name="ar"></param>
		public void OnConnectRequest( IAsyncResult ar )
		{
			Socket listener = (Socket)ar.AsyncState;
			NewConnection(listener.EndAccept(ar));
			listener.BeginAccept( new AsyncCallback( OnConnectRequest ), listener );
		}

		/// <summary>
		/// Add the given connection to our list of clients
		/// Note we have a new friend
		/// Send a welcome to the new client
		/// Setup a callback to recieve data
		/// </summary>
		/// <param name="sockClient">Connection to keep</param>
		//public void NewConnection( TcpListener listener )
        

		public void NewConnection( Socket sockClient )
		{
			// Program blocks on Accept() until a client connects.
			//SocketChatClient client = new SocketChatClient( listener.AcceptSocket() );
			SocketChatClient client = new SocketChatClient( sockClient );
			m_aryClients.Add( client );
			Console.WriteLine( "Client {0}, joined", client.Sock.RemoteEndPoint );
 
			// Get current date and time.
			DateTime now = DateTime.Now;
			String strDateLine = "Welcome " + now.ToString("G") + "\n\r";

			// Convert to byte array and send.
			Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes( strDateLine.ToCharArray() );
			client.Sock.Send( byteDateLine, byteDateLine.Length, 0 );
//
			client.SetupRecieveCallback( this );
		}
        

		/// <summary>
		/// Get the new data and send it out to all other connections. 
		/// Note: If not data was recieved the connection has probably 
		/// died.
		/// </summary>
		/// <param name="ar"></param>
		public void OnRecievedData( IAsyncResult ar )
        {
            SocketChatClient client = (SocketChatClient)ar.AsyncState;
            byte[] aryRet = client.GetRecievedData(ar);

            // If no data was recieved then the connection is probably dead
            if (aryRet.Length < 1)
            {
                Console.WriteLine("Client {0}, disconnected", client.Sock.RemoteEndPoint);
                client.Sock.Close();
                m_aryClients.Remove(client);
                return;
            }
            // Commented for database collection
            if(System.Text.Encoding.ASCII.GetString(aryRet )!="")
            {
                string strvalue=System.Text.Encoding.ASCII.GetString(aryRet );
                char[] sep = {';'};
                Array a = strvalue.Split(sep);

                TextWriter tw = new StreamWriter("d://date.txt");
                string path = "d://date.txt";
                StreamWriter sw = new StreamWriter(Path);
                string bufferOne = "trans_logging";  
                string buffertwo = "trans_logging";
                string bufferthree = "drc_dateTime";
                sw.WriteLine(bufferOne);
                sw.WriteLine(buffertwo);
                sw.WriteLine(bufferthree);

                try
                {
                    objmaster.Insert("trans_logging", "trans_logging", "dateTime", System.Text.Encoding.ASCII.GetString(aryRet), DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"));
                    tw.WriteLine(objmaster);

                
                }



                catch (Exception ex)
                {
                    Console.Write(ex.Message);
                }
            }

            // up to here

            //			// Send the recieved data to all clients (including sender for echo)
            //			foreach( SocketChatClient clientSend in m_aryClients )
            //			{
            //				try
            //				{
            //					clientSend.Sock.Send( aryRet );
            //				}
            //				catch
            //				{
            //					// If the send fails the close the connection
            //					Console.WriteLine( "Send to client {0} failed", client.Sock.RemoteEndPoint );
            //					clientSend.Sock.Close();
            //					m_aryClients.Remove( client );
            //					return;
            //				}
            //			}
            client.SetupRecieveCallback(this);
        }
	}

	/// <summary>
	/// Class holding information and buffers for the Client socket connection
	/// </summary>
	internal class SocketChatClient
	{
		private Socket m_sock;						// Connection to the client
		private byte[] m_byBuff = new byte[1000];		// Receive data buffer
		public  clsMaster  objmaster  = new clsMaster();
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="sock">client socket conneciton this object represents</param>
		public SocketChatClient( Socket sock )
		{
			m_sock = sock;
		}

		// Readonly access
		public Socket Sock
		{
			get{ return m_sock; }
		}

		/// <summary>
		/// Setup the callback for recieved data and loss of conneciton
		/// </summary>
		/// <param name="app"></param>
		public void SetupRecieveCallback( AppMain app )
		{
			try
			{
				AsyncCallback recieveData = new AsyncCallback(app.OnRecievedData);
				m_sock.BeginReceive( m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, this );
			}
			catch( Exception ex )
			{
				Console.WriteLine( "Recieve callback setup failed! {0}", ex.Message );
			}
		}

		/// <summary>
		/// Data has been recieved so we shall put it in an array and
		/// return it.
		/// </summary>
		/// <param name="ar"></param>
		/// <returns>Array of bytes containing the received data</returns>
		public byte [] GetRecievedData( IAsyncResult ar )
		{
            int nBytesRec = 0;
			try
			{
				nBytesRec = m_sock.EndReceive( ar );
				
				//Console.WriteLine(name);
			}
			catch{}
			byte [] byReturn = new byte[nBytesRec];
			Array.Copy( m_byBuff, byReturn, nBytesRec );
			
			/*
			// Check for any remaining data and display it
			// This will improve performance for large packets 
			// but adds nothing to readability and is not essential
			int nToBeRead = m_sock.Available;
			if( nToBeRead > 0 )
			{
				byte [] byData = new byte[nToBeRead];
				m_sock.Receive( byData );
				// Append byData to byReturn here
			}
			*/
			// comment below line after successful completion
			//*&Console.WriteLine(System.Text.Encoding.ASCII.GetString(byReturn ));

            Console.WriteLine("Received Data {0}", System.Text.Encoding.ASCII.GetString(byReturn));



			return byReturn;
		}
		
	}

}

GeneralRe: TCP chat Pin
priyajeni6-Sep-08 0:43
priyajeni6-Sep-08 0:43 
GeneralRe: TCP chat Pin
#realJSOP6-Sep-08 2:09
mve#realJSOP6-Sep-08 2:09 
GeneralRe: TCP chat Pin
PIEBALDconsult6-Sep-08 4:10
mvePIEBALDconsult6-Sep-08 4:10 
AnswerRe: TCP chat Pin
Mbah Dhaim6-Sep-08 8:08
Mbah Dhaim6-Sep-08 8:08 
AnswerRe: TCP chat Pin
nelsonpaixao7-Sep-08 13:14
nelsonpaixao7-Sep-08 13:14 
GeneralRe: TCP chat Pin
priyajeni7-Sep-08 18:33
priyajeni7-Sep-08 18:33 
Questionlogin dialog help Pin
captjack5-Sep-08 16:43
captjack5-Sep-08 16:43 
AnswerRe: login dialog help Pin
Ravi Kumar Tyagi5-Sep-08 18:39
Ravi Kumar Tyagi5-Sep-08 18:39 
AnswerRe: login dialog help Pin
zafersavas5-Sep-08 18:51
zafersavas5-Sep-08 18:51 
GeneralRe: login dialog help Pin
captjack6-Sep-08 4:12
captjack6-Sep-08 4:12 
GeneralRe: login dialog help Pin
zafersavas6-Sep-08 4:21
zafersavas6-Sep-08 4:21 
QuestionMobile Pin
nelsonpaixao5-Sep-08 13:55
nelsonpaixao5-Sep-08 13:55 
AnswerRe: Mobile Pin
Blue_Boy5-Sep-08 19:41
Blue_Boy5-Sep-08 19:41 
AnswerRe: Mobile Pin
CaptainKrtek7-Sep-08 8:55
CaptainKrtek7-Sep-08 8:55 
QuestionRight click GridView Pin
Jacob Dixon5-Sep-08 10:34
Jacob Dixon5-Sep-08 10:34 
AnswerRe: Right click GridView Pin
Bassam Saoud5-Sep-08 11:29
Bassam Saoud5-Sep-08 11:29 
GeneralRe: Right click GridView Pin
Jacob Dixon5-Sep-08 14:03
Jacob Dixon5-Sep-08 14:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.