Friday, January 11

Snake Game in WPF C#

Download Complete Soulution Here: Snake Game
Screen Shots:

Splash Screen


Menu Window


Source Code: XAML


<Window x:Class="WpfApplication2.MenuWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MenuWindow" Height="474" Width="500" WindowStyle="None" AllowsTransparency="True" Background="{x:Null}" WindowStartupLocation="CenterScreen" Icon="/WpfApplication2;component/image/Snakeicon.png">
    <Grid>
        <Ellipse Height="201" HorizontalAlignment="Left"  Visibility="Hidden" Margin="125,136,0,0" Name="ellipse1" VerticalAlignment="Top" Width="313" StrokeThickness="3" Opacity="1">
            <Ellipse.Effect>
                <DropShadowEffect BlurRadius="50" Color="Green" />
            </Ellipse.Effect>
            <Ellipse.Fill>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FF0C6155" Offset="1" />
                    <GradientStop Color="#FF85E0E7" Offset="0" />
                    <GradientStop Color="#FF176382" Offset="1" />
                </LinearGradientBrush>
            </Ellipse.Fill>
            <Ellipse.Stroke>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FF176382" Offset="0" />
                    <GradientStop Color="#FF85E0E7" Offset="1" />
                </LinearGradientBrush>
            </Ellipse.Stroke>
        </Ellipse>
        <Image Height="313" Opacity="0" Source="image\snake.png" MouseDown="image1_MouseDown" HorizontalAlignment="Left" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="387" Margin="51,19,0,0" >
            <Image.Effect>
                <DropShadowEffect />
            </Image.Effect>
        </Image>
        <Label Content="New Game" Height="28" HorizontalAlignment="Left" Cursor="Hand" FontWeight="Bold" MouseDown="newGameBtn_MouseDown" FontFamily="Chiller" Margin="239,149,0,0" Name="newGameBtn" VerticalAlignment="Top" Width="83" FontSize="20" Foreground="#FF041A1A" FontStyle="Normal" FontStretch="Condensed" Opacity="1" Visibility="Hidden">
            <Label.Effect>
                <DropShadowEffect />
            </Label.Effect>
        </Label>
        <Label Content="High Scores" MouseDown="label1_MouseDown" FontFamily="Chiller" FontWeight="Bold" Cursor="Hand" Height="28" HorizontalAlignment="Left" Margin="239,183,0,0" Name="label1" VerticalAlignment="Top" Width="83" FontSize="20" Foreground="#FF041A1A" FontStyle="Normal" FontStretch="Condensed" Opacity="1" Visibility="Hidden">
            <Label.Effect>
                <DropShadowEffect />
            </Label.Effect>
        </Label>
        <Label Content="Exit" Cursor="Hand" FontFamily="Chiller" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="257,213,0,0" MouseDown="ExitBtn_MouseDown" Name="ExitBtn" VerticalAlignment="Top" Width="39" FontSize="20" Foreground="#FF041A1A" FontStyle="Normal" FontStretch="Condensed" Opacity="1" Visibility="Hidden">
            <Label.Effect>
                <DropShadowEffect />
            </Label.Effect>
        </Label>
        <Label Content="Snake Game v 1.0" Height="Auto"  FontWeight="Bold" FontFamily="Chiller" FontSize="34" HorizontalAlignment="Left" Margin="185,106,0,0" Name="label2" VerticalAlignment="Top" Width="Auto" ForceCursor="False" Visibility="Hidden" Opacity="1" Foreground="#FF03384B">
            <Label.Effect>
                <DropShadowEffect />
            </Label.Effect>
        </Label>
        <Image Height="83" Source="image\Snakeicon.png" MouseDown="image2_MouseDown" Cursor="Hand" MouseLeave="image2_MouseLeave" MouseEnter="image2_MouseEnter" HorizontalAlignment="Left" Margin="204,115,0,0" Name="image2" Stretch="Fill" VerticalAlignment="Top" Width="92" >
            <Image.Effect>
                <DropShadowEffect BlurRadius="30" />
            </Image.Effect>
        </Image>
        <Image Height="57" Opacity="0" Source="image/InfoTag.png" HorizontalAlignment="Left" Margin="95,59,0,0" Name="tagInfoimg" Stretch="Fill" VerticalAlignment="Top" Width="257" />
        <Label Content="Developers : Umair Baig" Height="28" HorizontalAlignment="Left" Margin="179,204,0,0" Name="label3" VerticalAlignment="Top" Width="157" FontWeight="Bold" FontFamily="Shruti" Foreground="White" Opacity="0.7">
            <Label.Effect>
                <DropShadowEffect BlurRadius="30" />
            </Label.Effect>
            <Label.BorderBrush>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black" Offset="0" />
                    <GradientStop Color="White" Offset="1" />
                </LinearGradientBrush>
            </Label.BorderBrush>
            <Label.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FF4B81C3" Offset="0" />
                    <GradientStop Color="#FF031F47" Offset="1" />
                </LinearGradientBrush>
            </Label.Background>
        </Label>
    </Grid>
