Wednesday, August 22, 2012

How to use Operator Overloading in C#?


In this article, we will discuss operator overloading in C#. It means that we are defining an operator for a class. It is very like method overloading. We can declare it with the help of the operator keyword like this:
public static calculation operator /(calculation op1, calculation op2){}
Here we define an operator (/) with the operator keyword.
Declaration: We can generally declare it this way:

For Unary:
public static ret-type operator  op(parameter-type operand){}
For Binary
public static ret-type operator  op(parameter-type operand1, parameter-type operand1){}
Example:

First we look at an example of a unary operator(++):
class calculation{   int a, b, c;   public calculation()   {       a = b = c = 0;   }   public calculation(int x, int y, int z)   {       a = x;       b = y;       c = z;   }    public static calculation operator ++(calculation op1)   {       op1.a++;       op1.b++;       op1.c++;       return op1;   }   public void ShowTheResult()   {       Console.WriteLine(a + "," + b + "," + c);       Console.ReadLine();   }}class Program{    static void Main(string[] args)    {        calculation i = new calculation(10, 20, 30);        calculation j = new calculation(5, 10, 3);        calculation k = new calculation();        i++;        i.ShowTheResult();        Console.WriteLine();    }}

Here we use the ++ operator so the values 10, 20, 30 will be 11, 21, 31.

Now we look at an example of a binary operator; here we do the calculations like (+,-,*,/) with the help of operator overloading.

Here we create a Class Calculation in our program like this:
class calculation{     int a, b, c;     public calculation()     {         a = b = c = 0;     }     public calculation(int x, int y, int z)     {         a = x;         b = y;         c = z;     }     public static calculation operator +(calculation op1, calculation op2)     {         calculation calc = new calculation();         calc.a = op1.a + op2.a;         calc.b = op1.b + op2.b;         calc.c = op1.c + op2.c;         return calc;    }    public static calculation operator -(calculation op1, calculation op2)    {         calculation calc = new calculation();         calc.a = op1.a - op2.a;         calc.b = op1.b - op2.b;         calc.c = op1.c - op2.c;         return calc;    }    public static calculation operator *(calculation op1, calculation op2)    {         calculation calc = new calculation();         calc.a = op1.a * op2.a;         calc.b = op1.b * op2.b;         calc.c = op1.c * op2.c;    }    public static calculation operator /(calculation op1, calculation op2)    {         calculation calc = new calculation();         calc.a = op1.a / op2.a;         calc.b = op1.b / op2.b;         calc.c = op1.c / op2.c;         return calc;    }  
    public void ShowTheResult()    {         Console.WriteLine(a + "," + b + "," + c);         Console.ReadLine();    }}
Here we define the operators and a function (ShowTheResult()) to show the output. After that we write the following code in the Program class. By this the addition will be performed and the result will be shown with the help of The ShowTheResult() function.
 
class Program{    static void Main(string[] args)    {        calculation j = new calculation(5, 10, 3);        calculation k = new calculation();        k = i + j;        k.ShowTheResult();        Console.WriteLine();    }}

For subtraction, multiplication and division we write the following code:
class Program{     static void Main(string[] args)     {         calculation i = new calculation(10, 20, 30);         calculation j = new calculation(5, 10, 3);         calculation k = new calculation();         k = i - j;         k.ShowTheResult();         Console.WriteLine();               }}
Multiplyclass Program{
     static void Main(string[] args)
     {
         calculation i = new calculation(10, 20, 30);
         calculation j = new calculation(5, 10, 3);
         calculation k = new calculation();
         k = i * j;
         k.ShowTheResult();
         Console.WriteLine();
     }
 }
Division
class Program{     static void Main(string[] args)     {         calculation i = new calculation(10, 20, 30);         calculation j = new calculation(5, 10, 3);         calculation k = new calculation();         k = i / j;         k.ShowTheResult();         Console.WriteLine();    }
}


Checking the availability of a word in a sentence ?


Here in this post I have given an example that shows how to check the availability of a word in a given sentence using C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace CheckAvailability
{
    class Program
    {
        static void Main(string[] args)
        {

            string data = "Prahalad is the king of Programming ";
            Console.WriteLine("{0}\n\n",data);

            Console.WriteLine("Enter a word to check the availability from the above sentence\n");
            string get = Console.ReadLine();
            bool result = data.Contains(get);
            if (result == true)
            {
                Console.WriteLine("Data {0} is available",get);
            }
            else
                Console.WriteLine("Data {0} is not available",get);

            Console.Read();
        }
    }
}

thank you

What is WPF?


