Saturday 2 November 2013

Calling a method present in dll with out adding reference to project using Reflection

In this article we are going to see how to execute the method present in the dll, with out reference inside the project using Reflection.Reflection is used to load the dll in runtime and expose the methods , properties etc.

first create a Dll using class library project with following code,

  public class Operation
    {
        public bool IsReadOnly
        {
            get { return false; }
        }

        public int Addition(params int []vals)
        {
            int temp = 0;
            foreach (var eachnum in vals)
            {
                temp += eachnum;
            }
            return temp;
        }

        public int Subtraction(int val1, int val2)
        {
            try
            {
                return val1 - val2;
            }
            catch
            {
                return -1;
            }
        }
    }



This class operation consists of two methods one for addition and another for subtraction, Now a dll is generated Mathematics.dll





Now create a Console application which is used to load the dll at runtime , and execute the subtracion at runtime with out adding reference.


static void Main(string[] args)
        {
            Assembly assem_refer = Assembly.LoadFrom(@"D:\Project\StyleManager\Assembly_Reference\Mathematics.dll");
            Type typ = assem_refer.GetTypes()[0];
            object obj = Activator.CreateInstance(typ);

            /* Fetch the method info */
            MethodInfo []method = typ.GetMethods();
            Console.WriteLine();
            Console.WriteLine("Methods are present in Dll exposed using Reflection");
            Console.WriteLine();
            /* Execute the method */
            foreach (MethodInfo meth in method)
            {
                Console.WriteLine(meth.Name);   
            }
            Console.WriteLine();
            //executing a method
            MethodInfo sub =method.Where(x=>x.Name=="Subtraction").First();
            Console.WriteLine("Method Name :" + sub.Name);
            object[] param = new object[] { 5, 3 };
            var result = sub.Invoke(obj, param);
            Console.WriteLine("Values passed as Parameter {0},{1} Result is {2} ", 5, 3, result);

            Console.Read();
        }





Output  :



From this article you can learn how to load dll in runtime.




Friday 1 November 2013

C# - Various Ways to Write in a Text File

In C# we can create a file and write the content in various ways,In this article we will see that how we can create a file in various ways, check the existence of file in computer , delete the file and rename the file

Create a File and Write the Content ;

Way 1 :
In this example we are going to create a File and write the content in each and every line with increment in number up to 10000 lines in a second.

class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i <=10000; i++)
            {
                WriteLog(string.Format(" Value {0} "+Environment.NewLine,i));
            }
            Console.Read();
        }

        static void WriteLog(string message)
        {
            File.AppendAllText(@"D:\sample.txt", message);
        }
    }


 Output:

Way 2:
This example uses the filestream class in which we can change the settings options , and streamwriter class to write the content in file.   writer.Flush(); method is important if this method is not called then file will create but content will not write. if close is mentioned then at finally content will be write in file.

static void Main(string[] args)
        {
            FileStream fs=new FileStream(@"D:\sample.txt",FileMode.Append);
            StreamWriter writer = new StreamWriter(fs);
            writer.WriteLine("Hi this is testing application !/");
            writer.WriteLine("I am Rajesh");
            writer.WriteLine(":)");
            writer.Flush();
            writer.Close();
            fs.Close();
            Console.Read();
        }







Use File.Delete(@"D:\sample.txt") method to delete a file in particular path

To Check whether File is present in the particular path use the File.Exists(@"D:\sample.txt") method.

I Hope from this article you will learn how to create  a text file and write the content in it. as well delete and file exists 




Thursday 31 October 2013

Sending File from one computer to another using C#

     
In this article we are going to see how to send a file from one computer to another using TCP protocol.
now in this example i am taking my own laptop as Client and server, so IpAddress are same when you want to send to different mention the correct IpAddress and binding Port Number.

For Server Side Code 
C# :

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.Net.Sockets;
using System.Net;
using System.IO;

namespace RServer
{
    public partial class Form1 : Form
    {

        public delegate void Add(String Message);

        Add mess;
        public void AddMessage(String Message)
        {
            listBox1.Items.Add(Message);
        }

        public Form1()
        {
            InitializeComponent();
            mess = new Add(AddMessage);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(StartTcpServer);
        }

        public  string GetIP()
        {
            string name = Dns.GetHostName();
            IPHostEntry entry= Dns.GetHostEntry(name);
            IPAddress[] addr = entry.AddressList;
            if (addr[1].ToString().Split('.').Length == 4)
            {
                return addr[1].ToString();
            }
            return addr[2].ToString();
        }

        public void Message(string data)
        {
            listBox1.BeginInvoke(mess, data);

        }

        public  void StartTcpServer(object state)
        {
            TcpListener filelistener = new TcpListener(IPAddress.Parse(GetIP()),8085);
            filelistener.Start();
            TcpClient client = filelistener.AcceptTcpClient();
            Message("Client connection accepted from :" + client.Client.RemoteEndPoint + ".");
            byte []buffer = new byte[1500];
            int bytesread = 1;

            StreamWriter writer = new StreamWriter("D:\\sample.rar");

            while (bytesread > 0)
            {
                bytesread= client.GetStream().Read(buffer, 0, buffer.Length);
                if (bytesread == 0)
                    break;
                writer.BaseStream.Write(buffer, 0, buffer.Length);
                Message(bytesread + " Received. ");
            }
            writer.Close();

        }
    }
}



