PacMan Game using GDI+ 032-BS-2010, 095-BS-2010, 092-BS-2010, 101-BS-2010, 110-BS-2010

Untitled

Introduction:

Pac-Man  is an arcade game developed by Namco and licensed for distribution in the United States by Midway, in October 1980 and first released in Japan on May 22, 1980. Immensely popular from its original release to the present day, Pac-Man is considered one of the classics of the medium, virtually synonymous with video games, and an icon of 1980s popular culture Upon its release.

This article describes and explains a near replica of the classic pacman game, throughout the article different code sections are explained and the whole source code alongwith the executable is provided at the end of the article. The Code is written in Visual Studio 2012 using .Net 4.5 Framework. In order to compile and execute, the .Net Runtime 4.5 is required.

 

Basic WorkFlow Abstraction:

The Flow control undergoes a complex path during the execution of the game. but we’ll be looking at it in abstract way.

1) Present The Menu.
    1.1) Load the Desired Map or Saved Game.
    1.2) Load the Sprites and other files.
    1.3) Build the game environment.
    1.4) Play Intro music.
2) Start the Timer
    2.1) Move the Pacman according to user input.
    2.2) Move the Ghosts.
    2.3) Check for collisions between the character types.
    2.4) check for game over events.
3) Timer Call starts again and control jumps to location 2.

Obviously we have tried to keep it to the minimum detail, but don’t panic, the rest of the article presents all the nitty grifty details about the program.

Diving Right Into The Code:
When the game starts, the background of the menu is animated. It actually is the game engine running and the characters move around randomly in the default map. the area of map and the characters have a light grey overlay. The method responcible for this is InitializeIdleScreen.

public void InitializeIdleScreen()
{
    this.IntroPlaying = false;
    this.SpriteShifter.Enabled = false;
    this.IntroMusicTimer.Enabled = false;
    this.FruitPlacementTimer.Enabled = false;
    Program.OverLayEnabled = true;
    LoadMapToArray("defaultmap.map");
    InitializeCharacters();
    ReallocateAllSprites();
    OverLayAllSprites();
    this.BackGroundImage = new Bitmap(640, 504);
    BackImageGfx = Graphics.FromImage(BackGroundImage);
    BuildBackGroundImage();
    this.BackgroundImage = this.BackGroundImage;
    this.Controls.Clear();
    this.Controls.Add(LogoBox);
    this.MainPanel.Enabled = true;
    this.Controls.Add(MainPanel);
    this.SoundFxPlayer.Stream = global::PACMAN.Properties.Resources.Intro;
    this.PacManMoveDelegate = new NoParaNoReturn(BlankFun);
    Red.SetPathDelegate = new NoParaNoReturn(Red.SetRandomTargetPath);
    Red.CheckCollisionDelegate = new NoParaNoReturn(this.BlankFun);
    Blue.CheckCollisionDelegate = new NoParaNoReturn(this.BlankFun);
    Pink.CheckCollisionDelegate = new NoParaNoReturn(this.BlankFun);
    Yellow.CheckCollisionDelegate = new NoParaNoReturn(this.BlankFun);
    FirstPac.ClearBackImageDelegate = new TwoIntParaNoReturn(FirstPac.ClearBackGroundImageOneBlockOverLayed);
    this.KeyPreview = false;
    if(Program.HighPerformance==true)
    FormRefreshDelegate = new NoParaNoReturn(Refresh);
    else
    FormRefreshDelegate = new NoParaNoReturn(Invalidate);
    this.Mover.Enabled = true;
}

As seen in the code, the method first does some initial work, then loads the default map into a 2D array of characters (because the ghost characters roam around in defaultmap in idle screen). then all the characters are initialized according to the map and sprites are assigned (sprites are sequences of images that show a moving or animating object). it then overlays a grey color over all the sprites. then the background image is built (the map is drawn as an image in memory rather than being re-drawn in each Paint() call. Further in the method some more initialization is done which will become clear in the upcoming sections.

The code above called a method BuildBackGroundImage, so here we take a look at what it does actually.

 public void BuildBackGroundImage()
        {
            Image PalletImg = global::PACMAN.Properties.Resources.pallet;
            Image PowerPalletImg = global::PACMAN.Properties.Resources.powerpallet;
            SolidBrush b = new SolidBrush(Color.FromArgb(0, 51, 255));
            Pen p = new Pen(b, 5);
            for (int row = 0; row < 24; row++)
            {
                for (int col = 0; col < 32; col++)
                {
                    if (ExistsInMap(row, col))
                    {
                        bool drawn = false;
                        if (ExistsInMap(row, col + 1))
                        {
                            if (ExistsInMap(row + 1, col))
                            {
                                this.BackImageGfx.DrawArc(p, (20 * col) + 7, (20 * row) + 5, 15, 25, 180, 100);
                                drawn = true;
                            }
                            if (ExistsInMap(row - 1, col))
                            {
                                this.BackImageGfx.DrawArc(p, (20 * col) + 7, (20 * row) - 20, 25, 25, 90, 90);
                                drawn = true;
                            }
                        }
                        else if (ExistsInMap(row, col - 1))
                        {
                            if (ExistsInMap(row + 1, col))
                            {
                                this.BackImageGfx.DrawArc(p, (20 * col) - 8, (20 * row) + 5, 15, 22, 270, 100);
                                drawn = true;
                            }
                            if (ExistsInMap(row - 1, col))
                            {
                                this.BackImageGfx.DrawArc(p, (20 * col) - 18, (20 * row) - 20, 25, 25, 360, 90);
                                drawn = true;
                            }
                        }
                        if (!drawn)
                        {
                            if (ExistsInMap(row, col + 1) || ExistsInMap(row, col - 1))
                                this.BackImageGfx.DrawLine(p, 20 * col - 4, (20 * row) + 5, (20 * col) + 20, (20 * row) + 5);
                            else if (ExistsInMap(row + 1, col) || ExistsInMap(row - 1, col))
                                this.BackImageGfx.DrawLine(p, (20 * col) + 7, (20 * row) - 7, (20 * col) + 7, (20 * row) + 18);
                        }
                    }
                    else if (Map[row, col] == '|')
                    {
                        p.Brush = new SolidBrush(Color.FromArgb(255, 189, 228));
                        if (Map[row, col - 1] == '|' || Map[row, col + 1] == '|')
                            BackImageGfx.DrawLine(p, 20 * col - 4, (20 * row) + 5, (20 * col) + 20, (20 * row) + 5);
                        else if (Map[row + 1, col] == '|' || Map[row - 1, col] == '|')
                            BackImageGfx.DrawLine(p, (20 * col) + 7, (20 * row) - 7, (20 * col) + 7, (20 * row) + 18);
                        p.Brush = b;
                    }
                    else if (Map[row, col] == ' ')
                        BackImageGfx.DrawImage(PalletImg, new Point((20 * col) - 5, (20 * row) - 6));
                    else if (Map[row, col] == 'V')
                        BackImageGfx.DrawImage(PowerPalletImg, new Point((20 * col) - 5, (20 * row) - 6));
                }
            }
            if(Program.OverLayEnabled==true)
            BackImageGfx.FillRectangle(new SolidBrush(OverLayColor), new Rectangle(new Point(0, 0), BackGroundImage.Size));
        }

The method basically reads the map from the 2D array of characters and draws accordingly to a Bitmap. That Bitmap is used in game as the background image. Another way to do this could have been to put all these lines of code in the Paint() event. but that would have eaten up a major chunk of performance. (Drawing an image to screen takes lesser performace than evaluating 1900+ conditions and drawing to screen).

The constructor of the GameForm class does some basic initialization job and is not explained in this article, but these three lines from the constructor worth mentioning them.

            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.DoubleBuffer, true);

