Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, November 20, 2013

Thursday, June 13, 2013

C# Code to count kbps and download files from url

using System;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace Example
{
    public partial class Form1 : Form
    {

        string FileURL = "www.google.com";//your Url

        public Form1()
        {
            InitializeComponent();
        }

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

        private void DownloadString(string URLStr)
        {
            WebClient WC = new WebClient();
            WC.DownloadProgressChanged += new DownloadProgressChangedEventHandler(WC_DownloadProgressChanged);
            WC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(WC_DownloadStringCompleted);
            WC.DownloadStringAsync(new Uri(URLStr));

        }
        string Result = "";
        void WC_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            Result = e.Result;
        }

        void WC_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            //Progress Bar
            PBarCsv.Value = (int)((e.BytesReceived * 100) / e.TotalBytesToReceive);
            //Label For You File Total Byte
            LblTotByt.Text = "Total Bytes : " + e.TotalBytesToReceive.ToString();
            //Label For Remaining Bytes
            LblRemByt.Text = "Remain Bytes : " + (e.TotalBytesToReceive - e.BytesReceived).ToString();
            //Label For Current KBPS Download Speed
            lblSpeed.Text = "KBPS : " + ConvertBytes(e.BytesReceived).ToString() + " Speed";
        }

        private double ConvertBytes(long bytes)
        {
            return (bytes / 1024);
            //return (bytes / 1024f) / 1024f;
        }        

Monday, June 10, 2013

Delegate In C#

using System;

namespace ConsoleApplication1
{
    class Program
    {
        public delegate void Del(string message);
        static void Main(string[] args)
        {
            // Instantiate the delegate.
            Del handler = DelegateMethod;

            // Call the delegate.
            for (int i = 0; i < 9; i++)
            {
                handler("Hello World " + i.ToString());
            }

            
            Console.ReadKey();
        }

        // Create a method for a delegate. 
        public static void DelegateMethod(string message)
        {
            System.Console.WriteLine(message);
        }
    }
}

Result
Hello World 0
Hello World 1
Hello World 2
Hello World 3
Hello World 4
Hello World 5
Hello World 6
Hello World 7
Hello World 8

Properties In C#

using System;
class Student
{

   // Declare a Code property of type string
   private string iCode = "Nothing";
   public string Code
   {
      get
      {
         return iCode;
      }
      set
      {
         iCode = value;
      }
   }
   
   // Declare a Name property of type string
   private string iName = "Alfread";
   public string Name
   {
      get
      {
         return iName;
      }
      set
      {
         iName= value;
      }
   }

   // Declare a Age property of type int:
   private int iAge= 15;
   public int Age
   {
      get
      {
         return iAge;
      }
      set
      {
         iAge = value;
      }
   }
   public override string ToString()
   {
      return "Code = " + iCode+", Name = " + iName + ", Age = " + iAge ;
   }

   public static void Main()
   {
      // Create a new Student object:
      Student s = new Student();
            
      // Setting code, name and the age of the student
      s.Code = "001";
      s.Name = "Zara";
      s.Age = 9;
      Console.WriteLine("Student Info: {0}", s);
      //let us increase age
      s.Age += 1;
      Console.WriteLine("Student Info: {0}", s);
      Console.ReadKey();
    }
}

C# Read And Write Byte In File With File Stream

using System;
using System.IO;

namespace FileIOApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream F = new FileStream("test.dat", 
            FileMode.OpenOrCreate, FileAccess.ReadWrite);

            for (int i = 1; i <= 20; i++)
            {
                F.WriteByte((byte)i);
            }

            F.Position = 0;

            for (int i = 0; i <= 20; i++)
            {
                Console.Write(F.ReadByte() + " ");
            }
            F.Close();
            Console.ReadKey();
        }
    }
}

C# Creating User Defined Exceptions

using System;
namespace UserDefinedException
{
   class TestTemperature
   {
      static void Main(string[] args)
      {
         Temperature temp = new Temperature();
         try
         {
            temp.showTemp();
         }
         catch(TempIsZeroException e)
         {
            Console.WriteLine("TempIsZeroException: {0}", e.Message);
         }
         Console.ReadKey();
      }
   }
}
public class TempIsZeroException: ApplicationException
{
   public TempIsZeroException(string message): base(message)
   {
   }
}
public class Temperature
{
   int temperature = 0;
   public void showTemp()
   {
      if(temperature == 0)
      {
         throw (new TempIsZeroException("Zero Temperature found"));
      }
      else
      {
         Console.WriteLine("Temperature: {0}", temperature);
      }
   }
}