For Client Side Code:
C# :

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.IO;
using System.Net.Sockets;
using System.Net;

namespace RServer
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }

        public string GetIP()
        {
            string name = Dns.GetHostName();
            IPHostEntry entry = Dns.GetHostEntry(name);
            IPAddress[] addr = entry.AddressList;
            if (addr[1].ToString().Split('.').Length == 4)
            {
                return addr[1].ToString();
            }
            return addr[2].ToString();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                StreamReader sr = new StreamReader(textBox1.Text);

                TcpClient tcpClient = new TcpClient();
                tcpClient.Connect(new IPEndPoint(IPAddress.Parse(GetIP()), 8085));

                byte[] buffer = new byte[1500];
                long bytesSent = 0;

                while (bytesSent < sr.BaseStream.Length)
                {
                    int bytesRead = sr.BaseStream.Read(buffer, 0, 1500);
                    tcpClient.GetStream().Write(buffer, 0, bytesRead);
                    Message(bytesRead + " bytes sent.");

                    bytesSent += bytesRead;
                }

                tcpClient.Close();

                Message("finished");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void Message(string data)
        {
            listBox1.Items.Add(data);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.ShowDialog();
            textBox1.Text = op.FileName;
        }

    }
}




Output :
Server


Client



I Hope from this article you can learn how to send file from computer to another.

C# - Create a Chat Application Client - Server







In this article we are going to see how to create a chat application using C#, for this we have to create a two projects in Console Applications one for client and another for server.

please dis-connet the internet while checking with this code.

Server:

First Let we see about Server, Which will get the request from client .Get the IP address of the Server Machine and Get the username and Port at which server has to watch for request.Socket is the used to receive and accept the request in TCP as stream.

C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ChatServer
{
    class Program
    {
        static Socket soc;
        static Socket acc;
        static int port = 9000;
        static IPAddress ip;
        static Thread rec;
        static string name;

        static string GetIp()
        {
            string hostname = Dns.GetHostName();
            IPHostEntry ipentry = Dns.GetHostEntry(hostname);
            IPAddress[] addr = ipentry.AddressList;
            return addr[addr.Length - 1].ToString();
        }


        static void RecV()
        {
            while (true)
            {
                Thread.Sleep(500);
                byte[] buffer = new byte[300];
                int rece = acc.Receive(buffer, 0, buffer.Length, 0);
                Array.Resize(ref buffer, rece);
                Console.WriteLine(Encoding.Default.GetString(buffer));
            }
        }



        static void Main(string[] args)
        {
            rec = new Thread(RecV);
            Console.WriteLine("Your Local Ip is " + GetIp());
            Console.WriteLine("Please enter your name");
            name = Console.ReadLine();
            Console.WriteLine("Please enter HostPort");
            string prt = Console.ReadLine();

            try
            {
                port = Convert.ToInt32(prt);
            }
            catch
            {
                port = 9000;
            }

            ip = IPAddress.Parse(GetIp());
            soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            soc.Bind(new IPEndPoint(ip, port));
            soc.Listen(0);
            acc = soc.Accept();
            rec.Start();
            while (true)
            {
                byte[] sdata = Encoding.Default.GetBytes("<"+name+">"+Console.ReadLine());
                acc.Send(sdata, 0, sdata.Length, 0);
            }


        }
    }
}



Client :

Now we see for the client same steps , but difference is here is send is the request we are make a separate thread for see the message from server.

C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ChatClient
{
    class Program
    {
        static string name;
        static int port = 9000;
        static IPAddress ip;
        static Socket soc;
        static Thread rec;


        static string GetIp()
        {
            string hostname = Dns.GetHostName();
            IPHostEntry ipentry = Dns.GetHostEntry(hostname);
            IPAddress[] addr = ipentry.AddressList;
            return addr[addr.Length - 1].ToString();
        }

        static void RecV()
        {
            while (true)
            {
                Thread.Sleep(500);
                byte[] buffer = new byte[300];
                int rece = soc.Receive(buffer, 0, buffer.Length, 0);
                Array.Resize(ref buffer, rece);
                Console.WriteLine(Encoding.Default.GetString(buffer));
            }
        }

       

        static void Main(string[] args)
        {
            rec = new Thread(RecV);
            Console.WriteLine("Please enter your name");
            name = Console.ReadLine();
            ip = IPAddress.Parse(GetIp());
            Console.WriteLine("Please enter HostPort");
            string prt = Console.ReadLine();

            try
            {
                port = Convert.ToInt32(prt);
            }
            catch
            {
                port = 9000;
            }

            soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            soc.Connect(new IPEndPoint(ip, port));
            rec.Start();
            byte[] data = Encoding.Default.GetBytes("<" + name + "> Connected");
            soc.Send(data, 0, data.Length, 0);

            while (soc.Connected)
            {
                byte[] sdata = Encoding.Default.GetBytes("<" + name + ">" + Console.ReadLine());
                soc.Send(sdata, 0, sdata.Length, 0);

            }

        }
    }
}




Output:

Server ;




Client :




From this article , I hope you can learn how to create a sample chat application.