These lines of code actually enable Double Buffering. Double Buffering is necessary for games that require smooth visual experience. Moving something on the screen requires first clearing it and then reprinting it on the new location, between the process there comes a moment when the screen is blank, which is commonly reffered to as flicker, Double buffering tries to solve the issue by managing two video memory locations, The display device reads the data from one location while the program draws to other, when the drawing process is complete the display device is directed to read from the second location. and vice versa.

Another important method is the FindPath method that helps Ghosts find their path to their destination.

public static List FindPath(Point StartPoint, Point DestinationPoint)
       {
           BlockMap = new BlockOnMap[24, 32];
           BlockOnMap StartBlock = new BlockOnMap(StartPoint, null, BlockStatus.Open, 0, 0);
           BlockOnMap DestinationBlock; 
           BlockOnMap SelectedBlock = StartBlock;
           List SelectedPath = new List();
           ///////////Initialize Block Map//////////////
           for (int row = 0; row < 24; row++)
               for (int col = 0; col < 32; col++)
                   BlockMap[row, col] = new BlockOnMap(new Point(col, row), null, Program.GameWindow.Map[row, col] == '#' ? BlockStatus.Wall : Program.GameWindow.Map[row, col] == '|' ? BlockStatus.Wall : BlockStatus.Unexplored, 0, 0);
           BlockMap[StartPoint.Y, StartPoint.X] = StartBlock;
           DestinationBlock = BlockMap[DestinationPoint.Y, DestinationPoint.X];
           ////////////////////////////////////////////
           while (true)
           {
               SelectedBlock.Status=BlockStatus.Closed;
               if (DestinationBlock.Status==BlockStatus.Closed)
                   break;
               List SurroundingBlocks=GetSurrounding(SelectedBlock);
               foreach(BlockOnMap adjacentblock in SurroundingBlocks)
               {
                   if (adjacentblock.Status == BlockStatus.Open)
                   {
                       if (adjacentblock.G+1 < SelectedBlock.G)
                       {
                           SelectedBlock.Parent = adjacentblock;
                            SetFGH(SelectedBlock, DestinationBlock);
                       }
                   }
                   else
                   {
                       adjacentblock.Status = BlockStatus.Open;
                       adjacentblock.Parent = SelectedBlock;
                       SetFGH(adjacentblock, DestinationBlock);
                   }
               }
               SurroundingBlocks = (from n in SurroundingBlocks where n.Status == BlockStatus.Open orderby n.F select n).ToList()/*[0]*/;
                   if (SurroundingBlocks.Count == 0)
                       break;
                   else
                       SelectedBlock = SurroundingBlocks[0];

           }
           BlockOnMap pathblock = DestinationBlock;
           while (pathblock != null)
           {
               SelectedPath.Add(pathblock.LocationOnActualMap);
               pathblock = pathblock.Parent;
           }
           return SelectedPath;
       }

The method takes 2 points as paramters and uses the A* Search Algorithm to find the shortest (in most cases) path from StartPoint to EndPoint. Not All gohsts chase pacman, only the Red ghost actually chases pacman, rest of them just travel to random locations in map.

Conclusion:

The article described the important parts of source code, the whole of it could take days to write (and possibly exceed the max length of the post set by the admin of blog). The game is developed using GDI+, which wasn’t really meant for games. so the game eats up a major chunk of CPU time.

the source code can be downloaded from here while the game executable can be downloaded from here.

 

 

 

Simple Text Visualization 095-BS-2010

Untitled

 

Introduction:

            This article describes and explains a simple program that animates bar-like objects inside a console window. The whole program works in simple text mode (we’ll be dealing with characters, not pixels directly). The visualization is purely random and will not show any synchrony to the music being played in the background (if any). Although there will be multiple objects being animated on the screen at the same time, the program is not multithreaded and it just gives an illusion of actually animating multiple objects at the same time. Source code is written in Visual C++ 2012 so it will not compile in some other compilers without some minor modifications.

Workflow Abstraction:

           Let’s look at how the control flows throughout the program, we’ll be looking at the actions rather than code directly.

1) Start Main Procedure.
   1.1) Initialize array of Bar(s).
   1.2) Initialize Screen.
   1.3) Enter a loop Terminated by keypress only.
      1.3.1) Manipulate all the Bar objects and update the screen.
      1.3.2) Freeze the program (Sleep) for ~60 Milliseconds.
      1.3.3) Jump back to 1.3.1.

the loop at 1.3 scans for a keypress in each iteration. when found one, it terminates the loop which in turn causes the program to terminate because there are no further instructions to be executed.

Diving into the Code:

Major part of the source code is dominated by the Bar class.  The Bar Class has some properties and methods as listed below. The only user-defined data type other than Bar class is the behave enum.

Let’s start by looking at the Constructor of Bar class

bar ()
{
      bar_height_limit=5;
      max_height=4+rand()%(bar_height_limit-1);
      barpos=1;
      upperbar_limit=3;
      upperbar_pos=barpos+1;
      upperbar_max_height=max_height+upperbar_limit;
}

As obvious from the code above, the max height a bar can achieve is set to 5 blocks (A block on console is typically a 8×10 block of pixels). the second statement inside the constructor sets a random height greater or equal to 4. the current printing position is set to 1. the max height of the upper bar (represented by a “=”) from the top of the lower bar (white bar) is set to 3. the position of the upper bar is set on top of the lower bar.  and the last line is quite obvious.

An Important method of the Bar class is the Print method.

void print_bar ()
{
   oldx=wherex();
   oldy=wherey();
   set_behaviour();
       if (behaviour==up)
	   printup();
       else if(behaviour==down)
	   printdown();
   print_upperbar();
   gotoxy(oldx+2,oldy);
}

Print method manipulates only one block of bar in each call. the procedure involves either printing a new block over the top of bar or removing a block from the top. during the procedure the position of the cursor (text cursor) is manipluated to print at specific locations. Three user-defined methods are called in print method, those are explained below.

let’s look at the wherex method

int wherex()
{
	CONSOLE_SCREEN_BUFFER_INFO SBInfo;
	GetConsoleScreenBufferInfo(consolehandle, &SBInfo);
	return SBInfo.dwCursorPosition.X;
}

the method declares a variable for the struct CONSOLE_SCREEN_BUFFER_INFO, calls the library method that gathers the information about console screen buffer. the wherex method returns the X property of the current location of the text cursor in the console.

the wherey method does the same the only exception is that it returns the Y property of the  location of the text cursor in the console.

the gotoxy method plays an important role in the program.

void gotoxy(int x,int y)
{
	_COORD cord= {x,y};
	SetConsoleCursorPosition ( consolehandle, cord );
}

the method declares a variable for struct _COORD and initializes it using the values from the parameters. then it passes the variable to the SetConsoleCursorPosition method from the library.

THE MAIN METHOD:

let’s look right into the code!

int _tmain(int argc, _TCHAR* argv[])
{
   consolehandle=GetStdHandle(STD_OUTPUT_HANDLE);
   srand(time(NULL));
   const int size=30;
   SetConsoleTextAttribute (consolehandle, FOREGROUND_GREEN|FOREGROUND_BLUE|FOREGROUND_RED |FOREGROUND_INTENSITY );
   CONSOLE_CURSOR_INFO cci;
   GetConsoleCursorInfo(consolehandle,&cci);
   cci.bVisible=false;
   SetConsoleCursorInfo(consolehandle,&cci);
   bar bars[size];
   gotoxy(10,20);
   for (int i=0;i<size;i++)
      cout<<(const char)(219)<<' ';
   while(!_kbhit())
    {
	gotoxy(10,20);
	for (int i=0;i<size;i++)
        	bars[i].print_bar();
        Sleep(60);
    }
   return 0;
}