</Window>


C# Code:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MenuWindow.xaml
    /// </summary>
    public partial class MenuWindow : Window
    {
        public MenuWindow()
        {
            InitializeComponent();   
        }

        private void newGameBtn_MouseDown(object sender, MouseButtonEventArgs e)
        {
            WpfApplication1.Window1 gameWindow = new WpfApplication1.Window1();
            gameWindow.Show();
            this.Close();
        }

        private void ExitBtn_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }
        private void image1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }
        private void image2_MouseEnter(object sender, MouseEventArgs e)
        {
            DoubleAnimation setImageOpacity = new DoubleAnimation();
            setImageOpacity.To = 1;
            setImageOpacity.From = 0;
            tagInfoimg.BeginAnimation(OpacityProperty, setImageOpacity);
        }

        private void image2_MouseLeave(object sender, MouseEventArgs e)
        {
            DoubleAnimation setImageOpacity = new DoubleAnimation();
            setImageOpacity.To = 0;
            setImageOpacity.From = 1;
            tagInfoimg.BeginAnimation(OpacityProperty, setImageOpacity);
        
        }

        private void image2_MouseDown(object sender, MouseButtonEventArgs e)
        {
            // Set opacity of Label Snake Game v1.0

            label2.Visibility = System.Windows.Visibility.Visible;
            image2.Visibility = System.Windows.Visibility.Visible;
            ellipse1.Visibility = System.Windows.Visibility.Visible;
            newGameBtn.Visibility = System.Windows.Visibility.Visible;
            ExitBtn.Visibility = System.Windows.Visibility.Visible;
            label1.Visibility = System.Windows.Visibility.Visible;

            DoubleAnimation setOpacity = new DoubleAnimation();
            setOpacity.To = 0;
            setOpacity.From = 1;
            setOpacity.RepeatBehavior = RepeatBehavior.Forever; // it will do animation forever.
            label2.BeginAnimation(OpacityProperty, setOpacity);


            // set opacity of snake image.

            DoubleAnimation setImageOpacity = new DoubleAnimation();
            setImageOpacity.To = 1;
            setImageOpacity.From = 0;
            image1.BeginAnimation(OpacityProperty, setImageOpacity);




            image2.Visibility = System.Windows.Visibility.Hidden;
            label3.Visibility = System.Windows.Visibility.Hidden;
        }

        private void label1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            // High Score File Reading 
            // File is placed at Debug Directory
            string[] readFromFile = File.ReadAllLines("Highscore.txt"); // Data Reading from existing file. File is class and ReadAllLines is its static method.
            int[] highscore = new int[readFromFile.Length];     // we must have integer array equal length of data read from file.


            //data was read in String array. as you know score is in integer format. so you need to parse it.
            for (int i = 0; i < highscore.Length; i++) {
                highscore[i] = int.Parse(readFromFile[i]); 
            }
            highscore = sortInteger(highscore); // Sorting function is called to sort array in ascending order.
             // to show only top scorers you need to start loop in the reverse order. for top three scorers you bound it for 3 iterations.
            for (int i = (highscore.Length - 1); i > (highscore.Length - 4); i--) {
                MessageBox.Show(highscore[i].ToString());
            }
        }
        private int[] sortInteger(int[] highscore) {
            //Sorting array
            Array.Sort(highscore);
            return highscore;
        }
    }
}