Windows Presentation Foundation (WPF) is the code-name of the presentation (user-interfaces) sub system in Windows programming model and is used to create user interfaces. This blog talks about WPF.
If you have been programming .NET, you must be familiar with Windows Forms and ASP.NET. Windows Forms are used to build Windows client application and ASP.NET is used to build Web applications.
Well, WPF is a new technology that may be used instead of both Windows Forms and ASP.NET.
What is WPF?
WPF is the engine that is responsible for creating, displaying, and manipulating user-interfaces, documents, images, movies, and media in Windows Vista.
Physically, WPF is a set of libraries that have all functionality you need to build, run, execute, and manage Windows Vista applications.
What is XAML?
XAML is a new descriptive programming language developed by Microsoft to write user interfaces for next generation managed applications.
How XAML is related to WPF?
XAML is a new descriptive programming language developed by Microsoft to write user interfaces for next generation managed applications. XAML is used in WPF to represent the controls and code with the help of C#, Visual Basic, and other .NET Framework languages.

XAML can be think as ASP.NET and/or Windows Forms in Windows Vista. For example, to write a Web application in .NET 1.0, 1.1, or 2.0, you use ASP.NET and to write Windows Applications, you use Windows Forms. Now in Windows Vista and .NET 3.0, you will use XAML instead of Windows Forms and ASP.NET.

Does that mean XAML will replace ASP.NET and Windows Forms? YES and NO. Both ASP.NET and Windows Forms will also be supported on .NET 3.0 but you don't have to use them if you don't want.
What Operating Systems does WPF support?
Windows Vista, Windows XP, and Windows 2003 Server.
How do I build WPF Applicaitons?
To build WPF application, you must install .NET 3.5 SDK. You can also also Visual Studio 2010 and 2008. These two comes with WPF. If you are a student or beginner, you may want to try free version of Visual C# Express 2008 here.

Alternatively, you can download other versions on MSDN.
What do I need to run WPF Applications?
To run WPF applications, you must install .NET 3.5 or 4.0 SDK redistributable. It can be found on MSDN downloads sites.

How to use GZipStream ??



Here i will give you one examples which implements GZipstream class.

You just go through the program which is written in C# language


using System.IO;
using System.IO.Compression;
using System.Text;

class Program
{
    static void Main()
    {
 try
 {
     // 1.
     // Starting file is 26,747 bytes.
     string anyString = File.ReadAllText("TextFile1.txt");

     // 2.
     // Output file is 7,388 bytes.
     CompressStringToFile("new.gz", anyString);
 }
 catch
 {
     // Couldn't compress.
 }
    }

    public static void CompressStringToFile(string fileName, string value)
    {
 // A.
 // Write string to temporary file.
 string temp = Path.GetTempFileName();
 File.WriteAllText(temp, value);

 // B.
 // Read file into byte array buffer.
 byte[] b;
 using (FileStream f = new FileStream(temp, FileMode.Open))
 {
     b = new byte[f.Length];
     f.Read(b, 0, (int)f.Length);
 }

 // C.
 // Use GZipStream to write compressed bytes to target file.
 using (FileStream f2 = new FileStream(fileName, FileMode.Create))
 using (GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false))
 {
     gz.Write(b, 0, b.Length);
 }
    }
}

Result
    Starting file is 26,747 bytes.
    Output file is 7,388 bytes.

Monday, July 30, 2012

How to use FileSystemWatcher class ?

Here is the sample code ,,just try it,,,

working properly


code:


namespace FileMonitor  
{ 
    public interface EventsList 
    { 
        void OnRenamed(object source, RenamedEventArgs e); 
        void OnChanged(object source, FileSystemEventArgs e); 
    } 
      
    public  class MonitorEngine  
    { 
        private String path; 
        private EventsList events = null; 
     
        public MonitorEngine(String path,EventsList ev) 
        { 
            this.events=ev; 
            this.path=path; 
        } 
        public void WatcherFiles() 
        { 
            FileSystemWatcher watcher = new FileSystemWatcher(); 
            try 
            { 
                watcher.Path = path; 
                watcher.IncludeSubdirectories=true; 
            } 
            catch(ArgumentException ex)  
            { 
                MessageBox.Show(ex.Message); 
                return; 
            } 
             
            // setup what we are looking for 
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite| 
                                   NotifyFilters.FileName  | NotifyFilters.DirectoryName; 
             
            watcher.Filter = "*.*"; 
             
            // Add event handlers. 
            watcher.Changed += new FileSystemEventHandler(events.OnChanged); 
            watcher.Created += new FileSystemEventHandler(events.OnChanged); 
            watcher.Deleted += new FileSystemEventHandler(events.OnChanged); 
            watcher.Renamed += new RenamedEventHandler(events.OnRenamed); 
         
            // Begin watching the directory. 
            watcher.EnableRaisingEvents = true;  
             
        } 
    } 
} 