The main method starts by initializing the global variable consolehandle, the handle to the console window is used throughout the program to manipulate various properties like the text color or the position of the cursos etc. the second line initializes the random number pattern which will be used by the rand method, intially the text color is set to white (using RED|GREEN|BLUE|INTENSITY flags), and important thing to notice when the program is executed is that the text cursor is not visible, that is because the main method sets the appropriate console attributes to set it to invisible.

Although only one bar is manipulated at a time, it doesn’t look so, this happens because the bars are manipulated in a fraction of second and then the program is frozen for some time, then the bars are manipulated again and frozen again, this goes on till a keypress is recieved.

 

Conclusion:

This tiny program does present some nice animation on the screen. it can be further tweaked to work in synchrony with the actual music. Plus this little exercise just taught you how to animate more than one objects on the screen while living in single thread.

Source Code and Executable can be downloaded by following this link.

 

Back Propagation Simulator

Backprop

Background:

When the idea of neural networks came in Artificial intelligence then there was need of constructing a neuron on the basis of a human brain neuron. the idea was to create an artificial neuron that will receive some data do some processing on it and then pass it on to next neuron , of course making a ditto copy of human brain neuron was not possible so some modifications were made in the main working to make it achievable.

Introduction:

Back propagation Module is software for simulating the learning of an artificial neural network. Its prime objective is to calculate the total no of iterations required for a neural network to perform learning on a specific data.

Objective:

Its prime objective is to calculate the total no of iterations required for a neural network to perform learning on a specific data.

Secondary objective is that it outputs the ideal weights that can be used in the real world problem.

Principles of BP:

   Overview:

There are three layers in the network namely initial layer, hidden layer and output layer. As their name suggests initial layer is responsible for receiving data. It initiates the learning process then the data is passed on to the hidden layer. This layer is not visible to the outer world as it has no connection to the output nor input. Then there is output layer it function is to perform final calculations and output the final result as required. The program keeps running until error value is reduced to the value of biased value or to 0 in ideal case which is impossible to achieve.

   Biased Value:

The neural network is never perfect. It’s never outputs the 100 % accurate result so we require a biased value to determine how accurate result we want. The less the value of biased value the more time network requires to train on a data. It is just like narrowing down the requirements when we are trying to determine a best option from a choice of many options.

   Weights:

Weight represent the actual data in the real world that any robot encounter as this process is specially designed for robot to learn something. There can be any no weights that can be used on any layer but for the time being the software uses 2 weights for input layer 3 for hidden and 2 for output layer.

   Input:

Input values are just like flags in microprocessors. One input can contain value 1 or 0 just like a flag can be on or off. A set of inputs in provided to system to use in its learning.

   Output:

Output value can also be 0 or 1. Output is represented by Y.

   Net Value:

Net value is used for determining error in the layer. If there are two weights and two inputs values i.e. there are two neurons then net will be calculated by formula

weight_1 * input_1 + weight_2 * input_2;

    Neuron:

A neuron is composed of two things a weight and input value.

   Threshold value:

Also called theta is used when calculating output.

Its formula is

net >= theta_threshold ? 1 : 0;

   Learning Rate:

Also called alpha is used to specify how fast or slow network train on a set of values.

   Weight Update:

A weight is updated of a layer when there is error against an input.

Implementation:

   Classes:

There are three classes representing each of one layer. Each class almost similar to other. There are only few differences in the formulas of calculation. Initial layer has no error value.

Each layer has these fields depending on the layer no of fields may differ.

double weight;

public double input{get ; set;}

double net;

one method net calculate to calculate the net value of layer

private double netcalculate()

{

return weight_1 * input_1 + weight_2 * input_2 + weight_3 * input_3;

}

Two read only properties to get output value and error value.

public double output

{

get

{

return net >= Program.theta_threshold ? 1 : 0;

}

}

public double error

{
get

{

return ((input_1 + input_2 == 2 ? 1 : 0) - output) * output * (1 - output);}}

Main Class:

Then there is a main program class that is responsible to run the network. All the calculation is done in main class.

Some values which are same for each layer are defined in main class.

Such as

public static double theta_threshold;

public static double alpha_learningrate;

public static double BiasedValue;

Putting everything together:

      Working of code:

All the process is concerned with main class.

First 7 neurons are declared

initiallayer neuron1_1 = null;

initiallayer neuron1_2 = null; 

innerlayer neuron2_1 =null;

innerlayer neuron2_2 = null;

innerlayer neuron2_3 = null;

outerlayer neuron3_1 = null;

outerlayer neuron3_2 = null;

then a open while loop is started .this loop only stops when the error in all classes is eliminated.

if (checkError()) break;

the method checkError checks that weather for all the given inputs error is eliminated or not.

static bool checkError()

{

for (int i = 0; i < 4; i++)

{

if (Errors[i])

return false;

}

return true;

}

After that weights are assigned to all neurons .

neuron1_1 = new initiallayer(0.1, x1[i]);

neuron1_2 = new initiallayer(0.3, x2[i]);

neuron2_1 = new innerlayer(0.4, 0.5, neuron1_1.output, neuron1_2.output);

neuron2_2 = new innerlayer(0.5, 0.6, neuron1_1.output, neuron1_2.output);

neuron2_3 = new innerlayer(0.3, 0.5, neuron1_1.output, neuron1_2.output);

 

only the weights of output layer are updated because this layer weights are going to be the final output so its weights are not initialized every time rather its weight only change when the weight update occurs.

That’s why we need this condition in the loop.

if (neuron3_1 == null || neuron3_2 == null)

{

neuron3_1 = new outerlayer(0.4, 0.5, 0.4, neuron2_1.output, neuron2_2.output, neuron2_3.output);

neuron3_2 = new outerlayer(0.6, 0.7, 0.1, neuron2_1.output, neuron2_2.output, neuron2_3.output);

}

else

{

neuron3_1.input_1 = neuron2_1.output;

neuron3_1.input_2 = neuron2_2.output;

neuron3_1.input_2 = neuron2_3.output;

 neuron3_2.input_1 = neuron2_1.output;

neuron3_2.input_2 = neuron2_2.output;

neuron3_2.input_2 = neuron2_3.output;

}

After that net calculated for each layer and its error is determined and then the output is transferred to the next layer and finally weights of output layer are updated if there is still error.

 if (neuron2_1.error(neuron3_1.error, neuron3_2.error) > BiasedValue)

weightupdate(1, neuron2_1.delta(), neuron3_1, neuron3_2);

else if (neuron2_2.error(neuron3_1.error, neuron3_2.error) > BiasedValue)

weightupdate(2, neuron2_2.delta(), neuron3_1, neuron3_2);

else if (neuron2_3.error(neuron3_1.error, neuron3_2.error) > BiasedValue)

weightupdate(3, neuron2_3.delta(), neuron3_1, neuron3_2);

If there is error then weight update is called static void weightupdate(int neuron , double delta , outerlayer neuron3_1  , outerlayer neuron3_2){switch (neuron){


case 1:

{

neuron3_1.weight_1 += delta;

neuron3_2.weight_1 += delta;

break;

}

case 2:

{

neuron3_1.weight_2 += delta;

neuron3_2.weight_2 += delta;

break;

}

case 3:

{

neuron3_1.weight_3 += delta;

neuron3_2.weight_3 += delta;

break;

}

}

}

Delta is property defined in inner layer

public double delta()

{

return   calculatederror * Program.alpha_learningrate * output ;

 } 

Calulate error method is

 public double error(double Error1 , double Error2)

{

calculatederror = ((1 - output) * output * ((weight_1 * Error1) +  (weight_2*Error2) ));

return calculatederror;

}

