Sunday, 8 December 2013

c# whois

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

namespace whois
{
    class Program
    {
        public class Whois
        {
            private static int portNumber = 43;
            private string host;

            public Whois(string hostName)
            {
                this.host = hostName;
            }


            public void lookUp(string searchText)
            {
                TcpClient theConnection = null;
                NetworkStream network = null;
                BufferedStream basestream = null;
                StreamReader inputstream = null;
                StreamWriter outputstream = null;

                try
                {
                    theConnection = new TcpClient(host, portNumber);
                    network = theConnection.GetStream();
                    basestream = new BufferedStream(network);
                }
                catch (SocketException se)
                {
                    Console.WriteLine("exception caught attempting to open connection to {0}", host);
                    Console.WriteLine("\nexception details: {0}", se.ToString());
                    return;
                }

                try
                {
                    outputstream = new StreamWriter(basestream);
                    outputstream.WriteLine(searchText);
                    outputstream.Flush();
                }
                catch (Exception e)
                {
                    Console.WriteLine("exception caught attempting to send data to host: {0}.", host);
                    Console.WriteLine("\nexception details:{0}", e.ToString());
                    theConnection.Close();
                    return;
                }

                try
                {
                    inputstream = new StreamReader(basestream);
                    string intermediateoutput;
                    while (null != (intermediateoutput = inputstream.ReadLine()))
                    {
                        Console.WriteLine(intermediateoutput);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("exception caught attempting to read data from host: {0}", host);
                    Console.WriteLine("\nexception details:{0}", e.ToString());
                    theConnection.Close();
                    return;
                }
                theConnection.Close();
            }
        }
        static void Main(string[] args)
        {
            string host;
            string search;

            if (0 == args.Length)
            {
                Console.WriteLine("usage:whois<lookup host> hostname");
                return;
            }
            else if (2 == args.Length)
            {
                host = args[0];
                search = args[1];
            }
            else
            {
                host = "whois.internic.net";
                search = args[0];
            }

            Whois whoisinstance = new Whois(host);
            whoisinstance.lookUp(search);

        }
    }
}

c# web upload download pic




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

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

        private WebRequest req;

        //connect
        private void button1_Click(object sender, EventArgs e)
        {
            string url = textBox1.Text;
            try
            {
                req = WebRequest.Create(url);
                textBox1.Enabled = false;
                button2.Enabled = true;
                button3.Enabled = true;
            }
            catch (WebException exp)
            {
                MessageBox.Show(exp.Message, "error");
            }
        }

        //download
        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Enabled = true;
            button2.Enabled = false;
            button3.Enabled = false;

            HttpWebResponse httpWebReponse = (HttpWebResponse)req.GetResponse();
            Stream stm = httpWebReponse.GetResponseStream();
            Image m = Image.FromStream(stm);
            pictureBox1.Image = m;
            m.Save("m");
           
        }

        //upload
        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Enabled = true;
            button2.Enabled = false;
            button3.Enabled = false;

            openFileDialog1.Filter = "png(*.png)|*.png|jpg(*.jpg)|*.jpg|all files(*.*)|*.*";
            openFileDialog1.Title = "browse picture to upload";


            string imagepath = "";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                imagepath = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
               
                pictureBox1.Image= new Bitmap(openFileDialog1.FileName);
               
                WebClient client = new WebClient();
                client.UploadFile(textBox1.Text, imagepath);
            }
        }
    }
}

Saturday, 7 December 2013

c# web upload download txt






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

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

        private WebClient client;

        //connect
        private void button1_Click(object sender, EventArgs e)
        {
            string url = textBox1.Text;
            try
            {
                WebRequest req = WebRequest.Create(url);
                textBox1.Enabled = false;
                button2.Enabled = true;
                button3.Enabled = true;
            }
            catch (WebException exp)
            {
                MessageBox.Show(exp.Message, "error");
            }
        }

        //download
        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Enabled = true;
            button2.Enabled = false;
            button3.Enabled = false;
            listBox1.Items.Clear();

            client = new WebClient();
            client.DownloadFile(textBox1.Text,"web.aspx");

            Stream strm = client.OpenRead(textBox1.Text);
            StreamReader sr = new StreamReader(strm);

            string line;
            do
            {
                line = sr.ReadLine();
                if (line != null) { listBox1.Items.Add(line); }
            }
            while (line != null);

            strm.Close();
        }

        //upload
        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Enabled = true;
            button2.Enabled = false;
            button3.Enabled = false;
            listBox1.Items.Clear();

            openFileDialog1.Filter = "html(*.html)|*.html|txt(*.txt)|*.txt|all files(*.*)|*.*";
            openFileDialog1.Title = "browse file to upload";


            string filepath = "";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                filepath = openFileDialog1.InitialDirectory + openFileDialog1.FileName;            
                client = new WebClient();
                client.UploadFile(textBox1.Text, filepath);
            }
        }
    }
}