/////////////////////////////////////////////// Menu Window Ends////////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////// Game Play Starts//////////////////////////////////////////////////////////////////////////////////////////



Game Play


XAML Code:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Snake Bit Game" Height="422" Width="642" ResizeMode="NoResize" Icon="/WpfApplication2;component/image/Snakeicon.png">
    <Grid Height="383">
        <Rectangle Name="rectangle1" Stroke="Black" Margin="0,46,0,12" />
        <Canvas Name="paintCanvas"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MaxWidth="642" MaxHeight="422" Margin="0,46,0,12">
            
        </Canvas>
        <Label Content="Score :" Height="40" HorizontalAlignment="Left" Name="label1" VerticalAlignment="Top" FontFamily="Chiller" FontSize="24" FontWeight="SemiBold" />
        <Label  Height="40" HorizontalAlignment="Left" Name="scorelbl" VerticalAlignment="Top" FontFamily="Chiller" FontSize="24" FontWeight="SemiBold" Margin="69,0,0,0" />
        <Label Content="Level :" FontFamily="Chiller" FontSize="24" FontWeight="SemiBold" Height="40" HorizontalAlignment="Left" Margin="521,0,0,0" Name="label2" VerticalAlignment="Top" />
        <Label  FontFamily="Chiller" FontSize="24" FontWeight="SemiBold" Height="40" HorizontalAlignment="Left" Margin="589,0,0,0" Name="levellbl" VerticalAlignment="Top" />
        <Label Content="Speed :" FontFamily="Chiller" FontSize="24" FontWeight="SemiBold" Height="40" HorizontalAlignment="Left" Margin="114,0,0,0" Name="speedlbl" VerticalAlignment="Top" />
        <Label Content="Snake Game v 1.0" FontFamily="Chiller" FontSize="24" FontWeight="SemiBold" Height="40" HorizontalAlignment="Left" Margin="268,0,0,0" Name="label3" VerticalAlignment="Top" >
            <Label.Effect>
                <DropShadowEffect />
            </Label.Effect>
        </Label>
    </Grid>
</Window>



C# Code: With Comments