And in case there is no error else condition executes which puts false in respective error value

 else Errors[i] = false; 

      Errors is defined in main class

 public static bool[] Errors = {true , true ,true , true };

     and this line ensure the running of loop and iterates over input values again and again until loop breaks.

i = i == 3 ? 0 : i + 1;

Final notes on implementation

In this article only important code is described which is important in understanding the working and concept of B.P

That’s all. Thanks.

 

CDS

Introduction

Logo

      CDS is an android app developed to automate the cab system. It works under main authority of CABS system monitored by local government or any private organization.

Objective

The cab drivers and the passengers go through lot of problem to find each other this app make things faster and saves the time of many people.

Overview

The app works with server. It connects to server via local GPRS or Wi-Fi and requires a username and password given to every cab driver to login and then keep a constant connection to the server to receive new jobs and messages and update location of driver every 3 seconds.

Working Of Cds

Wording of CDS

On application launch, a splash screen will be displayed for a specific amount of time and will automatically be replaced by the next screen.

2. After splash screen, if user has not yet signed into the system, app will present user a login screen if user enters correct username and password then app redirects user to Main menu of the app.

3. If user enters wrong credentials on login screen then the app presents user an error message

4. On main menu, user has different options to choose from. Main menu is main control panel of the app. User can explore all the features of the app by visiting Main menu screen and selecting option(s) of his choice. Main menu screen gives user a high level picture of important features of the app he is going to use.

5. If user taps on “Current Job” option from main menu then app takes user to current job detail screen. On this screen, user can see details of the current job assigned to him. He can look at pickup address, destination address, pickup time, passenger name, number of passengers and other useful information. He can also inform his company about status of the job on this screen by tapping on appropriate buttons.

6. If user taps on “My Jobs” option then app takes user to the “My jobs” list screen. This screen lists a number of jobs completed by the driver recently.

7. If user taps on “Messages” option then app takes user to Messages inbox screen View Messages. This is a list view of all messages received by the user. By tapping on any message from the list, user can see detail of the message by going to Message reply screen. User can reply to the message as well on this screen. If user wants to select from predefined replies to send, he can tap on Respond button on this screen. The app will take user to Message reply option screen

8. If user taps on “My location” option then app will open a map view and will show user his current location on the map.

9. If user taps on “Flight Arrival” option then app takes user to Flight Arrivals information screen. This screen gives user information about flight arrivals on nearby airports within next few hours.

10. If user taps on “Emergency” option then app sends the server an emergency signal on behalf of the driver. This feature will also work if user shakes his device (Optional).

11. If user receives a new job alert then the app presents user an alert. This alert contains options to accept or Reject the job. If user accepts the job then app redirects user to Job details screen. If user rejects the job then alert is dismissed.

12. If user receives a new message then app presents user an alert. This alert contains message and options to reply or dismiss the alert. Tapping on View button takes user to Message Reply screen.

13. On the Message Reply Screen, text based reply option will be available through tapping Send while tapping Respond will take user to Reply Message Templates Screen that carries various templates messages to be tapped and sent in response in one tap.

Modules of CDS

Splash Screen:

Splash Screen

Login Screen:

Used for login.

Username Pass

Main Menu:

Home screen of app.

MainMenu

Messages:

Sent and received messages.

Messages

Jobs:

Accepted and rejected jobs lists.

Jobs

Current job:

Current Job

Panic-Emergency:

panic all

Flight Arrivals:

It shows airports in the area.

Flight

My Location:

Pinpoints the current location of driver or the passenger waiting.

 

Flow of Code:

When the app starts a service (Thread) is started and it is responsible to handle all the background process of app. It updates driver location every 3 sec and also checks for new message and new job. The scope of new message and new job is in all the app, so no matter on which activity (screen) user is the new alert dialog (message box) will appear in the app and also in minimized state app Is still communication with server however in case of new alert message or job a toast (type of label shown on screen for a short interval) is shown and user can then maximize app to see the message or to accept or reject the job. All the messages and jobs are stored in data base. Android supports SQL lite data base to store data. it is very much similar to the SQL we use in C# all the quires are same but there is no need of connection because database is located in the cell phone itself only a pointer (called cursor in android to read from DB in android) to the database does the trick.

Code Explanation (Java):

There is touch and drag system in menu. The menu item must be dragged in the middle of screen to select it. This is achieved by on Touch event in android which is defined for almost every component. In menu item on Touch event is defined for every item.  Whenever it is touched its coordinated are noted and the when user drags it the new coordinates are noted if the item which was touched is still in action down state( touched state) then it is transferred to new coordinates of screen . This way touch and drag is implemented in main menu.

Messages and jobs activities are filled with list views. Whenever data is to be displayed a data adapter is filled with data and is passed to that list view to display it. Same is the case with flight arrivals but its data is static it never changes so its values are not refreshed time to time but it values changes from country to country.

Current job used some text views (labels) and edits texts (text box) to display current job and there are few buttons below to send the information to server about the job.

GUI (XML)

All the activities have relative layout and their items adjust according to the resolution size of the mobile device. The icons used in the app are custom built and the animations associated with onClick and onTouch events are handled manually.

The background images and the graphics used in different animation are designed manually in Photoshop. There is no case of exploiting any copy rights.

Remarks:

The server requirements are CDS_Mobile_To_Server_Communicaiton.txt

App demo is CDS. Only use for educational purpose.

Maze Solver

M Usman , Roll No: 008

Introduction 

This program generates and solves a maze using depth first search algorithm. It may prove quite sturdy in demonstration of depth first search algorithm for its comprehensive understanding in a graphical way.

Background

The program is written in C# using Visual Studio 2012 as a development tool. It implements pointers, recursion, and GDI+ graphics.

We will normally use the stack and queue data structures. As prompts, evoke that the stack is First-In-Last-Out (FILO), while the queue is First-In-First-Out (FIFO).

Maze Generation 

Untitled

 

To generate a maze with DFS, we have this simple algorithm:

  • Have all walls in your maze intact (not broken).
  • Choose a random start point, push it into the stack. Call this initial square ‘current square’.
  • Repeat while the stack is not empty:
  • Get list of all neighboring squares to the current square where those neighbors have all their walls intact (unvisited).
  • If there are neighbors (i.e., List.Count > 0):
  • Choose one of the neighbors at random. Call it ‘temp’.
  • Knock the wall between ‘temp’ and the current square.
  • Push the current square into the stack.
  • Make the current square equals ‘temp’.
  • Else if there are no neighbors, pop a square from the stack. Make current square equal to it.

After executing this algorithm, you will have a ‘prefect maze’ which indicates that your maze doesn’t have ‘dead ends’ (i.e., unreachable squares) and has a single solution.

If the generation is with DFS, the program will choose a random wall and knock it, then it moves to the new square. When it reaches an edge (or visited cell), it backs again to the nearest “UNVISITED” square.

Solving Maze

 Untitled

We will now use DFS to solve the maze it created, as in the following backpedaling algorithm:

We have an empty list for the found path. Name it ‘foundPath’.

DFS(Cell start) : Boolean

if start is equal to the maze end

Add start to ‘foundPath’

Mark start as visited

Return true

Else if start is visited already

Return false

Else:

Mark start as visited

For each neighbor of start

If the wall between start and neighbor is knocked

Recursively call DFS function with the neighbor

If the call returns true

Add start to ‘foundPath’

Return true

If you reached this point, return false

This algorithm finds the path to the maze end. When it returns true, it adds the current location to ‘foundPath’, causing all other calls in the stack to return true and add their current locations, too. At finish, we will have a complete list of squares between begin and end.

However, we won’t use those recursive versions, since they may cause a StackOverFlowException when the calls are too many for that stack. We will instead use the same algorithms but iteratively (i.e., with a loop). Instead of making every recursive call, add its ‘start’ to ‘foundPath’, and we will have a pointer to the previous one (as we will see later in the article).

