Friday, February 10, 2012

How to Implement Threaded Server Socket Application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace ServerSocketApp
{
class Server
{
 private TcpListener tcpListn = null;
 private Thread listenThread = null;
 private bool isServerListening = false;

 public Server()
 {
  tcpListn = new TcpListener(IPAddress.Any,8090);
  listenThread = new Thread(new ThreadStart(listeningToclients));
  this.isServerListening = true;
  listenThread.Start();
 }

 //listener
 private void listeningToclients()
 {
  tcpListn.Start();
  Console.WriteLine("Server started!");
  Console.WriteLine("Waiting for clients...");
  while (this.isServerListening)
  {
   TcpClient tcpClient = tcpListn.AcceptTcpClient();
   Thread clientThread = new Thread(new ParameterizedThreadStart(handleClient));
   clientThread.Start(tcpClient);
  }

 }

 //client handler
 private void handleClient(object clientObj)
 {
  TcpClient client = (TcpClient)clientObj;
  Console.WriteLine("Client connected!");

  NetworkStream stream = client.GetStream();
  ASCIIEncoding asciiEnco = new ASCIIEncoding();

  //read data from client
  byte[] byteBuffIn = new byte[client.ReceiveBufferSize];
  int length = stream.Read(byteBuffIn, 0, client.ReceiveBufferSize);
  StringBuilder clientMessage = new StringBuilder("");
  clientMessage.Append(asciiEnco.GetString(byteBuffIn));

  //write data to client
  byte[] byteBuffOut = asciiEnco.GetBytes("Hello client! \n"+"You said : " + clientMessage.ToString() +"\n Your ID  : " + new Random().Next());
  stream.Write(byteBuffOut, 0, byteBuffOut.Length);

  stream.Flush();
  stream.Close();
  client.Close(); //close the client
 }

 public void stopServer()
 {
  this.isServerListening = false;
  Console.WriteLine("Server stoped!");
 }

}
}

Saturday, February 4, 2012

Arrays in .NET Webservices

Web Service
public class Service1 : System.Web.Services.WebService
{
 [WebMethod]
 public int[] sort(int[] arr)
 {
  Array.Sort(arr);
  return arr;
 }
}
Then run the service.
Copy the URL of the WSDL
ex :  http://localhost:4886/Service1.asmx?WSDL

Then create a new desktop or console application. This application will consume the previously written web service.

Right click on the project -> Add service reference -> Give the address of wsdl of our web service -> Change the namespace name for a proper name.

consumer code.

class Program
{
 static void Main(string[] args)
 {
  MyCalcService.Service1SoapClient clie = new MyCalcService.Service1SoapClient();
  MyCalcService.ArrayOfInt x=new MyCalcService.ArrayOfInt();
  x.Add(-1);
  x.Add(76);
  x.Add(9);
  x.Add(-7);

  x = clie.sort(x);
  foreach (int i in x)
  {
   Console.Write(i+ " ");
  }
  Console.ReadKey();
 }
}
Remember that though we used int[] type for our array in web service we cannot use same array type at the client side. We have to use ArrayOfInt type in the service references namespace.

Reading Text from Files (C#.net)

private void button2_Click(object sender, EventArgs e)
{
try
{
 string buffer;
 StringBuilder stb = new StringBuilder();
 StreamReader strmRdr = File.OpenText("c:\\testfile.txt");
 while ((buffer = strmRdr.ReadLine()) != null)
 {
  stb.Append(buffer);
  stb.Append(Environment.NewLine);
 }
 textBox1.Text = stb.ToString();
 strmRdr.Close();
}
catch (IOException ex)
{
 Console.WriteLine("Error in handling file!\n" + ex.Message.ToString());
}
}

Writing Text to files( C#.net )

private void button1_Click(object sender, EventArgs e)
{
 try
 {
  FileStream fileStrm = File.Open("c:\\testfile.txt", FileMode.OpenOrCreate);
  StreamWriter writer = new StreamWriter(fileStrm);
  writer.WriteLine("First Line");
  for (int i = 2; i < 100; i++)
  {
   writer.WriteLine("This is line {0}", i);
  }
  writer.Close();
  fileStrm.Close();
  Console.WriteLine("File created!");
 }
 catch (IOException ex)
 {
  Console.WriteLine("Error in handling file!\n" + ex.Message.ToString() );
 }
}

Friday, February 3, 2012

Using DataGridView to Show Data in a table

Selecting multiple files and show their information on a DataGridView
    public partial class Form1 : Form
    {
        private String[] selectedFiles;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = "Open a file to process";
            openFileDialog1.Multiselect = true;
            //selectable file types
            openFileDialog1.Filter = "Portable Document Format (*.pdf)|*.pdf|Text Documents(*.txt)|*.txt|Executable(*.exe)|*.exe|MPEG Layer 3 File(*.mp3)|*.mp3";
            openFileDialog1.InitialDirectory = "c:";
            DialogResult respo= openFileDialog1.ShowDialog();
            if (respo == DialogResult.OK)
            {
                selectedFiles = openFileDialog1.FileNames;
            }
            else
            {
                textBox1.Text = "No selected file!";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            dataGridView1.Columns.Add("FileName", "File Name");
            dataGridView1.Columns.Add("FileSize", "File Size");
            dataGridView1.Columns.Add("IsSystem", "Last Accessed Time");

            

            //dataGridView1.Rows.Add(new Object[] { "A.php", "2345KB", "True" });
            //dataGridView1.Rows.Add(new Object[] { "CV.doc", "3543KB", "False" });
            //dataGridView1.Rows.Add(new Object[] { "cmd.exe", "35763KB", "True" });
            foreach (String file in selectedFiles)
            {
                FileInfo fObj = new FileInfo(file);
                String fileName;
                try
                {
                    fileName = file.Substring(file.LastIndexOf('\\') + 1);
                }catch(ArgumentOutOfRangeException ex)
                {
                    fileName = file;
                }

                long leng = fObj.Length;
                bool isReadOnly = fObj.IsReadOnly;
                DateTime lwt = fObj.LastWriteTime;
                String lastAccess = lwt.ToString();

                dataGridView1.Rows.Add(new Object[]{fileName,leng,lastAccess});

                Console.WriteLine(fileName);
            }
        }

Using FileOpen Dialog

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = "Open a file to process";
            //selectable file types
            openFileDialog1.Filter = "Portable Document Format (*.pdf)|*.pdf|Text Documents(*.txt)|*.txt";
            openFileDialog1.InitialDirectory = "c:\";
            DialogResult respo= openFileDialog1.ShowDialog();
            if (respo == DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName;
            }
            else
            {
                textBox1.Text = "No selected file!";
            }
        }

Thursday, February 2, 2012

Progressbar Update In C#.net

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

namespace ThreaddedApp
{
    public partial class Form1 : Form
    {
        delegate void progressbarrunnerDelegate();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Invoke(new progressbarrunnerDelegate(progressbarrunner));
        }

        private void progressbarrunner()
        {
            for (int i = 0; i < 100; i++)
            {
                Thread.Sleep(50);
                this.progressBar1.Value = i;
                Application.DoEvents();
            }
        }
    }
}

 
© Copyright 2035 kani.stack.notez
Theme by Yusuf Fikri