using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WpfApplication1
{
    using System.Windows.Threading;

    public partial class Window1 : Window
    {


        // This list describes the Bonus Red pieces of Food on the Canvas
        private List<Point> bonusPoints = new List<Point>();

        // This list describes the body of the snake on the Canvas
        private List<Point> snakePoints = new List<Point>();

        /// <summary>
        /// Size of snake and eatables things
        /// </summary>
        
        private Brush snakeColor = Brushes.Green;
        private enum SIZE
        {
            THIN = 4,
            NORMAL = 6,
            THICK = 8
        };

        /// <summary>
        /// Moving Diection of snake can be changed from here.
        /// </summary>

        private enum MOVINGDIRECTION
        {
            UPWARDS = 8,
            DOWNWARDS = 2,
            TOLEFT = 4,
            TORIGHT = 6
        };

        /// <summary>
        /// Speed of Snake can be changed from here
        /// </summary>

        private TimeSpan FAST = new TimeSpan(10000);          // Fast Speed
        private TimeSpan MODERATE = new TimeSpan(30000);     // moderate speed of snake can be handled here.
        private TimeSpan SLOW = new TimeSpan(90000);        // SLow Speed
        
        

        private Point startingPoint = new Point(100, 100);
        private Point currentPosition = new Point();

        // Movement direction initialisation
        private int direction = 0;

        /* Placeholder for the previous movement direction
         * The snake needs this to avoid its own body.  */
        private int previousDirection = 0;

        /* Here user can change the size of the snake. and eatable things
         * Possible sizes are THIN, NORMAL and THICK */
        private int headSize = (int)SIZE.THICK; 



        private int length = 50;   // length of snake is handled here.
        private int score = 0;      // Initiatl score.
        private Random rnd = new Random();  // Random number which will add red balls for snake.
        private DispatcherTimer timer;


        public Window1()
        {
            InitializeComponent();
            timer = new DispatcherTimer();
            timer.Tick += new EventHandler(timer_Tick);



            levellbl.Content = "1"; // level Label Number Setting
            speedlbl.Content = "Speed : Slow";  // speed Setting here

            /* Here user can change the speed of the snake. 
             * Possible speeds are FAST, MODERATE, SLOW and DAMNSLOW */
            timer.Interval = SLOW; // Speed is Slow
            timer.Start();


            this.KeyDown += new KeyEventHandler(OnButtonKeyDown);   // On any key down on keyboard device it will be triggered.
            paintSnake(startingPoint);                              //Starting point of snake.
            currentPosition = startingPoint;
            // Instantiate Food Objects
            int num = 0;
            for (int n = 0; n < 1; n++)
            {
                paintBonus(num);
            }
        }

        
       
        private void paintSnake(Point currentposition)
        {

            /* This method is used to paint a frame of the snake´s body
             * each time it is called. */

                Ellipse newEllipse = new Ellipse();
                newEllipse.Fill = snakeColor;
                newEllipse.Width = headSize;
                newEllipse.Height = headSize;
                Canvas.SetTop(newEllipse, currentposition.Y);
                Canvas.SetLeft(newEllipse, currentposition.X);

                int count = paintCanvas.Children.Count;
                paintCanvas.Children.Add(newEllipse);
                snakePoints.Add(currentposition);


                // Restrict the tail of the snake
                if (count > length)
                {
                    paintCanvas.Children.RemoveAt(count - length);
                    snakePoints.RemoveAt(count - length);
                }
              
        }
        private void paintBonus(int index)
        {
            Point bonusPoint = new Point(rnd.Next(5, 620), rnd.Next(5, 315));     // New points are generated which will add red balls.

                //// Eatable red balls start////

                Ellipse newEllipse = new Ellipse();
                newEllipse.Fill = Brushes.Red;
                newEllipse.Width = headSize;
                newEllipse.Height = headSize;
                
                Canvas.SetTop(newEllipse, bonusPoint.Y);
                Canvas.SetLeft(newEllipse, bonusPoint.X);
                paintCanvas.Children.Insert(index, newEllipse);
                bonusPoints.Insert(index, bonusPoint);
            //// Eatable red balls End////
            
        }


        private void timer_Tick(object sender, EventArgs e)
        {
            // Expand the body of the snake to the direction of movement

                switch (direction)
                {
                    case (int)MOVINGDIRECTION.DOWNWARDS:
                        currentPosition.Y += 1;
                        paintSnake(currentPosition);
                        break;
                    case (int)MOVINGDIRECTION.UPWARDS:
                        currentPosition.Y -= 1;
                        paintSnake(currentPosition);
                        break;
                    case (int)MOVINGDIRECTION.TOLEFT:
                        currentPosition.X -= 1;
                        paintSnake(currentPosition);
                        break;
                    case (int)MOVINGDIRECTION.TORIGHT:
                        currentPosition.X += 1;
                        paintSnake(currentPosition);
                        break;
                }

                // Restrict to boundaries of the Canvas
                if ((currentPosition.X < 5) || (currentPosition.X > 620) ||
                    (currentPosition.Y < 5) || (currentPosition.Y > 315))
                    GameOver();

                // Hitting a bonus Point causes the lengthen-Snake Effect
                int n = 0;
                foreach (Point point in bonusPoints)
                {

                    if ((Math.Abs(point.X - currentPosition.X) < headSize) && 
                        (Math.Abs(point.Y - currentPosition.Y) < headSize))
                    {
                        length += 10;
                        score += 10;

                        scorelbl.Content = score.ToString();
                        if (score == 50) {
                          //  MessageBox.Show("Level 1 Clear");
                            timer.Interval = MODERATE;
                            levellbl.Content = "2";
                            speedlbl.Content = "Speed : Moderate";  // speed Setting here
                        }
                        if (score == 100)
                        {
                            //MessageBox.Show("Level 2 Clear");
                            timer.Interval = FAST;
                            levellbl.Content = "3";
                            speedlbl.Content = "Speed : Fast";  // speed Setting here
                        }
                        // In the case of food consumption, erase the food object
                        // from the list of bonuses as well as from the canvas
                        bonusPoints.RemoveAt(n);
                        paintCanvas.Children.RemoveAt(n);
                        paintBonus(n);
                        break;
                    }
                    n++;
                }

                // Restrict hits to body of Snake


                for (int q = 0; q < (snakePoints.Count - headSize*2); q++)
                {
                    Point point = new Point(snakePoints[q].X, snakePoints[q].Y);
                    if ((Math.Abs(point.X - currentPosition.X) < (headSize)) &&
                         (Math.Abs(point.Y - currentPosition.Y) < (headSize)) )
                    {
                        GameOver();
                        break;
                    }

                }
        }
        private void OnButtonKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Down:
                    if (previousDirection != (int)MOVINGDIRECTION.UPWARDS)
                        direction = (int)MOVINGDIRECTION.DOWNWARDS;
                    break;
                case Key.Up:
                    if (previousDirection != (int)MOVINGDIRECTION.DOWNWARDS)
                        direction = (int)MOVINGDIRECTION.UPWARDS;
                    break;
                case Key.Left:
                    if (previousDirection != (int)MOVINGDIRECTION.TORIGHT)
                        direction = (int)MOVINGDIRECTION.TOLEFT;
                    break;
                case Key.Right:
                    if (previousDirection != (int)MOVINGDIRECTION.TOLEFT)
                        direction = (int)MOVINGDIRECTION.TORIGHT;
                    break;

            }
            previousDirection = direction;
        }

        private void GameOver()
        {
            StreamWriter writeData = new StreamWriter("Highscore.txt", true);
            writeData.WriteLine(score);
            writeData.Close();
            MessageBox.Show("You Lose! Your score is "+ score.ToString(), "Game Over", MessageBoxButton.OK, MessageBoxImage.Hand);
            this.Close();
        }
    }
}