For generation, DFS searches at random. When it reaches an edge, it backs to the nearest (unvisited) square and repeats the process until it finds the end.

We have a third method that traverses the maze, the right-hand rule. It considers “putting” your right hand on the wall, never leaving it. Even if this way will be longer, you’ll absolutely reach the end, or back again to the beginning if there is no end. We are sure, however, that we have a path to the end, since we are using DFS that gives perfect mazes. In the right-hand rule, we will consider only traversing the maze without finding the path.

Using the Code

The Cell Struct

We have perceived in the Background section, we need to have walls in order to generate and solve a maze. So let’s have a struct called Cell that encapsulates four boolean variables: RightWall, LeftWall, UpWall, and DownWall. At first, all the walls should be intact, so we initialize them to true. When we knock a wall, we will simply set its boolean variable to false. Cell should have a Visited boolean too, which indicates whether this cell has been visited already. Every cell should draw itself, so every cell has a Draw() method.

If we want to generate a maze of 40 by 40 squares, for example, we will need a container for them. Let’s have a two-dimensional array that carries all the cell instances, call it ‘maze’. For any cell, we have two locations: one that represents its location for the graphics, and another that represents its location in the two-dimensional array. In the previous section, we demonstrated the recursive version of the DFS solution. We stated that we won’t use the recursion. Instead of having every recursive call add its ‘start’ to foundPath, we will have a pointer in every cell to its ‘previous’ cell. A chain of these ‘previous’ pointers will form the complete path. So before we push the ‘temp’ (which indicates the next neighbor of ‘start’ to be visited) to the stack, we set its ‘previous’ pointer to ‘start’.

The Maze Class

We have a class Maze that encapsulates the 2D array maze (of Cell instances). For the array, we represent it as Height x Width, not the reverse. So when we have a position Point of x and y coordinates, we access the array as maze[position.Y, position.X]. We take its maximum width and height in the constructor and reverse the array. Yet we can use any smaller width and height the user selects. This makes more sense because the repeated reserve\release operations are bad in terms of performance. Maze has a method Draw which draws every cell (in the bounds the user selects).

In the method iterativeDepthFirstSearchSolve, we use pointers to refer to the previous cell in the foundPath. To enable pointers usage, those methods must be marked as “unsafe”. The .NET Common Language Runtime usually moves objects from one place to another while the program runs. However, if we want to refer to an object with a pointer, that object must be “fixed” in its place so the pointer can always point to it correctly. Therefore we use the syntax:

fixed(Cell* cell = &start)

next.Previous = cell;

to set the previous pointer of “next” to point to “start”.

To use pointers, we must tell the compiler about it. By going to the Properties window in Visual Studio (form Solution Explorer) > Build we can set the option “Allow unsafe code” to enable using pointers.

 

In the form, we have a picture box which we draw on. Recall that picture boxes are appreciated for graphics, because they are double-buffered which prevents flickering. The user can select the difficulty level of the maze. The more difficult the maze, the larger. The user can select between 1 and 100 difficulties. Let’s call the value the user selects ‘value’. We then calculate the maze width as:

width = pictureBoxDraw.Width / value;

where pictureBoxDraw is the picture we draw on. Similarly, we define the height as:

height = (pictureBoxDraw.Height – value) / value;

We then pass them to Maze.Generate which initializes this specific size (resets all cells in the specific bounds). Widthis the number of cells per row, and Height is the number of cells per column. The width\height should be bigger when ‘value’ is bigger, so before calculation, we set the value to:

value = 100 – value;

We use a BackgroundWorker to do the work on another thread, so the GUI doesn’t hang when the maze is being generated and solved. We use a timer to frequently call Maze.Draw while the maze is working.

The user can select the speed of working. The larger the value, the faster the work. We use Thread.SpinWait to slow the operation according to the specific speed.

 

Delete Data Using WCF

<time datetime=”2013-03-05T19:30″>March 6, 7:30am</time>
<h1 itemprop=”name”>.Article: Delete Data Using WCF</h1>
<div itemscope itemtype =”http://cssubject.skoze.com”>
<span>Author: <span itemprop=”author”>Ahsan Afzal</span> (born January 18, 1993)</span>
<span itemprop=”genre”>Web Enggineering</span>
</div

Introduction
This article demonstrates one of the interesting and very useful concepts in Entity Framework.

Step By Step :
Step 1: Create a new web application

Output1

Step 2: Adding New Entity Data Model Framework

OutputEDF

Step 3: Add new template

POCO WCF Pic

Step 4: The complete code of WebForm1.aspx looks as in the following:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”WebForm1.aspx.cs

“Inherits=”DeleteDataPOCOTemplateWCFSupport.WebForm1” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head id=”Head1″ runat=”server”>

    <title></title>

</head>

<body>

    <form id=”form1″ runat=”server”>

    <center>

        <div>

            <table>

                <tr>

                    <td colspan=”2″ align=”center”>

                        <asp:Label ID=”Label1″ runat=”server” Text=”Delete Data – POCO Template WCF Support”

                            Font-Bold=”true” Font-Size=”Large” Font-Names=”Verdana” ForeColor=”Maroon”></asp:Label>

                    </td>

                </tr>

                <tr>

                    <td>

                        <asp:Label ID=”Label2″ runat=”server” Text=”Please Enter Employee Id” ForeColor=”Brown”

                            Font-Bold=”true” Font-Size=”Medium” Font-Names=”Verdana”></asp:Label>

                    </td>

                    <td>

                        <asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td colspan=”2″ align=”center”>

                        <asp:Button ID=”Button1″ runat=”server” Text=”Delete Data” Font-Names=”Verdana”Width=”213px”

                            BackColor=”Orange” Font-Bold=”True” OnClick=”Button1_Click” />

                    </td>

                </tr>

                <tr>

                    <td colspan=”2″ align=”center”>

                        <asp:Label ID=”Label3″ runat=”server” Font-Bold=”true” Font-Size=”Medium” Font-Names=”Verdana”></asp:Label>

                    </td>

                </tr>

            </table>

        </div>

    </center>

    </form>

</body>

</html>

Step 5: The complete code of WebForm1.aspx.cs looks as in the following:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;namespace DeleteDataPOCOTemplateWCFSupport

{

    public partial class WebForm1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

        }

        protected void Button1_Click(object sender, EventArgs e)

        {

            if (string.IsNullOrEmpty(TextBox1.Text))

            {

                Label3.Text = “Please Enter Some Values”;

                Label3.ForeColor = System.Drawing.Color.Red;

            }

            else

            {

                int Id = int.Parse(TextBox1.Text);

                var query = (from r in objEntities.tblEmployee where r.EmpId == Id select r).Single();

                objEntities.DeleteObject(query);

                objEntities.SaveChanges();

                Label3.Text = “Data Deleted Successfully”;

                Label3.ForeColor = System.Drawing.Color.Green;

                TextBox1.Text = string.Empty;

            }

        }

        #region Instance MembersCompanyEntities objEntities = new CompanyEntities();

        #endregion

    }

}

Step 6: The output of the application looks as in the following:Output2

Step 7: The deleted data output of the application looks as in the following:Output3

I hope This Article is helpful to you …

 

Towers of Hanoi

Faisal ASif

035-BSCS-2010

Sec B

Introduction

This article contains a recursive solution for the Towers of Hanoi problem.

The application is written in C# and the front end is done using windows forms

Please note that I used the recursive method.

toh

 

Background

I built this project as the final project of 3rd semester in the subject of data structures.

Towers of Hanoi is a puzzle game where there are three stands, each holds number of plates.
The idea here is that you have to move plates in the first stand to the third one, while moving plates you must consider:

  1. Size order, meaning when moving a plate you can’t put it on a smaller one.
  2. Only one plate can be moved at each step