c# web response


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using System.Net;

namespace url
{
    class Program
    {

        static void Main(string[] args)
        {
            // Create a 'WebRequest' object with the specified url.
            WebRequest myWebRequest = WebRequest.Create(args[0]);

            // Send the 'WebRequest' and wait for response.
            WebResponse myWebResponse = myWebRequest.GetResponse();

            // Obtain a 'Stream' object associated with the response object.
            Stream ReceiveStream = myWebResponse.GetResponseStream();

            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

            // Pipe the stream to a higher level stream reader with the required encoding format.
            StreamReader readStream = new StreamReader(ReceiveStream, encode);
            Console.WriteLine("\nResponse stream received");
            Char[] read = new Char[256];

            // Read 256 charcters at a time.    
            int count = readStream.Read(read, 0, 256);
            Console.WriteLine("HTML...\r\n");

            while (count > 0)
            {
                // Dump the 256 characters on a string and display the string onto the console.
                String str = new String(read, 0, count);
                Console.Write(str);
                count = readStream.Read(read, 0, 256);
            }

            Console.WriteLine("");
            // Release the resources of stream object.
            readStream.Close();

            // Release the resources of response object.
            myWebResponse.Close();
        }
    }
}

Friday, 6 December 2013

c# email

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

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

        private void SendButton_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage amessage = new MailMessage();
                amessage.From = new MailAddress(FromTextBox.Text);
                amessage.To.Add(new MailAddress(ToTextBox.Text));
                amessage.CC.Add(new MailAddress(CCTextBox.Text));
                amessage.Bcc.Add(new MailAddress(BCCTextBox.Text));
                amessage.Subject = SubjectTextBox.Text;
                amessage.Body = MessageTextBox.Text;

                SmtpClient smtp = new SmtpClient("smtp server");
                smtp.Send(amessage);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
               
        }

        private void ExitButton_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

c# default webpage



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

namespace webpage
{
    class Program
    {
        public static string DoSocketGet(string server)
        {
            //Set up variables and String to write to the server.
            Encoding ASCII = Encoding.ASCII;
            string Get = "GET / HTTP/1.1\r\nHost: " + server +
                         "\r\nConnection: Close\r\n\r\n";
            Byte[] ByteGet = ASCII.GetBytes(Get);
            Byte[] RecvBytes = new Byte[256];
            String strRetPage = null;


            // IPAddress and IPEndPoint represent the endpoint that will
            //   receive the request.
            // Get first IPAddress in list return by DNS.


            try
            {


                // Define those variables to be evaluated in the next for loop and
                // then used to connect to the server. These variables are defined
                // outside the for loop to make them accessible there after.
                Socket s = null;
                IPEndPoint hostEndPoint;
                IPAddress hostAddress = null;
                int conPort = 80;

                // Get DNS host information.
                IPHostEntry hostInfo = Dns.GetHostEntry(server);
                // Get the DNS IP addresses associated with the host.
                IPAddress[] IPaddresses = hostInfo.AddressList;

                // Evaluate the socket and receiving host IPAddress and IPEndPoint.
                for (int index = 0; index < IPaddresses.Length; index++)
                {
                    hostAddress = IPaddresses[index];
                    hostEndPoint = new IPEndPoint(hostAddress, conPort);


                    // Creates the Socket to send data over a TCP connection.
                    s = new Socket(hostAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);



                    // Connect to the host using its IPEndPoint.
                    s.Connect(hostEndPoint);

                    if (!s.Connected)
                    {
                        // Connection failed, try next IPaddress.
                        strRetPage = "Unable to connect to host";
                        s = null;
                        continue;
                    }

                    // Sent the GET request to the host.
                    s.Send(ByteGet, ByteGet.Length, 0);


                } // End of the for loop.      



                // Receive the host home page content and loop until all the data is received.
                Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
                strRetPage = "Default HTML page on " + server + ":\r\n";
                strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);

                while (bytes > 0)
                {
                    bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
                    strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
                }


            } // End of the try block.