C# Exception Handling

try
{
   // statements causing exception
}
catch( ExceptionName e1 )
{
   // error handling code
}
catch( ExceptionName e2 )
{
   // error handling code
}
catch( ExceptionName eN )
{
   // error handling code
}
finally
{
   // statements to be executed
}

try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.

catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

throw: A program throws an exception when a problem shows up. This is done using a throw keyword.

Example

using System;
namespace ErrorHandlingApplication
{
    class DivNumbers
    {
        int result;
        DivNumbers()
        {
            result = 0;
        }
        public void division(int num1, int num2)
        {
            try
            {
                result = num1 / num2;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Exception caught: {0}", e);
            }
            finally
            {
                Console.WriteLine("Result: {0}", result);
            }

        }
        static void Main(string[] args)
        {
            DivNumbers d = new DivNumbers();
            d.division(25, 0);
            Console.ReadKey();
        }
    }

}

C# Namespaces

using System;
namespace first_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside first_space");
      }
   }
}
namespace second_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside second_space");
      }
   }
}  
class TestClass
{
   static void Main(string[] args)
   {
      first_space.namespace_cl fc = new first_space.namespace_cl();
      second_space.namespace_cl sc = new second_space.namespace_cl();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

C# Interfaces

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

namespace InterfaceApplication
{

public interface ITransactions
{
    // interface members
    void showTransaction();
    double getAmount();
}

public class Transaction : ITransactions
{
    private string tCode;    private string date;
    private double amount;


    public Transaction()
    {
        tCode = " ";
        date = " ";
        amount = 0.0;
    }
    public Transaction(string c, string d, double a)    {
        tCode = c;
        date = d;
        amount = a;
    }    public double getAmount()    {
        return amount;
    }    public void showTransaction()    {
        Console.WriteLine("Transaction: {0}", tCode);
        Console.WriteLine("Date: {0}", date);        Console.WriteLine("Amount: {0}", getAmount());
    }
}
    class Tester
    {
       static void Main(string[] args)
        {            Transaction t1 = new Transaction("001", "8/10/2012",         78900.00);
            Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);

            t1.showTransaction();
            t2.showTransaction();

            Console.ReadKey();
        }
    }
}

Result:
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

C# Inheritance

Base and Derived Classes

A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base class or interface.


The syntax used in C# for creating derived classes is as follows:


class

{
 ...
}
class :
{
 ...
}

Example


using System;

namespace InheritanceApplication
{
   class Shape 
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // Derived class

   class Rectangle: Shape
   {
      public int getArea()
      { 
         return (width * height); 
      }
   }
   
   class RectangleTester
   {
      static void Main(string[] args)
      {
         Rectangle Rect = new Rectangle();

         Rect.setWidth(5);

         Rect.setHeight(7);

         // Print the area of the object.

         Console.WriteLine("Total area: {0}",  Rect.getArea());
         Console.ReadKey();
      }
   }

}

Result

Total area: 35

C# Declaring enum Variable

Example
using System;
namespace EnumApplication
{
    class EnumProgram
    {
        enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
        static void Main(string[] args)
        {
             int WeekdayStart = (int)Days.Mon;
             int WeekdayEnd = (int)Days.Fri;
             Console.WriteLine("Monday: {0}", WeekdayStart);
             Console.WriteLine("Friday: {0}", WeekdayEnd);
             Console.ReadKey();
        }
    }
}

Result
Monday:1
Friday:5

C# Defining a Structure

struct Books
{
   public string title;
   public string author;
   public string subject;
   public int book_id;
};

The following program shows the use of the structure:

using System;
   
struct Books
{
   public string title;
   public string author;
   public string subject;
   public int book_id;
};

public class testStructure
{
   public static void Main(string[] args)
   {

      Books Book1;        /* Declare Book1 of type Book */
      Books Book2;        /* Declare Book2 of type Book */

      /* book 1 specification */
      Book1.title = "C# Programming";
      Book1.author = "Ali Rabjar";
      Book1.subject = "C# Programming";
      Book1.book_id = 123456;

      /* book 2 specification */
      Book2.title = "Billing";
      Book2.author = "Ali";
      Book2.subject =  "Billing";
      Book2.book_id =56789123;

      /* print Book1 info */
      Console.WriteLine( "Book 1 title : {0}", Book1.title);
      Console.WriteLine("Book 1 author : {0}", Book1.author);
      Console.WriteLine("Book 1 subject : {0}", Book1.subject);
      Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);