The requirements

1. A graphical representation, using Windows forms, of the puzzle.

2. The user should be able to choose if they would like to use 3,4,5,6 disks* in the puzzle. There will always be three poles** present.

3. The application should allow only valid moves – as defined by these rules.

You may only move one disk at a time

You cannot place a bigger disk on a smaller disk

4. The application must have a ‘Show Me’ feature where the application will show the user the solution, step by step, for the selected number of disks.

For more about the puzzle see: Tower of Hanoi

* The term disk is used throughout the article to describe the movable parts of the puzzle.

** The term pole is used to describe the pegs, containing the disks.

The design

I wanted a clear separation between the UI and the backend. I created the MoveCalculator class with the sole purpose of working on the solution. The GameState class would handle the game mechanics and the GameForm would drive the front end, with the help of a few controls.

I wanted the MoveCalculator to return something usefull to the GameState, so the Move class was introduced. The MoveCalculator would return a list of moves and the GameState would make them.

UI elements  

The GameForm contains all the graphical components and servers as the driver for the application.

I wanted to use the PictureBox control as the base object for the disks and poles,

but needed more, so I extended the PictureBox control.

The Pole PictureBox had to keep track of the disks on itself, by maintaining a sorted list of disks.

The Disk PictureBox got the responsibility to move itself around. I also added drop and drag functionality to make the game more enjoyable.

Solver Algorithm

The algorithm used to solve the puzzle is a very simple recursive function. In the function each move gets add to a list. This list gets used to solve the puzzle.

In the start state of the game all the disks will be on the start pole. After executing all the moves in the list, all the disks should be on the ‘end pole’.

The code

Here follows 5 snippets from the application:

The MoveCalculator class takes in the amount of disks that the user wants to play with and returns a list of moves needed to solve the puzzle.   

Snippet 1: The recursive Calculate   method:

public static class MoveCalculator
{         
	private static void Calculate(int n, int fromPole, int toPole)
        {
            if (n == -1)
            {
                return; // We are done
            }
            int intermediatePole = GetIntermediatePole(fromPole, toPole);

            Calculate(n - 1, fromPole, intermediatePole);
            moves.Add(new Move(fromPole, toPole));
            Calculate(n - 1, intermediatePole, toPole);
        }    
	... 
}  

Snippet 2: A Move contains a FromPole and a ToPole. Since we will always move the disk on the top of the FromPole, the two poles are all we need.

Move also contains information about itself like AffectCount and IsValid.

public class Move 
{
	public Pole FromPole { get; set; }
        public Pole ToPole { get; set; }

        public bool AffectCount()
        {
            //If the poles dont change the move should not be counted
            if (ToPole.Equals(FromPole))
            {
                return false;
            }
            return IsValid();
        }            

        public bool IsValid()
        {
            //Allow a move where the pole dont change
            if (ToPole.Equals(FromPole))
            {
                return true;
            }
            return ToPole.AllowDisk(FromPole.getTopDisk());
        }    
	...
}

Snippet 3: The UI makes use of two custom PictureBox controls: Pole & Disk  

Where a Disk is movable from one Pole to the next. And a Pole contains a list of Disks.

public class Disk : PictureBox
{
        public int Number { get; set; }

        public Disk(int Number) : base()
        { ... }

        public void MoveToPole(Pole DestinationPole)
        { ... } 
}  
public class Pole : PictureBox
{
        public SortedList<int, Disk> Disks { get; set; }
        public int Number { get; set; }

        public Pole(int number)
        { 
	...	
        }

        public bool IsEmpty()
        {
            return Disks.Count == 0;
        }

        public bool AllowDisk(Disk disk)
        {
            if (disk == null)
            {
                return false;
            }
            if (Disks.Count == 0)
            {
                return true;
            }
            return getTopDisk().Number > disk.Number;
        }

        public Disk getTopDisk()
        {
            if (Disks.Count > 0)
            {
                return Disks.First().Value;
            }
            return null;
        }

        public void RemoveDisk()
        {
            Disks.Remove(Disks.First().Key);
        }

        public void AddDisk(Disk disk)
        {

            if (AllowDisk(disk))
            {
                disk.MoveToPole(this);
                Disks.Add(disk.Number, disk);
            }
	}
	...
}  

Snippet 4: To keep information regarding the state of the game, the GameState class was added.

The GameState should start a game, execute moves and checks for completion.

public static class GameState
    {
        public static List<Pole> Poles = new List<Pole>();
        public static List<Bitmap> ImageList = new List<Bitmap>();
        public static int MoveCount { get; set; }
        public static int NumberOfDisks { get; set; }

        // Start the game
        static GameState()
        {
            LoadImagesFromFile();
            RestartGame(3);
        }

        public static int Move(Move move)
        {
	     if (move.AffectCount())
            {
                MoveCount++;
            }

            if (move.IsValid())
            {
                Disk disk = move.FromPole.getTopDisk();
                Poles[move.FromPole.Number].RemoveDisk();
                Poles[move.ToPole.Number].AddDisk(disk);
                return MoveCount;
            }

            else //Invalid move
            {
                return -1;
            }  
        }

        public static bool IsSolved()
        {
            return (Poles[Properties.Settings.Default.EndPole].Disks.Count == NumberOfDisks);
        } 
 }  

Snippet 5: Unit tests for the two classes containing the most logic: MoveCalculator  &  GameState 

 

[TestClass()]
public class MoveCalculatorTest {
	...
        [TestMethod()]
        public void GetMoveCountTest()
        {
            int actualMoveCount = MoveCalculator.GetMoveCount(3);
            int expectedMoveCount = 7;
            Assert.AreEqual(expectedMoveCount, actualMoveCount);

            actualMoveCount = MoveCalculator.GetMoveCount(4);
            expectedMoveCount = 15;
            Assert.AreEqual(expectedMoveCount, actualMoveCount);

            actualMoveCount = MoveCalculator.GetMoveCount(5);
            expectedMoveCount = 31;
            Assert.AreEqual(expectedMoveCount, actualMoveCount);
        }  
} 

 

[TestClass()] 
public class GameStateTest  {
	...
        [TestMethod()]
        public void IsSolvedTest()
        {
            GameState.RestartGame(numberOfDisks);

            bool expectedBefore = false; 
            bool actualBefore = GameState.IsSolved();
            solveGame();
            bool expectedAfter = true;
            bool actualAfter = GameState.IsSolved();

            //Assert 
            Assert.AreEqual(expectedBefore, actualBefore);
            Assert.AreEqual(expectedAfter, actualAfter);
        }
}  

 

Add Status in Facebook

Objective:

The purpose of this article is to automation in facebook using C# Windows Form Application..

Introduction:

 In this article we can automate the facebook and I used visual studio for my project and It will automate the facebook using C# .Net platform.  In this project we can only automatically logged in into facebook, and upload a “Hello World” Status on it.

Following are the classes, properties which I am using in my project.

  • §  Mshtml Library
  • §  HTMLDocument Class
  • §  HTMLInputElement
  • §  HTMLButtonElement
  • §  GetElementById Method
  • §  GetElementByName Method
  • §  HTMLElementCollection
  • §  GetElementsByTagName Method

Running illustration using Images:

Lets start using Visual illustration step by step as follows:

Step1: Add WebBrowser in the wfa.

 1

Step 2: Set Browser Address “http://www.facebook.com

2

Step 3:After Running Project Facebook site is Open.

3

Step 4: Then it will automatically Enter “Username” and “Password”. 

4

 Step 5: After That It will start the event of “ LOG IN “ and show  us the facebook home page .

5

Step 6: Then it will automatically Create a “Hello World .. !! ”status on Facebook  .

 6

