Saturday, December 15, 2007

A game of POKER

The latest James Bond movie "Cassino Royale" has inspired me to do a poker game.... This game was developed for the event "Craft.NET" in the Annual Tech-Fest, Quark -2007. An Artificial Intelligence algorithm was developed for a game with 5 computer players and a human player. This algorithm was implemented as a windows application using C#.NET 2005. Poker is a very popular card game, usually played with betting. The program stores all the previous actions played by all the six players in a history array. The computer player then decides its play of action according to the history of the other 5 players. Bluffing (possibility of the computer faking its cards) was also included in the program. A small percentage of chance was associated to bluffing.

Click Here to download the game. You will need to install .NET framework 2.0 for the game to work properly. The game works only in Windows XP/ Vista.





Bharath

Tuesday, November 20, 2007

A Web Messenger

Have u ever wondered how a web messenger like gtalk works????I have.....Thats why I was very glad that one of my friends took Web messenger as his computer projects, so that by helpin him I can know how it works...... The project has now been completed and it turns out that the entire proj was done by me as my friend had no time to learn everythin he needed to complete the proj.....now somthin about the project...
I've wirtten a XML web service to be run on the server side that keeps track of online users and directs the messages from sender to receiver....
I've designed a windows form in C# to be installed on the client machines....

Click Here to download the entire project

Thursday, August 30, 2007

AJAX -- Initiate a XMLHTTP request

If the codes given below are unreadble you can download the code files here.
XMLHTTPRequest.rar

As You might have known, ASP.NET 2 uses a control called Script manager to handle all asynchronous calls from the client. ASP.NET also facilitates developers by providing built in support for AJAX using updat panel control and script manager. This definitely make life easier for developers. But AJAX is abbreviation of Asynchronous Javascipt And Xml....What is the role of javascript and XML in AJAX??

Normally all webpages uses Hyper Text Transfer Protocol(HTTP) to transfer data between server and client. In this protocol, a client requests a webpage to the server using a HTTP-GET request and the server sends the page to the client...If the client wants to send some data back to server (viz. login information) a HTTP-POST is done...the server processes the posted data and again returns the page to the client....In this process, any GET or POST request causes the entire page on the client-side to refresh....Is it essential to refresh the entire page just to send(post) a small amount of data back to server?? Does the page with lots of interaction with server (think of gmail page) not take long time to load after every POST operation?? Yes, it does take long time to load using HTTP protocol.... the solution to this problem is to use XMLHTTP protocol, commonly known as AJAX.



This block diagram shows a typical HTTP protocol. As u can see there is no arrow connecting 2 "user action". So once a post is done the user cannot do anything until the server response is received. This is a synchronous model...Compare this with block diagram of XMLHTTP protocol shown a few lines below

I shall call the method by which the XMLHTTP posts a request to the server as CALLBACK.... Unlike HTTP-GET/POST request, XMLHTTP-CALLBACK does'nt cause the page on client side to get refreshed. This kind if request is called Asynchronous request. The block diagram of XMLHTTP is given below


Unlike HTTP, here the "User action" blocks are connected. So even if a CALLBACK is under process, the user can continue working with the webpage. This is an ansychronous model.

Different browsers use different ways to implement XMLHTTP protocol. Two common ways are
1) To use a native XMLHTTP object. IE7, Mozilla, Safari, and so on use native object.
2) To use ActiveX object. IE5.x and IE6 use ActiveX objects.

To create either of the 2 objects, we use javascript. Here is a .js file that contains a function to create XMLHTTP / ActiveX object....

---------------------------------XMLHTTPRequestobject.js-----------------------------


var READYSTATE_UNINITIALIZED = 0;
var READYSTATE_LOADING = 1;
var READYSTATE_LOADED = 2;
var READYSTATE_INTERACTIVE = 3;
var READYSTATE_COMPLETE = 4;
var HTTPSTATUS_OK = 200;

function createxmlhttprequestobject(){
if (ActiveXObject)//for IE 5.x & 6
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
return new ActiveXObject("Msxml2.XMLHTTP");
}
}
else //for other browsers
{
return new XMLHttpRequest();
}
}

-----------------------------------------------------------------------------------------------

The use of global variables that are declared in the file will be explained subsequently...

Here are some of the properties and methods of XMLHTTP / ActiveX objects that will be used in the code to initiate asynchronous request.

Properties

onreadystatechange - Sets or retrieves the event handler for asynchronous requests.
readyState - Retrieves the current state of the request operation.
responseBody - Retrieves the response body as an array of unsigned bytes.
responseText - Retrieves the response body as a string.
responseXML - Retrieves the response body as an XML.
status - Retrieves the HTTP status code of the request.
statusText - Retrieves the friendly HTTP status of the request.

