Client Server Application using C#

Download: Project Archive

In this simple article you will learn “How to program a client _server application in Console.

Requirements:

We need Following Namespaces

reference

*Threading will be used at server side to get multiple clients on stream.

How it works:

Client:
In main method we create a TcpClient through which it will connect  to Server.

static void Main(string[] args)
{
TcpClient client = new TcpClient("server IP",5000);
NetworkStream ns = client.GetStream();
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
ParameterizedThreadStart pts = new ParameterizedThreadStart(recieve);
Thread t = new Thread(pts);
t.Start(sr);
while (true)
{
String s = Console.ReadLine();
sw.WriteLine(s);
sw.Flush();

}
}

NetwrokStream class help us in making a connection between server and client. Stream Reader is used to read the message from server, Stream writer to write to stream or to transfer the message from client to server.

while (true)

{

String s = Console.ReadLine();

sw.WriteLine(s);

sw.Flush();

}

This piece of code will help us in sending messages to server.

How client receive message:

public static void recieve(Object obj)
{
    string s = "";
    StreamReader sr = (StreamReader)obj;

    while(true)
    {
       s= sr.ReadLine();
       Console.WriteLine(s);
    }
}

StreamReader at client side is used to read messages from Server. You read a message form server and write it on console.

Server:

At server side we need a arraylist to store multiple client and to forecast the message to each client. I am using three threads: Main thread, second thread to read and third one is to connect the client.

static ArrayList list = new ArrayList();