Understanding using the Code:

Now Following is the Code of My Project

public void Auto(String user,String password,String status)

{

int i=0;

if (i == 0)

{

Login(user, password);

i = 1;

}

else if (i == 1)

{

Status(status);

i = 2;

}

}

Finally:

Now if we see the Facebook class would look like :

class Facebook

{

public WebBrowser webBrowser1;

public Facebook(WebBrowser wb)

{

webBrowser1 = wb;

}

public void Auto(String user,String password,String status)

{

int i=0;

if (i == 0)

{

Login(user, password);

i = 1;

}

else if (i == 1)

{

Status(status);

i = 2;

}

}

public void Login(String user,String password)

{

HtmlElementCollection objc = webBrowser1.Document.GetElementsByTagName(“input”);

foreach (HtmlElement h in objc)

{

if (h != null && h.Name != null)

{

if (h.Name.Equals(“session[username_or_email]“))

{

h.SetAttribute(“value”, user);

}

if (h.Name.Equals(“session[password]“))

{

h.SetAttribute(“value”, password);

}

}

}

HtmlElementCollection obj = webBrowser1.Document.GetElementsByTagName(“button”);

foreach (HtmlElement h in obj)

{

if (h != null && h.Name != null)

{

if (h.GetAttribute(“ClassName”).Equals(“submit btn primary-btn flex-table-btn js-submit”))

{

h.InvokeMember(“click”);

 

}

}

}

}

public void Status(String Status)

{

HtmlElementCollection ob = webBrowser1.Document.GetElementsByTagName(“textarea”);

try

{

foreach (HtmlElement h in ob)

{

if (h != null && h.Name != null)

{

MessageBox.Show(“Error”);

}

}

catch (Exception e)

{

MessageBox.Show(“” + e);

}

HtmlElementCollection objc = webBrowser1.Document.GetElementsByTagName(“a”);

try

{

foreach (HtmlElement h in objc)

{

if (h != null && h.Name != null)

{

if (h.GetAttribute(“ClassName”).Equals(“button btn disabled”))

{

h.InvokeMember(“click”);

}

 

}

}

}

catch (Exception e)

{

MessageBox.Show(“” + e);

}

}

}

 

How to make Generics in C#

how to make Generics in C#

Introduction

We (should) always strive for perfection. The very reason for advent of computers is to reduce humane efforts. Although, it has not gone that way but for sure we are capable to handle much more today and a lot more complex things.

Generics in C# isn’t an invention in itself. Something of this sort was expected as template was available there in its predecessor C++.

For some reason I could never understand the real usage of template in C++. It was definitely not as broad as we see today with C#. From 2.0 to 3.5 to 4.0 it has matured a lot – Let’s see what it offers:

There are certain things that will never change.

Like you have n number of objects and you want to place them in an order. In computational term you would like to sort them ascending or descending. If those objects are comparable then with a logic like (bubble, binary..etc.) it can be sorted. So each class doesn’t need to define the sort method. What they need is to implement IComparableinterface.

See the code here:

public class Person : IComparable
{
  public Double NetWorth = 10000;
  public String Name = "xyz";
  public int CompareTo(object obj)
  {
      return NetWorth.CompareTo((obj as Person).NetWorth);
  }
}

public class Individual
{
     public Double NetWorth = 10000;
     public String Name = "abc";
}

These two classes are similar – apart from the IComparable implementation. Now I write a test like following:

List<Person> persons = new List<Person>();
persons.Add(new Person() { Name = "One", NetWorth = 10000 });
persons.Add(new Person() { Name = "Two", NetWorth = 1000 });            

persons.Sort();

List<Individual> individuals = new List<Individual>();

individuals.Add(new Individual() { Name = "One", NetWorth = 10000 });
individuals.Add(new Individual() { Name = "Two", NetWorth = 1000 });
individuals.Sort(); // Invalid operation exception will be thrown here at runtime

The framework developer has written sort functionality in List<T> based on IComparable interface. And we can leverage that by implementing fairly simple IComparable interface in our classes.

Things get easy this way. First we create interfaces based on our understanding/system-requirements and then we build a framework on top of that – which handles all/most of the complexity. And then leveraging the framework we develop our projects – that deals another set of complexity – the real business/functional complexity, and here it should be limited to that.

Nope – the power of Generics has not come so far.

It comes if form of performance, better designing and type safety and blah…blah…

Assume you are walking on a river bridge footpath. It’s easy… but just imagines that without a railing… ok-ok you are smart and you don’t see a problem there – now imagine your ageing parents or your kids are walking there… Hmm – I am sure you will see a problem there now – yes the problem is there because all aren’t smart and most importantly you can’t get confident about smartness of others. So the safety is required and the railing is really necessary. Forget about walking – your kid will run on that and you will still be ok. So Type-Safety provided by .NET is really an important feature.

We deal a lot with collections/arrays in general programming. For that matter the database is also a sort of collections only. A table is collection of rows. A row is collection of cells and likes. Excel sheet is another good example.

.NET 1.0 offered collections like ArrayList and Hashtable and Stack – these deals with objects. As object is base for anything so virtually you can insert, push, add any type in these collections. In normal scenario we rarely need this – what we need is collection of a particular type. For example – a collection of Controls, Datarows, Forecasts, etc. As a developer we know what we are going to store in a collection and what type of object we are going to read. But even if we know it the framework still requires casting because framework is not aware of the object type stored in an Arraylist or Hashtable.

Continuing with the code

ArrayList a = new  ArrayList();
a.Add(new Person());
Person item = (Person)a[0]; // Casting is required

List<T> essentially provides the same feature – with one added thing. It is not bound to 

List<Person> l = new List<Person>();
l.Add(new Person());
Person itm = l[0]; // Casting not required

For performance perspective it’s a big benefit – and the code is also neater.

The other benefit is type safety. In the Arraylist you could add any object but with list you can add only object of type with which it has created. [ or of a derived type ].

public class Politician : Person
{
      public string Speciality = "Nothing";
}

l.Add(new Politician()); // This is valid but while reading it has to be of original type only
Politician sp = l[1]; // invalid operation
Person sp = l[1]; // valid one

The LINQ library created by framework team depends a lot on Generic Interfaces. The full library is set of Extension methods that are created on Interfaces – like IEnumerable<T>

var hni = l.Where(mi => mi.NetWorth > 5000);

The Where is part of LINQ library that takes a function that will accept an argument of type Person and will return true or false. The where will internally iterate in the IEnumerable<person> collection and call this method passing the current item in the argument. If that returns true – that will become part of hni. This is not the exact way how it happens but something very similar. Here we are passing a lambda expression instead of a function.

This is about consuming a Generic Type – we have so many like ListDictionaryIEnumerable, and so on..; now what about creating a Generic class for our use: – consider following not so ideal example

public interface IDTO { }

public interface IModel {
  IDTO GetData();
  void Persist(IDTO dataObject);
}

public interface IView {
  void BindData(IDTO datasource);
  void SetUpdateEvent(Action<IDTO> updateAction);
}

public abstract class Controller<V, M> where V : IView, new()
                                   where M : IModel, new() 
{
 V view;
 M model;
 public Controller() {
       view = new V();
      model = new M();
 }
 public void Load() {
       var datasource = model.GetData();
      view.BindData(datasource);
      view.SetUpdateEvent(OnUpdate);
  }

 public void OnUpdate(IDTO dataSource) {
      model.Persist(dataSource);
      var datasource = model.GetData();
      view.BindData(datasource);
 }
}
public class MVC<M, V, C> where M : IModel
                          where V : IView
                          where C : Controller<V, M>, new()
{
  C controller = null;
  public void Load()
  {
      controller = new C();
      controller.Load();
  }
}

We are simulating a pattern here – roughly. The main thing here is the Controller class which is a generic one and relies on two types V and M.

There are few constraints we have put with where clause. If we don’t put it there then we can’t write code like

model.GetData();

Because the Controller class will be unaware of the type of M. By default it will treat that as object – so no specific methods would be available there. By putting constraints we say that the M has to be IModel and it must have a default constructor [the new() constraint]. And this opens up a lot of space to code a framework. This was not so with C++ templates

Now the compatibility test

public class Politician : Person
{
 public string Speciality = "Nothing";
}

public class Commonman : Person
{
 public string Occupation = "self employed";
}

Do the following now. It will pop names of Politicians

List<Politician> ms = new List<Politician>();
foreach (Person p in ms) 
{
    MessageBox.Show(p.Name); 
}

We are iterating in the Politicians list as its base type that is Person. It’s allowed – But consider following

List<Politician> ms = new List<Politician>();
foreach (Person p in ms) 
{
  MessageBox.Show(p.Name);
  p = new Commonman(); // not allowed
}

At other places p being a Person Type can have an object of type Commanman – but here in case it is not allowed. Because it can cause potential damage to the actual underlying list that will not accept a Commanman as a Politician and system will throw an exception at runtime

To prevent this runtime behavior the framework doesn’t allow the write operation here and so it goes well – no problem. In other words the List<T> within a foreach loop is treated as IEnumerable<out T> here T is the type we define in the foreach loop for reading current-item. [ this is known as Co-Variant ]. You can get the value but you can’t put in that list.

Action<Person> highlight = p => Console.WriteLine(p.Name);

Now in the above example we are defining an Action on base type Person. If we do a casting like following

Action<Commonman> hcman = highlight;

It’s allowed because Action is Contra-Variant.

BY H M SOHAIL (56-BSCS-2010) SECTION B

Reading Data from Flat File Database and Writing into SQL Database

Download Source Code

Introduction

This is a simple programs written in C# which reads data of records from a Plain Text File (Or Flat File Database) separated by custom delimiters, In case of my example here the delimiter is a cylinder ( | ), And write these records to a SQL Database accordingly.

Background

Sometimes we need to store records while we have to use very limited memory. In that case a plain text file is used to store records and information or in other words called Flat File Database. Its less size feature is very useful when we are transferring this database over network via streams. The record is stored in text files as One Record Per Line and is separated by a specific delimiter to differentiate between columns. Let’s analyze it. .

Using the Code

Before we go to the code there is one necessary step we have to perform which is

-We need to create a Text file in which we will write a few lines like below1

 

First line is my text file name from which I want to read the data which is “a384391.txt”.

In second line we described the delimiter of this text file which is cylinder “( | )” in my case.

And in third line ColNameHeader=True means that first line of our text file contains Column names so now DataAdapter place the Column Names in the Column Names section in the Data table.

There are few important things about this file

1-File Name must be “Schema”

2-File Extension must be “.ini”

3-This File should at the same location where our text file is residing.

As far as this programs is concerned I already placed the Text File as well as its Schema.ini file in the same folder as my project folder as “projectfolder/bin/Release/a384391/” so that it’s easy for the program to pick this location up.

Alright now let’s move through the code

 