Methods

open - Assigns method, destination URL, and other optional attributes of a pending request.
send - Sends an HTTP request to the server and receives a response.

Now global variables declared in xmlhttprequestobject.js are the different possible values of readystate property. Instead of using numbers using variable names in the code improves readability of th code..
READYSTATE_UNINITIALIZED = 0;
READYSTATE_LOADING = 1;
READYSTATE_LOADED = 2;
READYSTATE_INTERACTIVE = 3;
READYSTATE_COMPLETE = 4;

The .aspx file is given below. Read the comments for code explanation...


------------------------------------Default.aspx-----------------------------------------

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="XMLHTTPRequestObject.js">
</script>
<script type="text/javascript">
<!--
function bload(){
var xmlhttpobj = createxmlhttprequestobject();//creates XMLHTTP/ActiveX object
xmlhttpobj.open("GET", "http://" + location.host + "/AJAX trials/XMLFile.xml",false);
//used to specify the type of request, URL of server, and whether this is Asynchronous request or not
xmlhttpobj.send(null);//sends the request to server
if (xmlhttpobj.status == HTTPSTATUS_OK)//Checks whether the status of the request is OK
{
var textdoc = xmlhttpobj.responseText;//captues the response sent by the server as text
var xmldoc = xmlhttpobj.responseXML; //captues the response sent by the server as XML
var nodes = xmldoc.selectNodes("//bookstore/books/Title/text()");
//Since v requested for XML File v use XPath to traverse to the desired node
for (var i = 0; i < nodes.length; i++)//Adds all desiered nodes to listbox
{
var opt = document.createElement("option");
var val = document.createTextNode(nodes[i].nodeValue);
opt.appendChild(val);
opt.value = nodes[i].nodeValue;
document.getElementById("select1").appendChild(opt);
}

}
}

function selectchange(){
var xmlhttpobj = createxmlhttprequestobject();
xmlhttpobj.open("GET", "http://" + location.host + "/AJAX trials/XMLFile.xml",true);
//onready
xmlhttpobj.onreadystatechange = function(){
readystate_change(xmlhttpobj);
}
xmlhttpobj.send(null);
}

function readystate_change(xmlhttpobj){
if (xmlhttpobj.readyState == READYSTATE_COMPLETE)
{
var xmldoc = xmlhttpobj.responseXML;
var book = document.getElementById("select1").options[document.getElementById("select1").selectedIndex].value;
var nodes = xmldoc.selectSingleNode("//bookstore/books[Title = '" + book + "']")
var fn = nodes.selectSingleNode("Author/Firstname/text()").nodeValue;
var ln = nodes.selectSingleNode("Author/Lastname/text()").nodeValue;
document.getElementById("div1").innerHTML = "BOOK TITLE : " + book + "<br>" + "AUTHOR : " + fn + " " + ln;
}
}
//-->
</script>
</head>
<body onload = "return bload();">
<form id="form1" runat="server">
<div>
<select id="select1" onchange = "return selectchange();">
<option value="">Select a Book</option>
</select>
</div>
<div id = "div1">You are yet to make a selection</div>
</form>
</body>
</html>

---------------------------------------------------------------------------------------------

When the page loads the client makes a synchronous request to server for an XML File that contains details about some books. The title of these books are loaded into a listbox. When the user clicks on a book title, the client makes an asynchronous request to the server for the XML File and writes the author name of the book in div tag.....

Tuesday, August 28, 2007

Sending mail using ASP.NET

Hi...Have u ever thought of sending a mail with ASP.NET? Have u ever wondered how some sites uses automatic email delivary when u register for something? Here is the answer!!! emails can be sent through webpages by server side scripts!! Here I've given the pocedure to send mail with the help of ASP.NET...

The .NET framework library has a System.net.mail namespace. This namespace contains all the classes required to end a mail. For our purpose we will be using smtpclient and mailmessage class. We will also be using web.config file to configure the mail account settings.

Here is the code along with explanation.

---------------------------------------Web.Config file-------------------------------------

<!--Place the below code into the configuration tag in web.config
The usename and password used to logon and the smtp server address should be specified as attributes in network tag -->

<system.net>
   <mailSettings>
      <smtp>
         <network port="465" userName="bharath87" password="xxxxxxxxx"
          host="smtp.gmail.com"/>
       </smtp>
   </mailSettings>
</system.net>

----------------------------------Mail.aspx.vb------------------------------------