static void Main(string[] args)
{

Thread te= new Thread(run);

te.Start();

while (true)

{

String consread = Console.ReadLine();

for (int i = 0; i < list.Count; i++)

{

Socket soket = (Socket)list[i];

StreamWriter writer = new StreamWriter(new NetworkStream(soket));

writer.WriteLine(consread);

writer.Flush();

}

This piece of code is getting each client from the list and sending the message to it.

How server read:

public static  void read(Object obj)
{

String read = "";

StreamReader strread = (StreamReader)obj;

while(true)
{

read=strread.ReadLine();

Console.WriteLine(read);

}

}

Connecting a client:

public static void run ()
{

Program socket_store = new Program();

IPAddress ipadrs = IPAddress.Parse("IP of the server");

TcpListener tcplsnr = new TcpListener(ipadrs, 5000);

tcplsnr.Start();

while (true)
{
Socket sokt = tcplsnr.AcceptSocket();

Console.WriteLine("Client connected");

list.Add(sokt);

NetworkStream stre = new NetworkStream(sokt);

StreamReader stread = new StreamReader(stre);

StreamWriter strwr = new StreamWriter(stre);

ParameterizedThreadStart pts = new ParameterizedThreadStart(read);

Thread t1 = new Thread(pts);

t1.Start(stread);

}
}

Run function run in new thread. We define it to get the client connected to server. When a client is connected, it is stored in ArrayList, create a new thread fro reading from that client.

StreamReader stread = new StreamReader(stre);

Thread t1 = new Thread(pts);

t1.Start(stread);

—————————————————————————————-

that’s it !

About:

Danish Kamal khan

Computer Science Dept.

G-C-University Lahore Pakistan.

Tic Tac Toe in C#

080-BSCS-2010

Introduction

In this article, a functioning Tic-Tac-Toe program is developed – it might not be the fullest implementation, but it works. The program concentrates on a sensible implementation that might serve as a foundation for possibly more intricate implementations. The following assumes you are familiar with the rules of Tic-Tac-Toe – if not, take a minute to look them up. Also, a basic understanding of C#, WinForms, VS.NET and data structures is assumed.

Tic-Tac-Toe is a simple game but has a number of interesting issues like:

  • How to represent each square and how should it be addressed?
  • How to process the mouse click on the box and trap errors/incorrect mouse clicks?
  • What is the best way to determine if someone has won?

The first design choice is made to represent the game squares with the Button control. With this control, there is a simple way to change the text from blank to an X or Y, establish an event handler for the Click event and easily address them as a group. By using this control, we can concentrate on other design decisions without struggling with many technical details.

Starting with the default Windows project, add nine (3×3) buttons with the same dimensions arranged 3×3. Each of the Buttons is called but1but2, etc. Another Button, labeled Play, is added to trigger a new game. Finally, the form is titled Tic Tac Toe for Windows32.

Without any code, the project should look like:

To check for winners, the buttons need to be addressed as a group. You could use the Controls array, but then extra processing would be required to account for the non-box buttons – like the Play button. Also discarded was placing them in an ArrayList construct – as this has too much overhead. Finally, we settle on the single dimensional array.

To place them in an array, a variable is created that holds the objects. The declaration is:

private System.Windows.Forms.Button [] _buttonArray;

It is really critical to understand that this statement allocates space to hold Buttons but does not create anyButtons. If you try to immediately access the _buttonArray members without creating and assigning a newButton, an exception will be thrown. For example, the code fragment:

private System.Windows.Forms.Button [] _buttonArray = new Button[9];

_buttonArray[0].Text = “It will throw an exception!”;

will throw an error since there is no object there — only undefined space. The proper way would be:

private System.Windows.Forms.Button [] _buttonArray = new Button[9];

_buttonArray[0] = new Button();    //  <-- Allocate the object!
_buttonArray[0].Text = “Save”;    // No problem now...

Back to the program…Once the buttons are created in InitializeComponent(), they can be placed in the array using automatic initialization.

_buttonArray = new Button[9] {but1, but2, but3, but4, but5, but6, but7, but8, but9};

The next task is to establish the event handler for the Click event. In this routine, we need to:

  1. Check to see if the game is over.
  2. Make sure the Button’s text is empty – otherwise it’s already been played.
  3. Place the X or O in the square.
  4. Check to see if either X or O has won.

The code below implements this function…

private void ClickHandler(object sender, System.EventArgs e)
{
    Button tempButton = (Button)sender;

    if( this._isGameOver )
    {
        MessageBox.Show("Game Over...Select Play for a new game!",
                        "ERROR",MessageBoxButtons.OK);
        return;            
    }

    if( tempButton.Text != "" )    // if not empty..already has X or O
    {
        MessageBox.Show("Button already has value!","ERROR",MessageBoxButtons.OK);
        return;
    }

    if( _isX )    // Alternate putting the X or O character in the Text property
        tempButton.Text = "X";  
    else
        tempButton.Text = "O";

    _isX = !_isX;    // alternate characters

    // check to see if there is a winner
    this._isGameOver = TicTacToeUtils.CheckAndProcessWinner(_buttonArray );
    }

The code to attach the Click event handler to the array of Buttons is:

for(int i = 0; i < 9; i++)
    this._buttonArray[i].Click += new System.EventHandler(this.ClickHandler);

The strategy to determine who won is to cycle through all the winning combinations. The winning combinations are stored in a three dimensional array. Each time a square is selected, the program checks to see if there is a winner.

 
static private int [,] Winners = new int[,]
   {
    {0,1,2},
    {3,4,5},
    {6,7,8},
    {0,3,6},
    {1,4,7},
    {2,5,8},
    {0,4,8},
    {2,4,6}
   };

All that is required now is to loop through this array to check for winners. As well, it is a really good design to have a visual (and sometimes auditory) signal when something significant happens. In this instance, the color and font is changed for the winning three buttons.

static public bool CheckAndProcessWinner( Button [] myControls )
{
    bool gameOver = false;
    for(int i = 0; i < 8; i++)
    {
        int a = Winners[i,0],b=Winners[i,1],c=Winners[i,2];
        Button b1=myControls[a], b2=myControls[b], b3=myControls[c];

        if(b1.Text == "" || b2.Text == "" || b3.Text == "" ) // if one if blank
            continue;    // try another -- no need to go further

        if(b1.Text == b2.Text && b2.Text == b3.Text )
        {
            b1.BackColor = b2.BackColor = b3.BackColor = Color.LightCoral;
            b1.Font = b2.Font = b3.Font
                 = new System.Drawing.Font("Microsoft Sans Serif", 32F, 
                                           System.Drawing.FontStyle.Italic & 
                                           System.Drawing.FontStyle.Bold, 
                                           System.Drawing.GraphicsUnit.Point, 
                                           ((System.Byte)(0)));
            gameOver = true;
            break;  // don't bother to continue
        }
    }    
    return gameOver;
}

A completed game might look like:

Pressing the Play returns the game back to the default setting and readies it for another game.

At this point, it makes sense to run review and run the code. Please let me know what you think – I’ll be working on the next Tic-Tac-Toe Etude. There are more interesting design decisions that would make a different implementation– like making a Tic-Tac-Toe Windows control, replacing the Buttons with drawing (GDI+) calls, saving the game’s state, printing, converting this to a web page and separating the logic into a Web Service.

School Accounts Management

Introduction

This article is about the account management of a School. It is desktop based application developed using C#, sql server 2008 and Crystal Reports.

Overview

The System is designed according to requirements in which Students and teachers personals information recorded for collection of student fees and to made payment of monthly teacher salaries. It also record daily office expanses.

Some  key features of AMS are

  •  Only authorized access
  • Reporting at any instances
  •  Separate defaulter students(who had not paid their fees)
  •  Class wise Enrollment of Students with auto generated Roll Number and Registration number
  •  Total profit or loss show at the end of each month

Code behind

In this piece of code Connection established with sql server and crystal report runtime environment

<?xml version=”1.0″?>

<configuration>

<configSections>

</configSections>

<connectionStrings>

<add name=”MyConnectionString” connectionString=”Data Source=WAQAR-PC\SQLEXPRESS;Initial Catalog=SchoolSystem;Integrated Security=True”

providerName=”System.Data.SqlClient” />

</connectionStrings>

<startup  useLegacyV2RuntimeActivationPolicy=”true”><supportedRuntime version=”v4.0″ sku=”.NETFramework,Version=v4.0″/></startup>

</configuration>

A store procedure is called which take arguments from the input fields on the admission from and return the registration number with class roll number

public int Save(string StoreProcedureName{

SqlCommand cmd = new SqlCommand(StoreProcedureName, connection)          cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(new SqlParameter(“@ClassName”, this.classApplied));            cmd.Parameters.Add(new SqlParameter(“@DateOfAddmission”, this.DateOfAddmission));

cmd.Parameters.Add(new SqlParameter(“@Discnt”, this.Discount));           addparameter(cmd);

SqlDataAdapter da = new SqlDataAdapter(cmd)

DataTable dt = new DataTable();

da.Fill(dt);

if (dt.Rows.Count == 1)         {

studentId = dt.Rows[0]["RegistrationNo"].ToString(); }

return -1;        }

Take values from datagridview control and save to database.

private void button1_Click(object sender, EventArgs e){

int a = dataGridView1.Rows.Count;

for (int count = 0; count < a-1; count++)

{ Expnc.itemName = dataGridView1.Rows[count].Cells["clmItem"].Value.ToString(); Expnc.Quantity = Convert.ToDouble(dataGridView1.Rows[count].Cells["clmQty"].Value); Expnc.unit_price=Convert.ToDouble(dataGridView1.Rows[count].Cells["clmUnitPrice"].Value);Expnc.Total_Amount=Convert.ToDouble(dataGridView1.Rows[count].Cells["clmAmount"].Value); Expnc.Vocherdate = dtpVocherDate.Value.ToString();

Expnc.saveExpencess();      }

MessageBox.Show(“Saved”);}}}

bind a crystal report to the report viewer form

DataTable MyDataTable = new DataTable();

ReportDocument rptdoc = new ReportDocument();

if (lp_sc.ReportName == “Admission Date Wise Student Detail Report”){

MyDataTable = lp_sc.Find(“dbo.[rptStudentReport]“);

rptdoc.Load(lp_sc.ReportPath);

rptdoc.SetDataSource(MyDataTable);

Store Proccedure for auto genrateion of Registration number and Roll number

declare @roll int
declare @cName varchar(10)
declare @year varchar(20)
declare @con varchar(50)
– SET NOCOUNT ON added to prevent extra result sets from
– interfering with SELECT statements.
SET NOCOUNT ON;
– Insert statements for procedure here
select @roll= ISNULL( MAX(StudentEnroll.RollNo)+1,1) from StudentEnroll
where StudentEnroll.ClassID =@ClassName
select @cName=Classes.ClassName from Classes where Classes.ClassId=@ClassName
select @year=YEAR(@DateOfAddmission)
select  @con=cast(@roll as varchar(20)) + ‘-’ +@cName +’-'+@year

Screen Shortsmain reg fee ecpn

reports

reports

Database Design

database

Reading Data from .csv File and Writing into SQL

Introduction

This is a simple programs written in C# which reads data of records from a .csv File, And write these records to a SQL Database accordingly. The CSV (“Comma Separated Value”) file format is often used to exchange data between disparate applications.

Tools: 

1. Visual Studio 2010
2. Microsoft SQL 2008
3. Language: C#

 Background

Sometimes we need to store records while we have to use very limited memory. In that case a .csv 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 .csv files as One Record per line and is separated by a specific delimiter (which is “,” in .csv files) to differentiate between columns.

Using the Code

Let’s move through the code

Untitled1

This is a simple piece of code which fetch the records from .csv File separate them on the base of Delimiter(which is “,” in csv files) and the place them in the Data table object which is “dt” using Microsoft Jet OLEDB Adapter.

Now we have all the records of the .csv File into data table 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.

The attribute FMT =Delimited in the connection string defines the delimiter, the program will automatically identify that it is comma delimited or tab delimited and will separate the record accordingly.

File name from where we want records “Gan_Advertisers.csv”

Untitled2

 

Now we have to write the data which is present in our data table into the SQL Server database, and data is written into the SQL Database until all the rows successfully transferred to the SQL database.

Untitled3

After that data is written in SQL.

Now we have read data from a csv file and wrote it into SQL database.

Interview Reports

The goal of this task is to generate reports regarding applicants interview data required in admission process. list of students that are called for interview, present and absent on interview day, list of those who give interview on certain date and interview marks based list.

These are explained below:

  • List of Applicants that are called for Interview:

First the admin select in reports section from the menu, then he select the category Interview from the reports section, where he selects the List of all applicants that are called for Interview report there you have to code in this sense that your system interact with database, gets the result and shows on your interface in the form of list or table.

ALL STUDENTS INTERVIEW LIST

  • Attendance of Applicants on Interview date:

First the admin select in reports section from the menu, then he select the category Interview from the reports section, where he selects the Attendance of Applicants on Interview day report there you have to code in this sense that your system interact with database, gets the result and shows on your interface in the form of list or table.

INTERVIEW ATTENDANCE

  • Marks in Interview:

First the admin select in reports section from the menu, then he select the category Interview from the reports section, where he selects the List of marks in Interview report there you have to code in this sense that your system interact with database, gets the result and shows on your interface in the form of list or table.

INTERVIEW MARKS

  • Date wise List of Applicants for Interview:

First the admin select in reports section from the menu, then he select the category Interview from the reports section, where he selects the Date wise list of students for Interview report there you have to code in this sense that your system interact with database, gets the result and shows on your interface in the form of list or table.

DATEWISE LIST OF STUDENTS FOR INTERVIEW

Below Diagram shows the Sequence, how the admin can interact with system and gets the required Reports of Applicant’s Interview Record.

sequence_interview

Here is the Database script of table that is required for these reports.

Interview and  Applicant database table

History Data Reports

The goal of this task is to generate reports regarding History(previous year students that are applied for different programs). List of applicants who applied for specific year along with contact information, gender wise lists, their academic record, admission test and interview details, their status (the final status reports not eligible for admission based on 2nd year marks, those who are eligible but not come up to merit, the students who are eligible for enrollment in department but cannot submitted their dues, and the list of those students who submitted their dues and get enrolled in department).
These are explained below:

  • All Applicants list of Previous year:

First the admin select in reports section from the menu, then he select the category History from the reports section, where he selects the All Applicants list of Previous year report there you have to code in this sense that your system interact with database, gets the result and shows on your interface in the form of list or table.

STUDENT LIST OF YEAR....

  • Previous Applicants Academic Record:

First the admin select in reports section from the menu, then he select the category History from the reports section, where he selects the Academic Record list of Previous year report there you have to code in this sense that your system interact with database, gets the result and shows on your interface in the form of list or table.

ACADEMIC RECORD OF LAST YEAR

  • Gender wise List:

First the admin select in reports section from the menu, then he select the category History from the reports section, where he selects Gender wise list of Previous year report there you have to code in this sense that your system interact with database, gets the result and shows on your interface in the form of list or table.

GENDER WISE LIST OF YEAR

  • Admission Test and Interview Marks List:

First the admin select in reports section from the menu, then he select the category History from the reports section, where he selects the Admission Test and Interview Marks List of Previous year report there you have to code in this sense that your system interact with database, gets the result and shows on your interface in the form of list or table.

ADMISSION TEST AND INTERVIEW MARKS OF LAST YEAR

Below Diagram shows the Sequence, how the admin can interact with system and gets the required Reports of Applicant’s of previous years.

sequence_History

 

Test Venue Reports

The goal of this task is to generate reports regarding Test Venue’s data required for admission process. The number of rooms in each block, their capacity, and their availability.
These are explained below;

  • Test Venue Block’s Details:

First the admin select in reports section from the menu, then he select the category Test Venue from the reports section, where he selects the Test Venue Block’s Details report there you have to code in this sense that your system interact with database, gets the result and shows on your interface in the form of list or table.

VENUE REPORT

  • Room Details:

First the admin select in reports section from the menu, then he select the category Test Venue from the reports section, where he selects the Test Venue Room Details report there you have to code in this sense that your system interact with database, gets the result and shows on your interface in the form of list or table.

ROOM DETAILS

Below Diagram shows the Sequence, how the admin can interact with system and gets the required Reports of Admission test venue.

sequence_test venue

Here is the Database script of table that is required for these reports.

Test Venue

Reports about Academic Record

The goal of this task is to generate reports regarding applicants Academic Record data required for admission process. The list of students based on matriculation marks, inter marks, intermediate, CGPA or marks on bachelor level, and there Subject combinations report.

These are explained below:

  • All Academic Record of Applicant:

First the admin select in reports section from the menu, then he select the category Applicant Academic Record from the reports section, where he selects the All Academic Record of Applicant report there you have to code in this sense that your system interact with database, gets the result and shows on your interface in the form of list or table.

ACADEMIC RECORD OF STUDENTS

  • Subject Combination:

First the admin select in reports section from the menu, then he select the category Applicant Academic Record from the reports section, where he selects the Subject Combination report there you have to code in this sense that your system interact with database, gets the result and shows on your interface in the form of list or table.

SUBJECT COMBINATION REPORT

Below Diagram shows the Sequence, how the admin can interact with system and gets the required Reports of Applicant’s Academic Record of those that are enrolled for admission test.

sequence_academic record

Here is the Database script of table that is required for these reports.

Applicant database table and Academic Record

HTML Tables

Tables are defined with the <table> tag.
A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the <td> tag). td stands for “table data,” and holds the content of a data cell. A <td> tag can contain text, links, images, lists, forms, other tables, etc.

Table Example

<table border=”1″>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

How the HTML code above looks in a browser:

row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2

 


HTML Tables and the Border Attribute

If you do not specify a border attribute, the table will be displayed without borders. Sometimes this can be useful, but most of the time, we want the borders to show.

To display a table with borders, specify the border attribute:

<table border=”1″>
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>

 


HTML Table Headers

Header information in a table are defined with the <th> tag.

All major browsers display the text in the <th> element as bold and centered.

<table border=”1″>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

How the HTML code above looks in your browser:

Header 1 Header 2
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2

Download Code Examples:

The HTML Element

The <head> element is a container for all the head elements. Elements inside <head> can include scripts, instruct the browser where to find style sheets, provide meta information, and more.
The following tags can be added to the head section: <title>, <style>, <meta>, <link>, <script> and <base>.


The HTML <title> Element

The <title> tag defines the title of the document.

The <title> element is required in all HTML/XHTML documents.

The <title> element:

  • defines a title in the browser toolbar
  • provides a title for the page when it is added to favorites
  • displays a title for the page in search-engine results

A simplified HTML document:

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head><body>
The content of the document……
</body></html>

 


The HTML <base> Element

The <base> tag specifies the base URL/target for all relative URLs in a page:

<head>
<base href=”http://www.abc.com/images/” target=”_blank”>
</head>

 


The HTML <link> Element

The <link> tag defines the relationship between a document and an external resource.

The <link> tag is most used to link to style sheets:

<head>
<link rel=”stylesheet” type=”text/css” href=”mystyle.css”>
</head>

 


The HTML <style> Element

The <style> tag is used to define style information for an HTML document.

Inside the <style> element you specify how HTML elements should render in a browser:

<head>
<style type=”text/css”>
body {background-color:yellow}
p {color:blue}
</style>
</head>

 


The HTML <meta> Element

Metadata is data (information) about data.

The <meta> tag provides metadata about the HTML document. Metadata will not be displayed on the page, but will be machine parsable.

Meta elements are typically used to specify page description, keywords, author of the document, last modified, and other metadata.

The metadata can be used by browsers (how to display content or reload page), search engines (keywords), or other web services.

<meta> tags always goes inside the <head> element.

<meta> Tags – Examples of Use

Define keywords for search engines:

<meta name=”keywords” content=”HTML, CSS, XML, XHTML, JavaScript”>

Define a description of your web page:

<meta name=”description” content=”Free Web tutorials on HTML and CSS”>

Define the author of a page:

<meta name=”author” content=”Hege Refsnes”>

Refresh document every 30 seconds:

<meta http-equiv=”refresh” content=”30″>