Monday, 9 May 2011

Download Free PPT of C Sharp

If you are interested to download free PPT of C sharp , Open the link provided below:


http://sharecash.org/download.php?file=1964082


http://sharecash.org/download.php?file=1964081

If you are interested to get ebook of " C Sharp Programming" free ,

Refer this site i.e. http://csharpexpress.blogspot.com to atleast 20 friends and send me the proof to my email address given below:
anujbatta2011@gmail.com
and copy worth 10$ "Programming in C# will be mailed to you after getting proof at my email address.

Note:Email Address you should be valid one.


Sunday, 8 May 2011

How to Add Manually CheckBox in C#


You can add a CheckBox to a form at run time in the following manner.
Code for Add mannualy CheckBox in C#:


public void AddCheckBox()
{
  CheckBox chkBox = new CheckBox();
  chkBox.Location = new Point(50, 50);
 
  chkBox.AutoCheck = true;
  chkBox.Text = "Checked";
  chkBox.Checked = true;
  chkBox.CheckState = CheckState.Checked;
 
  chkBox.CheckedChanged += new EventHandler(chkBox_CheckedChanged);
 
  Controls.Add(chkBox);
}
 
private void chkBox_CheckedChanged(object sender, System.EventArgs e)
{
  if (sender is CheckBox)
  {
    CheckBox checkbox = sender as CheckBox;
    if (checkbox.Checked)
    {
      checkbox.Text = "Checked";
    }
    else
    {
      checkbox.Text = "UnChecked";
    }
  }
}

Synchronization in C#

Synchronization in C#
Introduction of Synchronization- Synchronization is particularly important when threads access the same data; it’s surprisingly easy to run aground in this area.
Synchronization constructs can be divided into four categories:
  • Simple blocking methods
  • Locking constructs
  • Signaling constructs
  • No blocking synchronization constructs
Synchronization in Threads- Synchronization is needed in thread when we have multiple threads that share data, we need to provide synchronized access to the data. We have to deal with synchronization issues related to concurrent access to variables and objects accessible by multiple threads at the same time.

using System;
using System.Threading;
namespace CSharpThreadExample

{
    class Program
    {
        static void Main(string[] arg)
        {
            Console.WriteLine("----->  Multiple Threads ---->");
            Printer p=new Printer();
            Thread[] Threads=new Thread[3];
            for(int i=0;i<3;i++)
            {
                Threads[i]=new Thread(new ThreadStart(p.PrintNumbers));
                Threads[i].Name="Child "+i;
            }
            foreach(Thread t in Threads)
                t.Start();

            Console.ReadLine();
        }
    }
    class Printer
    {
        public void PrintNumbers()
        {
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(100);
                Console.Write(i + ",");
            }
            Console.WriteLine();
        }
    }
}
Why we use Lock keyword-  lock(object)  is used to synchronize the shared object.

Syntax:
lock (objecttobelocked)
{

    objecttobelocked.somemethod();
    }
 
  • objecttobelocked is the object reference which is used by more than one thread to call the method on that object.
  • The lock keyword requires us to specify a token (an object reference) that must be acquired by a thread to enter within the lock scope.
Using of Monitor- The lock scope actually resolves to the Monitor class after being processed by the C# compiler. Lock keyword is just a notation for using System.Threading.Monitor class.

using System;
using System.Threading;
namespace CSharpThreadExample
{
    class Program
    {
        static void Main(string[] arg)
        {
            Console.WriteLine(" ----->  Multiple Threads  ----->");
            Printer p = new Printer();
            Thread[] Threads = new Thread[3];
            for (int i = 0; i < 3; i++)
            {
                Threads[i] = new Thread(new ThreadStart(p.PrintNumbers));
                Threads[i].Name = "Child " + i;
            }
            foreach (Thread t in Threads)
                t.Start();

            Console.ReadLine();
        }
    }
    class Printer
    {
        public void PrintNumbers()
        {
            Monitor.Enter(this);
            try
            {
                for (int i = 0; i < 5; i++)
                {
                    Thread.Sleep(100);
                    Console.Write(i + ",");
                }
                Console.WriteLine();
            }
            finally
            {
                Monitor.Exit(this);
            }
        }
    }
}

How to get IP Address of Websites using C#

How to get IP Address of Websites in C# application
In C# with the help of Namespace System.Net.Sockets and System.Net we can build an application through which we can find ID address of the websites.
Program code is given below-
IPHostEntry - Provides a container class for internet host address information .

Dns.GetHostEntry("Hostname")-
Resolve a DNS hostname or IP Address to an System.Net.IPHostEntry instance.

using System;
using System.Net;
using System.Net.Sockets;

class ip
{
     