            //File Name from which we want the read the Record
            string fileName = "a384391.txt";

            //Programatically Getting the File Location
            string directory = projectDirectory + "\\a384391";   //
            string folderName = Path.GetFileName(directory);

            //here we have a full path of that file now
            string fullPath = Path.GetFullPath(folderName);

            //Select Query to Get the Data
            string query = @"SELECT *FROM [" + fileName + "]";

            //Connection String to read the Data Via OLEDB in exteneded properties it is defined as a Text file
            string c_String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullPath + ";" + "Extended Properties=text;";

            // Created a dataAdapterObject
            OleDbDataAdapter comm = new OleDbDataAdapter(query, c_String);

            // Creaated a DataTable
            DataTable dt = new DataTable();

            //Tranferring data from Text File to DataTable via DataAdapter
            comm.Fill(dt);

 

This is a simple piece of code which fetch the records from Text File separate them on the base of Delimiter and the place them in the Datatable object which is “dt” using Microsoft Jet OLEDB Adapter.

Now we have all the records of the Text File into datatable each at its respective column and row. It’s time to write these records to Microsoft SQL Server. We already have a Table there  with all the column names. In Database “TextFileData” the Table is “dbo.a384391”

3

Now we have to move write the data which is present in our datatable into the SQL Server database. So let’s have a look at that code

First we need to make a SQL connection to connect the SQL Server

 

static public void makeSqlConnection()
   {
       string sSqlConnectionString = "SERVER=DOTEXE\\SQLEXPRESS;Initial Catalog=TextFileData; " +
                                      "CONNECTION RESET=FALSE;Integrated Security=SSPI";
       SqlConn = new SqlConnection(sSqlConnectionString);

   }

 

We need a Insert Query to write into Database

 

string insertQueryText = "INSERT INTO a384391 VALUES ( @merchantID @organization, @contactname, @email,"+
"@www, @dsalec, @dleadc, @dhitc, @catsub, @catname,@startdate, @dcookie, @7dayepc, @30dayepc, @7dayreversal,"+
"@30dayreversal, @powerrank, @compliance, @csalec, @cleadc, @chitc, @ccookie, @agroup, @gsalec, @gleadc, @ghitc, "+
 "@applydate, @holidays )";

 

and data is written into the SQL Database until all the rows successfully transferred to the SQL database.

 

foreach (DataRow dr in dt.Rows)
            {
                SqlCommand cmd = new SqlCommand(insertQueryText, SqlConn);
                cmd.Parameters.Add("@merchantID", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][0];
                cmd.Parameters.Add("@organization", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][1];
                cmd.Parameters.Add("@contactname", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][2];
                cmd.Parameters.Add("@email", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][3];
                cmd.Parameters.Add("@www", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][4];
                cmd.Parameters.Add("@dsalec", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][5];
                cmd.Parameters.Add("@dleadc", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][6];
                cmd.Parameters.Add("@dhitc", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][7];
                cmd.Parameters.Add("@catsub", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][8];
                cmd.Parameters.Add("@catname", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][9];
                cmd.Parameters.Add("@startdate", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][10];
                cmd.Parameters.Add("@dcookie", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][11];
                cmd.Parameters.Add("@7dayepc", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][12];
                cmd.Parameters.Add("@30dayepc", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][13];
                cmd.Parameters.Add("@7dayreversal", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][14];
                cmd.Parameters.Add("@30dayreversal", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][15];
                cmd.Parameters.Add("@powerrank", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][16];
                cmd.Parameters.Add("@compliance", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][17];
                cmd.Parameters.Add("@csalec", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][18];
                cmd.Parameters.Add("@cleadc", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][19];
                cmd.Parameters.Add("@chitc", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][20];
                cmd.Parameters.Add("@ccookie", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][21];
                cmd.Parameters.Add("@agroup", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][22];
                cmd.Parameters.Add("@gsalec", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][23];
                cmd.Parameters.Add("@gleadc", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][24];
                cmd.Parameters.Add("@ghitc", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][25];
                cmd.Parameters.Add("@applydate", SqlDbType.VarChar, 255).Value = dt.Rows[rowIndex][26];
                cmd.Parameters.Add("@holidays", SqlDbType.VarChar, 1000).Value = dt.Rows[rowIndex][27];
                rowIndex++;
                cmd.ExecuteNonQuery(); 
}

 

 

each time the query executed  first row of each column is written into Database.

That’s it. The second section is completed we copied all the data from datatable to SQL Table.

There is another approach available to write data into database is that to make a procedure into SQL Managment Studio and then simply call that  through your code in c#.