Thursday, December 6

Applets in Java


Where Do Applets and Classes Come from?
When a web browser sees an applet tag and decides to download and play the applet,
it starts a long chain of events. Let's say your browser sees the following applet tag:

<APPLET codebase="http://metalab.unc.edu/javafaq/classes"
code="Animation.class" width="200" height="100" >
<PARAM NAME = “FRAMErATE”   VALUE = “10”>
</APPLET>

1.      The web browser sets aside a rectangular area on the page 200 pixels wide and
100 pixels high. In most web browsers, this area has a fixed size and cannot be
modified once created. The appletviewer in the JDK is a notable exception.
2.      The browser opens a connection to the server specified in the codebase parameter, using port 80 unless another port is specified in the codebase URL. If there's no codebase parameter, then the browser connects to the same server that served the HTML page.
3.      The browser requests the .class file from the web server as it requests any other file. If a codebase is present, it is prefixed to the requested filename. Otherwise, the document base (the directory that contains the HTML page) is used. For example:
GET /javafaq/classes/Animation.class HTTP 1.0

4.      The server responds by sending a MIME header followed by a blank line (\r\n) followed by the binary data in the .class file. A properly configured server sends .class files with MIME type application/octet-stream. For example:
HTTP 1.0 200 OK
Date: Mon, 10 Jun 1999 17:11:43 GMT
Server: Apache/1.2.8
Content-type: application/octet-stream
Content-length: 2782
Last-modified: Fri, 08 Sep 1998 21:53:55 GMT
5.      The web browser receives the data and stores it in a byte array. The byte code verifier goes over the byte codes that have been received to make sure they don't do anything forbidden, such as converting an integer into a pointer.
6.      If the byte code verifier is satisfied with the bytes that were downloaded, then the raw data is converted into a Java class using the defineClass( ) and loadClass( ) methods of the current ClassLoader object.
7.      The web browser instantiates the Animation class using its noargs constructor.
8.      The web browser invokes the init( ) method of Animation.
9.       The web browser invokes the start( ) method of Animation.

10.  If the Animation class references another class, the Java interpreter first searches for
the new class in the user's CLASSPATH. If the class is found in the user's CLASSPATH,
then it is created from the .class file on the user's hard drive. Otherwise the web
browser goes back to the site from which this class came and downloads the .class file for the new class. The same procedure is followed for the new class and any other
class that is downloaded from the Net. If the new class cannot be found, a
ClassNotFoundException is thrown



Who Can an Applet Talk to and What Can It Say?