    public static void Main()
    {
       String HostName ;
       Console.WriteLine("Enter Web Address:");
       HostName = Console.ReadLine();
       Console.WriteLine("Looking up: {0}", HostName);
       IPHostEntry NameToIpAddress;
       NameToIpAddress = Dns.GetHostEntry(HostName);
       int AddressCount = 0;
       foreach (IPAddress Address in NameToIpAddress.AddressList)
       Console.WriteLine("IP Address {0}: {1}", ++AddressCount, Address.ToString());
       Console.ReadLine();
  
        
    }
}
IP Address of Gmail.com
IP Address of Facebook.com
previous

Graphical Design Interface

Introduction of GDI(Graphics Design Interface)
GDI (Graphics Design Interface) through which we can design rectangle, circle, and more shapes with the help of programming of  classes and methods.  Like other languages C# also provides rich set of classes, methods and events for developing applications with graphical capabilities.
GDI+  -
  • GDI+ is the advance evolution of GDI.  Microsoft has taken care of most of the GDI problems and have made it easy to use with GDI+.
  • GDI+ resides in System.Drawing.dll assembly.
  • All GDI+ classes are reside in the System.Drawing, System.Text, System.Printing, System.Internal , System.Imaging, System.Drawing2D and System.Design namespaces.
Graphics Classes-
The Graphics class encapsulates GDI+ drawing surfaces. Before drawing any object (for example circle, or rectangle) we have to create a surface using Graphics class. Generally we use Paint event of a Form to get the reference of the graphics. Another way is to override OnPaint method.


protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
}
Some Graphics Class's Methods -
DrawArc ( ) Draws an arc from the specified ellipse.
DrawBezier( ) Draws a cubic bezier curve.
DrawBeziers ( ) Draws a series of cubic Bezier curves.
DrawClosedCurve( ) Draws a closed curve defined by an array of points.
DrawCurve ( ) Draws a curve defined by an array of points.
DrawEllipse( ) Draws an ellipse.
DrawImage ( ) Draws an image.
DrawLine ( ) Draws a line.
DrawPath( ) Draws the lines and curves defined by a GraphicsPath.
DrawPie ( ) Draws the outline of a pie section.
DrawPolygon( ) Draws the outline of a polygon.
DrawRectangle( ) Draws the outline of a rectangle.
DrawString ( ) Draws a string.
FillEllipse ( ) Fills the interior of an ellipse defined by a bounding rectangle.
FillPath( ) Fills the interior of a path.
FillPie ( ) Fills the interior of a pie section.
FillPolygon( ) Fills the interior of a polygon defined by an array of points.
FillRectangle ( ) Fills the interior of a rectangle with a Brush.
FillRectangles ( ) Fills the interiors of a series of rectangles with a Brush.
FillRegion( ) Fills the interior of a Region.
For making GDI+ application you have to first add Reference of System.Drawing.Dll like shown in below picture.
After this you have to add two namespaces -

using System.Drawing;
using System.Drawing.Drawing2D;
Graphics Objects-
With the help of Graphics object, you can draw lines, fill shapes, draw text and more. The major objects are given below-
Pen Used to draw lines and polygons, including rectangles, arcs, and pies.
Brush Used to fill enclosed surfaces with patterns,colors, or bitmaps.
Color Used to describe the color used to render a particular object. In GDI+ color can be alpha blended.
Font Used to describe the font to be used to render text.
Pen ClassA pen draws a line of specified width and style. You can initialize Pen with a color or brush.
Initializes a new instance of the Pen class with the specified color.

public Pen(Color);

Initializes a new instance of the Pen class with the specified Brush.

public Pen(Brush);

Initializes a new instance of the Pen class with the specified Brush and width.

public Pen(Brush, float);

Initializes a new instance of the Pen class with the specified Color and Width.

public Pen(Color, float);
Example-
Pen pn = new Pen( Color.Blue ); or Pen pn = new Pen( Color.Blue, 150 ); 
Properties of Pen -
Alignment Gets or sets the alignment for objects drawn with this Pen.
Brush Gets or sets the Brush that determines attributes of this Pen.
Color Gets or sets the color of this Pen.
Width Gets or sets the width of this Pen.
Color Class-
A Color represents an ARGB color. Properties of color is given below-
A Gets the alpha component value for this Color.
B Gets the blue component value for this Color.
G Gets the green component value for this Color.
R Gets the red component value for this Color.
Example-
         Pen pn = new Pen( Color.Blue );
Font Class- 
The Font class defines a particular format for text such as font type, size, and style attributes.

//Initializes a new instance of the Font class with the specified attributes.

public Font(string, float);

//Initializes a new instance of the Font class from the specified existing Font and FontStyle.

public Font(Font, FontStyle);
Example-  
          Font font = new Font("Times New Roman", 26);
Brush Class-
The Brush class is an abstract base class and cannot be instantiated. We always use its derived classes to instantiate a brush object, like
  • SolidBrush
  • TextureBrush
  • RectangleGradientBrush
  • LinearGradientBrush.  