Friday, July 27, 2012

How to show a message box in windows application?



just wirte down

System.windows.forms.messagebox.show("string");

Tuesday, July 24, 2012

How to make a textbox multiline in WPF?

the only think u have to do is add the property as follows


   1. TextWrapping="Wrap"
   2. VerticalScrollBarVisibility="Visible"
   3. AcceptsReturn="True"

Monday, July 23, 2012

How to make serial communication in .NET?


The first think, just kept in your mind dnt forget to include the namespace.
using System.IO.Ports;

using System.Data;
using System.Threading;


then next step ,go to your mainwindow.xaml.cs page

add the corresponding code to the related controls.

Sample code:


public partial class MainWindow : Window
    {
        #region variables
        //Richtextbox
        FlowDocument mcFlowDoc = new FlowDocument();
        Paragraph para = new Paragraph();
        //Serial
        SerialPort serial = new SerialPort();
        string recieved_data;
        #endregion


        public MainWindow()
        {
            InitializeComponent();
            InitializeComponent();
            Connect_btn.Content = "Connect";
        }

        private void Connect_Comms(object sender, RoutedEventArgs e)
        {
            if (Connect_btn.Content == "Connect")
            {
                serial.PortName = Comm_Port_Names.Text;
                serial.BaudRate = Convert.ToInt32(Baud_Rates.Text);
                serial.Handshake = System.IO.Ports.Handshake.None;
                serial.Parity = Parity.None;
                serial.DataBits = 8;
                serial.StopBits = StopBits.Two;
                serial.ReadTimeout = 200;
                serial.WriteTimeout = 50;
                serial.Open();

                Connect_btn.Content = "Disconnect";
                serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Recieve);

            }
            else
            {
                try // just in case serial port is not open could also be acheved using if(serial.IsOpen)
                {
                    serial.Close();
                    Connect_btn.Content = "Connect";
                }
                catch
                {
                }
            }
        }

        #region Recieving

        private delegate void UpdateUiTextDelegate(string text);
        private void Recieve(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            // Collecting the characters received to our 'buffer' (string).
            recieved_data = serial.ReadExisting();
            Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteData), recieved_data);
        }
        private void WriteData(string text)
        {
            // Assign the value of the recieved_data to the RichTextBox.
            para.Inlines.Add(text);
            mcFlowDoc.Blocks.Add(para);
            Commdata.Document = mcFlowDoc;
        }

        #endregion


        #region Sending       
       
        private void Send_Data(object sender, RoutedEventArgs e)
        {
            SerialCmdSend(SerialData.Text);
            SerialData.Text = "";
        }
        public void SerialCmdSend(string data)
        {
            if (serial.IsOpen)
            {
                try
                {
                    // Send the binary data out the port
                    byte[] hexstring = Encoding.ASCII.GetBytes(data);
                    //There is a intermitant problem that I came across
                    //If I write more than one byte in succesion without a
                    //delay the PIC i'm communicating with will Crash
                    //I expect this id due to PC timing issues ad they are
                    //not directley connected to the COM port the solution
                    //Is a ver small 1 millisecound delay between chracters
                    foreach (byte hexval in hexstring)
                    {
                        byte[] _hexval = new byte[] { hexval }; // need to convert byte to byte[] to write
                        serial.Write(_hexval, 0, 1);
                        Thread.Sleep(1);
                    }
                }
                catch (Exception ex)
                {
                    para.Inlines.Add("Failed to SEND" + data + "\n" + ex + "\n");
                    mcFlowDoc.Blocks.Add(para);
                    Commdata.Document = mcFlowDoc;
                }
            }
            else
            {
            }
        }

        #endregion


        #region Form Controls

        private void Close_Form(object sender, RoutedEventArgs e)
        {
            if (serial.IsOpen) serial.Close();
            this.Close();
        }
        private void Max_size(object sender, RoutedEventArgs e)
        {
            if (this.WindowState != WindowState.Maximized) this.WindowState = WindowState.Maximized;
            else this.WindowState = WindowState.Normal;
        }
        private void Min_size(object sender, RoutedEventArgs e)
        {
            if (this.WindowState != WindowState.Minimized) this.WindowState = WindowState.Minimized;
            else this.WindowState = WindowState.Normal;
        }
        private void Move_Window(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        #endregion
    }


Here you can see some objects of each controls, you simply just understand what the controls I put here. If you want to change the name of object means you can do it, it’s ur wish.

Just try it


its 100% working....