1.      Applets cannot access arbitrary addresses in memory. Unlike the other restrictions in the list, which are enforced by the browser's SecurityManager instance, this restriction is a property of the Java language itself and the byte code verifier.
2.      Applets cannot access the local filesystem in any way. They cannot read from or write to the local filesystem nor can they find out any information about files. Therefore, they cannot find out whether a file exists or what its modification date may be.
3.      Applets cannot launch other programs on the client. In other words, they
cannot call System.exec( ) or Runtime.exec( ).
4.      Applets cannot load native libraries or define native method calls.
5.      Applets are not allowed to use System.getProperty( ) in a way that reveals
information about the user or the user's machine, such as a username or home
directory. They may use System.getProperty( ) to find out what version of
Java is in use.
6.       Applets may not define any system properties.
7.      In Java 1.1 and later, applets may not create or manipulate any Thread or
ThreadGroup that is not in the applet's own ThreadGroup. They may do this
in Java 1.0.
8.       Applets cannot define or use a new instance of ClassLoader, SecurityManager, ContentHandlerFactory, SocketImplFactory, or URLStreamHandlerFactory. They must use the ones already in place.

9.      An applet can only open network connections to the host from which the applet itself was downloaded.
10.  An applet cannot listen on ports below 1,024. (Internet Explorer 5.0 doesn't
allow applets to listen on any ports.)
11.  Even if an applet can listen on a port, it can accept incoming connections only
from the host from which the applet itself was downloaded.

Thread Scheduling And Socket


1.      Thread Scheduling
There are two kinds of thread scheduling, preemptive and cooperative.
  • A preemptive thread scheduler determines when a thread has had its fair share of CPU time, pauses that thread, and then hands off control of the CPU to a different thread.
  • A cooperative thread scheduler waits for the running thread to pause itself before handing off control of the CPU to a different thread.
  • A virtual machine that uses cooperative thread scheduling is much more susceptible to thread starvation than a virtual machine that uses preemptive thread scheduling.
2.      Synchronization, wait(), notify(), notifyAll()
Monitor objects maintain a list of all threads waiting to enter the monitor object to execute synchronized methods. A thread is inserted in the list and waits for the object if that thread calls a synchronized method of the object while another thread is already executing in a synchronized method of that object. A thread also is inserted in the list if the thread calls wait while operating inside the object. However, it is important to distinguish between waiting threads that blocked because the monitor was busy and threads that explicitly called wait inside the monitor. Upon completion of a synchronized method, outside threads that blocked because the monitor was busy can proceed to enter the object. Threads that explicitly invoked wait can proceed only when notified via a call by another thread to notify or notifyAll. When it is acceptable for a waiting thread to proceed, the scheduler selects the thread with the highest priority.


A socket is a connection between two hosts. It can perform seven basic operations:

·         Connect to a remote machine
·         Send data
·         Receive data
·         Close a connection
·         Bind to a port
·         Listen for incoming data
·         Accept connections from remote machines on the bound port

Client Sockets
·         The program creates a new socket with a Socket( ) constructor.
·         The socket attempts to connect to the remote host.
·         Once the connection is established, the local and remote hosts get input and output streams from the socket and use those streams to send data to each other.
·         This connection is full-duplex; both hosts can send and receive data simultaneously.
·         What the data means depends on the protocol; different commands are sent to an FTP server than to an HTTP server. There will normally be some agreed-upon hand-shaking followed by the transmission of data from one to the other.
·         When the transmission of data is complete, one or both sides close the connection. Some protocols, such as HTTP 1.0, require the connection to be closed after each request is serviced. Others, such as FTP, allow multiple requests to be processed in a single connection.

Threads