Example-
LinearGradientBrush lBrush = new LinearGradientBrush(rect, Color.Red, Color.Yellow, 
LinearGradientMode.BackwardDiagonal);
Example of Drawing a Rectangle-

protected override void OnPaint(PaintEventArgs pe)
        {
            Graphics gcs = pe.Graphics;
            Rectangle rect = new Rectangle(30, 30, 230, 200);
            LinearGradientBrush lBrush = new LinearGradientBrush(rect, Color.Bisque, Color.DarkMagenta,
 LinearGradientMode.BackwardDiagonal);
            gcs.FillRectangle(lBrush, rect);
        } 

Creating DLL in C#

What is DLL?
A dynamic linking library (DLL) is linked to your program at run time. DLL is similar to an EXE but is not directly executable. Functions in the dll are called from the main exe. It provides a way to split what would be a very large exe into an exe plus one or more dlls.
Creating DLL in C#
To creating DLL in C# just follow next steps-
Goto File -> New Project then choose Class Library you will see window like below.
Here i am going to show DLL for addition, subtraction, multiplication, and division. Code for this is given below-

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

namespace ClassLibrary1
{
    public class Class1
    {
        public int add(int x,int y)
        {
           
          int  z = x + y;
          return z;
        }
        public int sub(int x, int y)
        {
           
          int   z = x - y;
          return z;
        }
        public int mul(int x, int y)
        {
            
            int z = x * y;
            return z;
        }
        public int div(int x, int y)
        {
            
            int z = x / y;
            return z;
        }
    }
}
After this Build this class by pressing F6 and dll will generate this class library now you can use this in any other application where you want to use this dll.
Using DLL in C# Application
For using DLL in application you have to make add reference of the dll that you

Design the form as shown in below picture -

 private void button1_Click(object sender, EventArgs e)
        {
           ClassLibrary1.Class1 c1 = new Class1();
          int result=  c1.add(int.Parse(textBox1.Text),int.Parse(textBox2.Text));
          textBox3.Text = result.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ClassLibrary1.Class1 c2 = new Class1();
            int result = c2.sub(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
            textBox3.Text = result.ToString();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            ClassLibrary1.Class1 c3 = new Class1();
            int result = c3.mul(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
            textBox3.Text = result.ToString();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ClassLibrary1.Class1 c4 = new Class1();
            int result = c4.div(int.Parse(textBox1.Text), int.Parse(textBox2.Text));
            textBox3.Text = result.ToString();
        }

Creating Bar Chart using C#

Creating Bar Chart in windows using C#
Introduction-
For making bar chart we will make use of ‘DrawRectangle’ in built function. because we have to first create a big rectangle defining the boundary of bar graphs. Parameters of DrawRectangle is :

1. Pen – This defines the color and style of border
2. Rectangle – Rectangle object to be created

Rectangle(int x, int y, int width,int height)

X and y are the co-ordinates of top left corner of rectangle. Width and height are width and height of rectangle.

Height = (weight of current array element *height of outer rectangle )/ maximum weight.
X coordinate is incremented by width of bars everytime a new bar is created.

Y co-ordinate is calculated by the following formula:
y = y coordinate of outer rectangle + height of outer rectangle – height of bar 
Code for DrawBarChart

private void DrawBarChart(PaintEventArgs e, int[] alWeight)
        {
            int numberOfSections = alWeight.Length;
            int lengthArea = 330;
            int heightArea = 280;
            int topX = 20;
            int topY = 20;
            int maxWeight = MaxValue(alWeight);
            int[] height = new int[numberOfSections];
            int total = SumOfArray(alWeight);
            Random rnd = new Random();
            SolidBrush brush = new SolidBrush(Color.Aquamarine);
            Pen pen = new Pen(Color.Gray);
            Rectangle rec = new Rectangle(topX, topY, lengthArea, heightArea);
            e.Graphics.DrawRectangle(pen, rec);
            pen.Color = Color.Black;
            int smallX = topX;
            int smallY = 0;
            int smallLength = (lengthArea / alWeight.Length);
            int smallHeight = 0;
            for (int i = 0; i < numberOfSections; i++)
            {
                brush.Color = Color.FromArgb(rnd.Next(200, 255),
           rnd.Next(255), rnd.Next(255), rnd.Next(255));
                smallHeight = ((alWeight[i] * heightArea) / maxWeight);
                smallY = topY + heightArea - smallHeight;
                Rectangle rectangle = new Rectangle
           (smallX, smallY, smallLength, smallHeight);
                e.Graphics.DrawRectangle(pen, rectangle);
                e.Graphics.FillRectangle(brush, rectangle);
                brush.Color = Color.FromKnownColor(KnownColor.Black);
                e.Graphics.DrawRectangle(pen, rectangle);
                smallX = smallX + smallLength;
            }
        }