      /* print Book2 info */
      Console.WriteLine("Book 2 title : {0}", Book2.title);
      Console.WriteLine("Book 2 author : {0}", Book2.author);
      Console.WriteLine("Book 2 subject : {0}", Book2.subject);
      Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);    

      Console.ReadKey();

   }
}

it produces following result:

Book 1 title : C# Programming
Book 1 author : Ali Rabjar
Book 1 subject : C# Programming
Book 1 book_id : 123456
Book 2 title : Billing
Book 2 author : Ali
Book 2 subject : Billing
Book 2 book_id : 56789123

C# The Null Coalescing Operator (??)

using System;

namespace CalculatorApplication
{
   class NullablesAtShow
   {
         
      static void Main(string[] args)
      {
         
         double? num1 = null;
         double? num2 = 3.14157;
         double num3;
         num3 = num1 ?? 5.34;      
         Console.WriteLine(" Value of num3: {0}", num3);
         num3 = num2 ?? 5.34;
         Console.WriteLine(" Value of num3: {0}", num3);
         Console.ReadLine();

      }
   }
}
When the above code is compiled and executed, it produces following result:
Value of num3: 5.34
Value of num3: 3.14157

Nullable in C#

C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable< Int32 > variable. Similarly, you can assign true, false or null in a Nullable< bool > variable. Syntax for declaring a nullable type is as follows:
< data_type> ?  = null;
The following example demonstrates use of nullable data types:
using System;
namespace CalculatorApplication
{
   class NullablesAtShow
   {
      static void Main(string[] args)
      {
         int? num1 = null;
         int? num2 = 45;
         double? num3 = new double?();
         double? num4 = 3.14157;
         
         bool? boolval = new bool?();

         // display the values
         
         Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}", 
                            num1, num2, num3, num4);
         Console.WriteLine("A Nullable boolean value: {0}", boolval);
         Console.ReadLine();

      }
   }
}
When the above code is compiled and executed, it produces following result:
Nullables at Show: , 45,  , 3.14157
A Nullable boolean value:

C# Recursive Method Call

A method can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function:

using System;

namespace CalculatorApplication
{
    class NumberManipulator
    {
        public int factorial(int num)
        {
            /* local variable declaration */
            int result;

            if (num == 1)
            {
                return 1;
            }
            else
            {
                result = factorial(num - 1) * num;
                return result;
            }
        }
    
        static void Main(string[] args)
        {
            NumberManipulator n = new NumberManipulator();
            //calling the factorial method
            Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
            Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
            Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
            Console.ReadLine();

        }
    }
}
When the above code is compiled and executed, it produces following result:
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

Calling Methods in C#

You can call a method using the name of the method. The following example illustrates this:

using System;

namespace CalculatorApplication
{
   class NumberManipulator
   {
      public int FindMax(int num1, int num2)
      {
         /* local variable declaration */
         int result;

         if (num1 > num2)
            result = num1;
         else
            result = num2;

         return result;
      }
      static void Main(string[] args)
      {
         /* local variable definition */
         int a = 100;
         int b = 200;
         int ret;
         NumberManipulator n = new NumberManipulator();

         //calling the FindMax method
         ret = n.FindMax(a, b);
         Console.WriteLine("Max value is : {0}", ret );
         Console.ReadLine();
      }
   }
When the above code is compiled and executed, it produces following result:
Max value is : 200
You can also call public method from other classes by using the instance of the class. For example, the method FindMax belongs to the NumberManipulator class, you can call it from another class Test.
using System;

namespace CalculatorApplication
{
    class NumberManipulator
    {
        public int FindMax(int num1, int num2)
        {
            /* local variable declaration */
            int result;

            if (num1 > num2)
                result = num1;
            else
                result = num2;

            return result;
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            /* local variable definition */
            int a = 100;
            int b = 200;
            int ret;
            NumberManipulator n = new NumberManipulator();
            //calling the FindMax method
            ret = n.FindMax(a, b);
            Console.WriteLine("Max value is : {0}", ret );
            Console.ReadLine();

        }
    }
}
When the above code is compiled and executed, it produces following result:
Max value is : 200