1.      Threads are subtasks in a program that can be in execution concurrently.
2.      The concurrency that computers perform today is normally implemented as operating system primitives” available only to highly experienced “systems programmers.”
3.      Java makes concurrency primitives available to the programmer.
4.      Subclass the Thread class and override its run( ) method.
5.      implement the Runnable interface and pass the Runnable object to the Thread constructor. Runnable has one method run().
6.      Signature of function: public void run( )
7.      run method may invoke other methods; it may construct other objects; it may even spawn other threads. The thread starts here and it stops here. When the run( ) method completes, the thread dies.
8.      the run( ) method is to a thread what the main( )method is to a traditional nonthreaded program.
9.      A single-threaded program exits when the main( ) method returns.
10.  A multithreaded program exits when both the main( ) method and the run( ) methods of all nondaemon threads return. (Daemon threads perform background tasks such as garbage collection and don't prevent the virtual machine from exiting.)
11.  Extending Thread Class
class A extends Thread
{
public static void main (String[] args)
{
Thread t = new A();
t.start( );
}
public void run()
{
//details
}
}

12.  Implementing Runnable:

class A implements Runnable
{
public static void main (String[] args)
{
A a = new A();
Thread t = new Thread(a);
t.start( );
}
public void run()
{
//details
}
}

13.  Passing Information to Thread.
14.  Returning Information from Thread.
15.  Avoid Race Condition.
16.  A thread specified as daemon will cease execution when the thread that created it ends. Syntax: threadName.setDaemon(true);
17.  A thread that is not daemon is called a user thread.
18.  Synchronized methods
public synchronized void writeEntry(String message)
19.  Every object that has synchronized methods has a monitor. The monitor lets only one thread at a time execute a synchronized method on the object.
20.  Only one synchronized instance method for an object can execute at any given time. Only one synchronized static method for a class can execute at one time.

21.  Synchronized Blocks
A code block can be declared as a synchronized on an object. Only one synchronized code block for an object can execute at any given time.
synchronized (System.out)
{
System.out.print(input + ": ");
for (int i = 0; i < digest.length; i++)
{
System.out.print(digest[i] + " ");
}
System.out.println( );
}
22.  Thread Scheduling
  • All important threads get at least some time to run and that the more important threads get more time.
  • Threads should execute in a reasonable order.(e.g. not in series)
  • Thread should not suffer through starvation.
23.  Thread Priority
  • Priority is specified as an integer ranging from 1(lowest) to 10(highest).
  • When multiple threads are able to run, generally the VM will run only the highest-priority thread,
  • public final void setPriority(int newPriority)
  • public final int getPriority( )

24.  Suspension of Thread
There are 10 ways a thread can pause in favor of other threads or indicate that it is ready to pause. These are:
  • It can block on I/O.
  • It can block on a synchronized object.
A thread can wait on an object it has locked. While waiting, it releases the lock on the object and pauses until it is notified by some other thread. Another thread changes the object in some way, notifies the thread waiting on that object, and then continues.
  • It can yield.
  • It can go to sleep.
A thread that goes to sleep does hold onto all the locks it's grabbed. Consequently, other threads that need the same locks will be blocked even if the CPU is available.

  • It can join another thread.
  • It can wait on an object.
  • It can finish.
There's a nontrivial amount of overhead for the virtual machine in setting up and tearing down threads.
  • It can be preempted by a higher-priority thread.
  • It can be suspended.
It can stop.

Sunday, November 4

Crystal Reporting (WPF Application + MYSQL Database) Complete Guide


to generate crystal report in wpf c# application is little difficult. first of all read all requirements about platform you are using. Make sure that you have added following assemblies.


Platform:
Windows 7 64bit
WPF application
MYSQL database
MYSQL ODBC connector 32bit

make sure you have installed MYSQL ODBC connector. if there is mismatch of driver and application let say mysql ODBC is 64Bit/32Bit and wpf application is off 32Bit/64bit repectively then you will face this mismatch issue. to resolve this go to C:\Windows\SysWOW64 and run odbcad32.exe file if you have installed MYSQL ODBC connector 32bit on your PC. now create datasource like this:




now open visual studio and create wpf application. add crystal report on your project. as crystal report viewer os windows form component. go to Project from menu bar. click on project properties. and set target framework to .NET framework 4. now add xml in your window tag of WPF.
xmlns:winform="clr-namespace:CrystalDecisions.Windows.Forms;assembly=CrystalDecisions.Windows.Forms"

in your grid tag

        <WindowsFormsHost Margin="0,12,0,0" Name="windowsFormsHost1">
            <winform:CrystalReportViewer x:Name="rptviewer" />
        </WindowsFormsHost>
and now create crystal report on your project.

















create an instance of your crystal report like this:
          
   CrystalReport1 e = new CrystalReport1();
            rptviewer.ReportSource = e;