'when the aspx page loads the mail is sent to the recipent.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)_ Handles Me.Load
        Dim mm As New System.Net.Mail.MailMessage("bharath87@gamil.com", "xxxx@gmail.com")
        mm.Subject = "Test"
        mm.Body = "This is a test message"
        Dim smtp As New System.Net.Mail.SmtpClient()
        smtp.Send(mm)
End Sub

-----------------------------------------------------------------------------------

As u can see, an instance of the Mailmessage class is created with all information about the mail (sender, recipent, subject, body of te mail etc.) specified through the properties and methods of he object.
A new smtpClient object is created. This object is used to send the mailmessage created to the recipent. When the send method is called ASP.NET contacts the smtp server specified in web.config and login to the server with the usrname and password provided(Web.config). Then the message is sent to the recipent through the smtp server.....

Thursday, August 23, 2007

Javascript Games!!

Javascript is one language that gives coders a lot of freedom within a web-browser. I hope everyone agrees with me about the prev statement. It is the best choice (perhaps the second best only after flash) to develop simple games in a browser...I always wanted to try some web games using javascript...Here is my first one.

This one is a simple word game...Letters (a to z) fall from the top of the browser's client area towards the bottom at some fixed speed... The player has to type the correct letter (one of those which are currently visible on the screen)....a correct hit on the keyboard earns a point for the player....but a wrong hit costs him a point (negetive point)......The number of alphabets that are displayed at an instant is specified as a variable in the code....Here is the code..

IMPORTANT : This Code works only in Interner Explorer 6.0 or higher.
A code that works in all browsers will be updated soon.

------------------------------------wordgame.js----------------------------------
//This array contains the alphabets that are currently displayed on the screen
var curletters = new Array();
//speed of falling alphabets
var level = 5;
var intr = new Array();
var interval;
var j = 0;
//number of alphabets displayed at an instant on the screen
var nol = 5;
var score = 0;

function body_onload(){
//alert(randomletter());
}

function randomletter(){
var randno = Math.round(Math.random() * 26);
var letter = String.fromCharCode(randno + 97);
return letter;
}

function createletter(i){
var letter = randomletter();
var div = document.createElement("div");
div.id = "div" + i;
div.innerHTML = letter;
curletters[i] = letter;
div.style.position = "absolute";
div.style.top = -5;
div.style.left = randomx();
document.body.appendChild(div);
intr[i] = setInterval("moveletter(" + i + ")",(level * 10));
}

function randomx(){
var x = document.documentElement.clientWidth;
var rand = Math.random();
var xpos = Math.round(rand * x);
return xpos;
}

function moveletter(i){
var top = document.getElementById("div" + i).style.top;
top = parseInt(top.substring(0,top.indexOf("px")));
top = top + 5;
var max = document.documentElement.clientHeight;
//alert(max);
//max = parseInt(max.substring(0,max.indexOf("px")));
document.getElementById("div" + i).style.top = top;
if(top > max){
clearInterval(intr[i]);
document.body.removeChild(document.getElementById("div" + i));
createletter(i);
}

}

function Button1_onclick() {
interval = setInterval("start()",1000);

}

function start(){
//alert(j);
j = j + 1;
if(j >= nol){
clearInterval(interval);
}
createletter(j - 1);
}


function test(){
var num;
var key = event.keyCode;
for (num=0;num < nol; num++)
{
if (key == curletters[num].charCodeAt(0))
{
if (document.getElementById("div" + num).innerHTML == "")
{
continue;
}
deleteletter(num);
score += 1;
document.getElementById("Text1").value = score;
break;
}
if (num == (nol-1))
{
score -= 1;
document.getElementById("Text1").value = score;
}
}
}


function deleteletter(num){
document.getElementById("div" + num).innerHTML = "";
}

----------------------------------------------------------------------------------------------
Click here to play the game in ur browser

OR

Click Here to download the javascript (.js) code file

I hope you like my game......

Wednesday, August 15, 2007

Intro...

Hi... I am Bharath. I'm a UG engineering/science student at BITS-Pilani,Goa campus.

I donno how the thought of blogging occured to me suddenly...but I had a thought in my mind for a long time about sharing my Web development skills with outside world. I think blogging is a perfect way.....
In this blog, I'll be writing abt my experiences as an amateur ASP.NET programmer...
I have been programming with ASP.NET for the past 3 years and I've updated myself with its various updates since it was introduced....
In this blog I'll also be wiritng about my experiences with other web development tools such as javascript, ASP.NET AJAX.... and sometimes abt .NET languages such as C# and VB........