            catch (SocketException e)
            {
                Console.WriteLine("SocketException caught!!!");
                Console.WriteLine("Source : " + e.Source);
                Console.WriteLine("Message : " + e.Message);
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException caught!!!");
                Console.WriteLine("Source : " + e.Source);
                Console.WriteLine("Message : " + e.Message);
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine("NullReferenceException caught!!!");
                Console.WriteLine("Source : " + e.Source);
                Console.WriteLine("Message : " + e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught!!!");
                Console.WriteLine("Source : " + e.Source);
                Console.WriteLine("Message : " + e.Message);
            }

            return strRetPage;

        }
        public static void Main()
        {
            Console.WriteLine(DoSocketGet("localhost"));
        }

    }
}

Tuesday, 3 December 2013

c# chat









//form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Timers;
using System.IO;

namespace net
{
    public partial class Form1 : Form
    {
        public Form2 yourchoice;

        public Form1()
        {
            InitializeComponent();
            this.Hide();
            yourchoice = new Form2();
            yourchoice.ShowDialog();
            this.Show();
            localhost = Class1.host;
            remoteconnect = Class1.remote;
            if (localhost == true && remoteconnect == false) { ishost(); }
        }

        private int sent = 0;
        private Socket s;
        private TcpClient x;
        private string[] timer2str;
        private int timer2i = 0;
        private string[] timer1str;
        private int timer1i = 0;
        private string previousrichtext="echo";
        private bool localhost;
        private bool remoteconnect;

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        //host server
        private void ishost()
        {
            button1.Enabled = false;
            textBox1.Enabled = false;
            textBox3.Enabled = false;

            MessageBox.Show("local address 127.0.0.2:8001\n wait for remote connection");
            IPAddress ipAd = IPAddress.Parse("127.0.0.2");
            TcpListener myList = new TcpListener(ipAd, 8001);
            listBox1.Items.Add("my local address:" + myList.LocalEndpoint);
            myList.Start();
            s = myList.AcceptSocket();
            listBox1.Items.Add("remote address: " + s.RemoteEndPoint);
            textBox2.Text = s.RemoteEndPoint.ToString();
            button4.Enabled = true;
            timer1.Enabled = true;
        }

        //remote connect
        private void button1_Click(object sender, EventArgs e)
        {
            if (remoteconnect == true && localhost == false)
            {
                try
                {
                    x = new TcpClient();
                    listBox1.Items.Add("connecting to " + textBox1.Text);
                    x.Connect(textBox1.Text, int.Parse(textBox3.Text));
                    listBox1.Items.Add("connected");
                    textBox2.Text = textBox1.Text;
                    timer2.Enabled=true;
                }
                catch (Exception)
                {
                    listBox1.Items.Add("server not found");
                }

                Stream stm = x.GetStream();
                try
                {
                    string str = "echo";
                    ASCIIEncoding asen = new ASCIIEncoding();
                    byte[] ba = asen.GetBytes(str);
                    stm.Write(ba, 0, ba.Length);
                }
                catch (Exception) { }
            }
        }

        //search server
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                IPHostEntry IPHost = Dns.GetHostEntry(textBox4.Text);
                listBox1.Items.Add("HostName: " + IPHost.HostName);

                string[] aliases = IPHost.Aliases;
                listBox1.Items.Add("count of host aliases: " + aliases.Length);

                for (int i = 0; i < aliases.Length; i++)
                {
                    listBox1.Items.Add(aliases[i]);
                }

                IPAddress[] addr = IPHost.AddressList;
                listBox1.Items.Add("host IP list: ");

                for (int i = 0; i < addr.Length; i++)
                {
                    listBox1.Items.Add(addr[i]);
                }

                button4.Enabled = true;
            }
            catch (Exception)
            {
                listBox1.Items.Add("server not found");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }

        //host server timer
        private void timer1_Tick_2(object sender, EventArgs e)
        {      
            try
            {
                byte[] b = new byte[1000];
                int k = s.Receive(b);

                string richtext = "";
                for (int i = 0; i < k; i++)
                {
                    richtext += (Convert.ToChar(b[i])).ToString();
                }
           
                if (richtext != "echo")
                {
                    if (previousrichtext == "echo")
                    {
                        DateTime now = DateTime.Now;
                        richTextBox1.AppendText(now.ToShortDateString() + " " + now.ToShortTimeString() + " remote"+"\u2028");
                    }
                    richTextBox1.AppendText(richtext + "\u2028");                
                }
                previousrichtext = richtext;
            }
            catch (Exception) { listBox1.Items.Add("timer1 write error"); }

            if (sent == 1)
            {
                richTextBox2.Enabled = false;
                button4.Enabled = false;
                sent = 0;
                try
                {
                    timer1str = richTextBox2.Lines;
                    if (timer1i < timer1str.Length)
                    {
                        ASCIIEncoding asen = new ASCIIEncoding();
                        s.Send(asen.GetBytes(timer1str[timer1i]+"   "));
                        timer1i++;
                        sent = 1;
                    }
                }
                catch (Exception) { listBox1.Items.Add("timer1 send rtf error"); }
            }
         
            if(sent==0)
            {
                timer1i = 0;
                richTextBox2.Enabled = true;

                try
                {
                    string str = "echo";
                    ASCIIEncoding asen = new ASCIIEncoding();
                    s.Send(asen.GetBytes(str));
                }
                catch (Exception) { listBox1.Items.Add("timer1 send echo error"); }

                button4.Enabled = true;
            }
        }

        //remote timer
        private void timer2_Tick(object sender, EventArgs e)
        {
            Stream stm = x.GetStream();

            try
            {
                byte[] bb = new byte[1000];
                int k = stm.Read(bb, 0, 1000);

                string richtext = "";
                for (int i = 0; i < k; i++)
                {
                    richtext += (Convert.ToChar(bb[i])).ToString();
                }
         
                if (richtext != "echo")
                {
                    if (previousrichtext == "echo")
                    {
                        DateTime now = DateTime.Now;
                        richTextBox1.AppendText(now.ToShortDateString() + " " + now.ToShortTimeString() + " remote" + "\u2028");
                    }
                    richTextBox1.AppendText(richtext + "\u2028");
                }
                previousrichtext = richtext;
            }
            catch (Exception) { listBox1.Items.Add("timer2 write error"); }

            if (sent == 1)
            {
                richTextBox2.Enabled = false;
                button4.Enabled = false;
                sent = 0;
                try
                {
                    timer2str = richTextBox2.Lines;
                    if (timer2i < timer2str.Length)
                    {

                        ASCIIEncoding asen = new ASCIIEncoding();
                        byte[] ba = asen.GetBytes(timer2str[timer2i]+"  ");
                        stm.Write(ba, 0, ba.Length);
                        timer2i++;
                        sent = 1;
                    }
                 
                }
                catch (Exception) { listBox1.Items.Add("timer2 send rtf error"); }
            }
         
            if(sent==0)
            {
                timer2i = 0;
                richTextBox2.Enabled = true;

                try
                {
                    string str = "echo";
                    ASCIIEncoding asen = new ASCIIEncoding();
                    byte[] ba = asen.GetBytes(str);
                    stm.Write(ba, 0, ba.Length);
                }
                catch (Exception) { listBox1.Items.Add("timer2 sent echo error"); }

                button4.Enabled = true;
            }
        }

        //send message
        private void button4_Click(object sender, EventArgs e)
        {
            sent = 1;
            DateTime now = DateTime.Now;
            richTextBox1.AppendText(now.ToShortDateString() + " " + now.ToShortTimeString() + " me" + "\u2028");
            richTextBox1.Text += richTextBox2.Text;
        }

        //save
        private void button6_Click(object sender, EventArgs e)
        {
            richTextBox1.SaveFile(@"C:\Users\abc\Desktop\chathistory.rtf", RichTextBoxStreamType.RichText);
        }

    }
}

----------------------------------------------------------------------------------------------------
//class1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace net
{
    static class Class1
    {
        private static Form1 x = new Form1();
        public static Form1 mainForm
        {
            set { x = value; }
            get { return x; }
        }

        private static bool y;
        public static bool isremote
        {
            set { y = value; }
            get { return y; }
        }

        public static bool remote
        {
            get { return y; }
        }

        private static bool z;
        public static bool ishost
        {
            set { z = value; }
            get { return z; }
        }

        public static bool host
        {
            get { return z; }
        }
       
    }
}

--------------------------------------------------------------------------------------
form2.cs

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

namespace net
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Class1.ishost = true;
            Class1.isremote = false;
            this.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Class1.isremote = true;
            Class1.ishost = false;
            this.Close();
        }
    }
}

--------------------------------------------------------------------------------
//program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace net
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(Class1.mainForm);
        }
    }
}


c# richtextbox