Showing posts with label starters. Show all posts
Showing posts with label starters. Show all posts

Thursday, December 20, 2012

Software architecture

Let me understand the real difference between "tire" and "layer" terms commonly used in architecture.

tire - referes to physical entity that is PC(s) and Server(s)
e.g - client machine running webbrowser, app serve running the web app, database server hosting the database. 

layer - refers to logical entity that is a component
e.g. userinterface layer, business logic layer, data access layer, database layer etc.

The conventiona asp or servlets, jsp or any web app that returns the html content and on the other side queries the database with SQL queries may not be a pure layered architecture because of the overlap of the layer reponsibilities.

A clean layered architecture could be

client - html, javascript, css client talking with a webservice using HTTP GET or POST, all presentation logic is part of javascript and css

dataaccess - webservice interfaceing with database using stored procedure (not SQL queries) to access data and return the data to the client in JSON or XML formats.

database - servers the webservice for the requested data using the stored procedures

The client machines can be many, the webservice if stateless can be
hosted in many servers for scalability reasons, the database server could be hosted in redudant high end server machines for availability reasons.

There are three logical "layers" and 3-tires but actually involving "n" number of physical machines.

client-HTTP(GET/POST)->webservice-TCP database connection ( to execute Stored Proc) ->DB
client<-http database="database" font="font" recordset-db="recordset-db" webservice="webservice">
 
No HTML is exchanged between client and webservice. 
No SQL command is issued by webservice to DB.

The above is a clean layered and tired architecture if the client, webservice and DB are deployed in different machines.

Reference: http://msdn.microsoft.com/en-us/library/aa905336.aspx

to be continued..

Wednesday, December 19, 2012

Auto Update

I am trying to understand how this software auto update might be working.
There could be three steps in it
1) Check for the availability of new version
2) Download the latest version
3) Install the downloaded version of software

Next i am going to expand on how each step could be designed or implemented

Check for availability of new version

When the current version of the application is started it could do the following in a background thread 1) Read the current version all the component that could be updated in the software
2) Go the vendor software update web server and check for the availability of newer version
2.1) Only if the exiting software license supports free updates
3) If newers version ar available the goto step2 or do nothing

Download the latest version

Options
1) Update the software user about the availability of newer version by displaying a message box and request the user for a manual update
2) Update the software user about the availability of newer version by dispaying a message box and request the user to intiate the auto download
2.1) Perform the download in the background (HTTP or FTP)

If download is successfully completed then goto to step 3 or display the error message to the user and the user to try again later.

Install the downloaded version of software

Note: Technology should support installation of newer version when current version of the software is running.
Install the downloaded software and request the user to restart the software.

Not sure how much of the above understanding and ideas are correct?

References
http://stackoverflow.com/questions/4499656/how-do-i-architect-automatic-update-of-my-clients


 

Saturday, February 25, 2012

Scalability & Perfoamce

Load balance your website.
1) Use DNS (Domain Name Server) to distribute your website load.
2) Use Load Balancing Switch to distribute your website load.
The above mentioned load balancing methods work very well for static websites. But if your website have to do back end processing with a database or any other service, then even those services have to be load balanced otherwise they would become the bottle neck.

The above stuff is just the beginning of the vast topic called "Scalability"!
Abstraction interface
1) System abstraction interface help in hiding the complexity of the actual system and also the changes with in the system transparent to users of the system like hardware upgrade or adding hardware resource to scale up....
Scalability on the client

1) Paging concept (showing only few mail subjects on a mail client)

Scalability on the web/app server

1) multiple threads to handle http request
2) Load balancing architecture (one load balancing proxy server with multiple app server) to handle http request


External resources

Let's make the web faster
Web browser capabilities
Online web page testing
High Performance Web Sites and YSlow
Even Faster Websites
steve souders

to be continued.....

Tuesday, May 17, 2011

html input button issue

Try the below script and click on fun2 button. Button inside label tag have some problem, that is the second button invokes the onclick of the first button and then the second button.




Now remove the label (begin and end) tag and try the same code. Everything would work fine.


 

Thursday, February 3, 2011

parseint defect

When using parseInt() in javascript to convert or check "08" (e.g. parseInt("08")), then it would return 0. Instead use parseInt("08",10), i.e base 10 for converting or checking.

Sunday, January 30, 2011

HTML GET and POST

Let us quickly try to understand GET and POST request in HTML.
GET is used to request data from server and POST is used to submit data to server.

Let us create a simple HTML page called request.html as show below
<html>
    <head>
        <title>
            Request
        </title>
    </head>
    <body>
        <form method="GET" action="response.php">
            Enter the GET METHOD text:
            <input type="text" name="getinput" value="get value"/>
            <br/>
            Enter the POST METHOD text:
            <input type="text" name="postinput" value="post value"/>
            <br/>
            <input type="submit" value="Submit"/>
        </form>
    </body>
</html>
Save request.html file under apache\htdocs folder in c:\ if you have one.

Now create another file called response.php as show below
<?php
echo "GET:".$_GET["getinput"]; //GET
echo "<br/>";
echo "POST:".$_POST["postinput"]; //POST
?>
Save response.php file under apache\htdocs folder in c:\ if you have one.

If you notice the request.html source code the form tag's method attribute is set to GET.
Now open the request.html file using any of your web browser (e.g. http://localhost/request.html).
After the file opens in your web browser, hit the submit button.
Now you can notice the address bar URL had changed to
http://localhost/response.php?getinput=get+value&postinput=post+value
The above URL is also called Query String.
And the response would be
GET:get value
POST:
The above result is because we used GET method to QUERY/POST data to the server.

Now change the method attribute (form tag) value to POST in the request.html file and save the file.

Now again open the request.html file using any of your web browser (e.g. http://localhost/request.html).
After the file opens in your web browser, hit the submit button.
Now you can notice the address bar URL had changed to
http://localhost/response.php
And the response would be
GET:
POST:post value
The above result is because we used POST method to POST data to the server.

Take some time and try to understand the request.html and response.php file source code.
Please read more on Hypertext Transfer Protocol and Query string.

Thursday, January 20, 2011

JSON with special character text in PHP with MySQL

If you want to use JSON with special characters text to write to MySQL database or read from MySQL database using javascript and PHP, follow the below steps

To save/write JSON with special character text,
In Javascript
1) Do encodeURIComponent to the value to be submitted in javascript before POST

In PHP
1) Do stripslashes of the received POST data
2) Do mysql_real_escape_string before insert or update SQL statement

To pass back special character text via JSON from database,
In PHP
1) Do json_encode before creating JSON string (Note: Do not include " before and after the encoded json value.)

Monday, January 17, 2011

Online IDE

I was searching for an online cloud based IDE to store and edit my hobby projects on the net. Then i found CODERUN.

Few more IDEs,

1) https://bespin.mozillalabs.com/
2) http://kodingen.com/

Online bookmarks

I have been using two laptops for some time. I used to save URL bookmarks in both the laptops. Recently i started using my Nokia 5800 and an iPad for web browsing. I started storing bookmarks in my iPad as well. I found it very difficult to remember the bookmarks and respective devices.
To solve this problem i found a decent enouhg solutions at google bookmarks.
Now i am managing all my bookmarks at google bookmarks. Now i can access my bookmarks from any where and any device!

Friday, January 14, 2011

USB computer

Let me quickly tell you how to make a USB computer!

1) get one 8/16 GB USB drive.
2) download ubuntu from ubuntu desktop to your PC/laptop.
3) burn the ubuntu iso onto the USB drive as per the instruction given on ubuntu desktop using the universal USB Installer, but select the persistance option ( step 4 in the univsal USB installer ) of your desired memory size.
4) great! Now you have a ubuntu USB computer.
5) now shut down your PC/laptop with out removing the ubuntu USB driver.
6) start your PC/laptop press F12 and a change the boot sequence to boot OS from mounted ubuntu USB drive.
7) do your work with the ubuntu USB drive.
8) once your are done with your work, shut down your PC/laptop and remove the ubuntu USB driver.
9) now carry your ubuntu USB computer where ever you want and mount it on any PC/laptop and do your work!

Wednesday, August 25, 2010

Reading GPS data from Nokia phones

To read GPS data from your Nokia phone follow the below steps,

Make sure your Nokia phone supports inbuilt GPS receiver.

Install Aptana with Nokia WRT Plug-in for Aptana Studio.

Create a new project in Aptana with WRTKit.

1) Paste the below code in the index.html file.
2) Package the widget.
3) Download the package (yourprojectname.wgz) to your Nokia phone and install.
4) Run the application and wait the application to establish connection with the satellites.
5) Have fun!

Javascript example
<!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>
<title>GPS Tracker</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />        
<script type="text/javascript" src="WRTKit/WRTKit.js"></script>        
<META NAME="Generator" CONTENT="Nokia WRT plug-in for Aptana Studio 2.3.0" />
<style>
body{background-color:#ffffff;font-size:15px;}
#btnGetLocation{width:100%;margin:5px;height:50px;width:100px;}
#latLabel{text-align:left;margin:5px;width:150px;}
#longLabel{text-align:left;margin:5px;width:150px;}
#statusLabel{text-align:left;margin:5px;width:150px;}
#gpsStatusLabel{padding:5px;text-align:left;margin:5px;height:20px;width:150px;}
.gpsStatusLabelA{background-color:lightgreen;}
.gpsStatusLabelIA{background-color:red;}
#gpsStrengthLabel{text-align:left;margin:5px;width:150px;}
</style>
<script>
var interval=1000;   
var TXT_ACTIVE = "Active";
var TXT_INACTIVE = "Inactive";  
var TXT_RUNNING="Running";
var TXT_GPSSTATUSLABEL="gpsStatusLabel";
var GPS_INACTIVE = 0;
var GPS_ACTIVE = 1;

var locDataTimer = null;
var serviceObj = null;
var distanceCriteria = null;
var trackCriteria = null;

function updateElement(name,value)
{
 document.getElementById(name).innerHTML=value;
 if(name == TXT_GPSSTATUSLABEL)
 {     
  if(value == TXT_ACTIVE)
  {  
   document.getElementById(name).setAttribute("class", "gpsStatusLabelA");  
  }
  else
  {  
   document.getElementById(name).setAttribute("class", "gpsStatusLabelIA");
  }
 }
}
function reset()
{
 updateElement("gpsStatusLabel",TXT_INACTIVE);
 updateElement("gpsStrengthLabel","");
 updateElement("statusLabel","");
 updateElement("latLabel","");
 updateElement("longLabel","");    
}
function initUI()
{
 reset();
}
function initSO()
{
 try
 {
  serviceObj = device.getServiceObject("Service.Location", "ILocation");
 }
 catch (ex) 
 {
  updateElement("statusLabel",ex);
  return;
 } 
 // The user cancelled the service object initialization
 if (serviceObj.ILocation == null) 
 {
  return; 
 }        
 // Specify that location information need not be guaranteed. This helps in
 // that the widget doesn't need to wait for that information possibly
 // indefinitely.
 var updateOptions = new Object();
 updateOptions.PartialUpdates = true;
 
 // Initialize the criteria for the GetLocation call
 trackCriteria = new Object();
 trackCriteria.LocationInformationClass = "GenericLocationInfo";
 trackCriteria.Updateoptions = updateOptions;
 // Set the timer to tick (update the location data) at one second intervals
 locDataTimer = setInterval("tick()", interval);
}
function init()
{
 initUI();    
 initSO();
}

// Called when the locDataTimer's interval elapses
function tick() 
{
 updateElement("statusLabel",TXT_RUNNING);
 try 
 {
  var result = serviceObj.ILocation.GetLocation(trackCriteria);
  displayData(result);    
 }
 catch (ex) 
 {
  updateElement("statusLabel",ex);  
 }
}
// Displays the location data
function displayData(result) 
{
 if (result.ReturnValue == undefined) 
 {
  return;
 }

 var latitude = result.ReturnValue.Latitude;
 if (!isNaN(latitude)) 
 {
  updateElement("latLabel", latitude.toFixed(4) + " \u00B0");
 }       
 var longitude = result.ReturnValue.Longitude;
 if (!isNaN(longitude)) 
 {
  updateElement("longLabel", longitude.toFixed(4) + " \u00B0");
 }   
 if (!isNaN(latitude) || !isNaN(longitude)) 
 {
  // Either latitude or longitude information is received, so we can be
  // sure that the GPS is active
  changeGPSStatus(GPS_ACTIVE);
 }
 else 
 {
  changeGPSStatus(GPS_INACTIVE);
 }
 
 var numOfSatellites = result.ReturnValue.SatelliteNumView;
 if (numOfSatellites == undefined) 
 {
  numOfSatellites = 0;
 }
 updateElement("gpsStrengthLabel",numOfSatellites);
}   
//Changes the GPS status on the status pane
function changeGPSStatus(newStatus) 
{       
 if (newStatus == GPS_ACTIVE) 
 {
  updateElement("gpsStatusLabel",TXT_ACTIVE);
 } 
 else 
 {
  updateElement("gpsStatusLabel",TXT_INACTIVE);
 }
}
</script>
</head>
<body onload="init()">
<h3>GPS Tracker</h3>
<table border="1px" width="100%">
<tr>
<td>
GPS:
</td> 
<td align="center">
<div id="gpsStatusLabel"></div>   
</td>
</tr>
<tr>
<td>
GPS Strength:
</td> 
<td align="center">
<div id="gpsStrengthLabel"></div>   
</td>
</tr>
<tr>
<td>
Lat:
</td> 
<td align="center">
<div id="latLabel"></div>   
</td>
</tr>
<tr>
<td>
Long:
</td> 
<td align="center">
<div id="longLabel"></div>   
</td>
</tr>   
<tr>
<td>
Status:
</td> 
<td align="center">
<div id="statusLabel"></div>   
</td>
</tr>
</table>       
</body>
</html>

Simple soap client

Below is a simple javascript soap client. The same code can be modified to work as an ajax client by removing the SOAPAction header. The below code accepts the service URL, soap envelope, SOAPAction header name (because it may be of different case in different technology), action and method.

Javascript example
<html>
<head>
<title>Soap Client</title>
<script>
var READY_STATE_UNINITIALIZED=0;
var READY_STATE_LOADING=1;
var READY_STATE_LOADED=2;
var READY_STATE_INTERACTIVE=3;
var READY_STATE_COMPLETE=4;
var xmlHttpRequest;
function getXmlHttpRequest()
{
 var xRequest=null;
 if (window.XMLHttpRequest)
 {
  xRequest=new XMLHttpRequest();
 }
 else if (typeof ActiveXObject != "undefined")
 {
  xRequest=new ActiveXObject("Microsoft.XMLHTTP");
 }
 return xRequest;
}
function handleEmptyString(value,userMessage)
{
    var status=false;
    if(value == "")
    {
        alert(userMessage);
    }
    else
    {
        status=true;
    }
    return status;
}
function sendRequest(url,soapActionHeaderName,
                        soapAction,params,httpMethod,contentType)
{
    var status=false;
    status=handleEmptyString(url,"Please enter the URL.");
    if(status == true)
    {
        status=handleEmptyString(soapActionHeaderName,"Please enter the Soap action header name.");
        if(status == true)
        {
            status=handleEmptyString(soapAction,"Please enter the Saop action.");
            if(status == true)
            {
                status=handleEmptyString(params,"Please enter the soap request.");
                if(status == true)
                {
                    status=handleEmptyString(contentType,"Please enter the content type.");
                }
            }
        }
    }
    if(status==true)
    {
        //Disable mozilla security restriction
        if(window.netscape &&
        window.netscape.security.PrivilegeManager.enablePrivilege)
        {
            var pm=netscape.security.PrivilegeManager;
            pm.enablePrivilege('UniversalBrowserRead');
        }
        // If method not set
        if (!httpMethod)
        {
            httpMethod="GET";
        }
        xmlHttpRequest=getXmlHttpRequest();
        if (xmlHttpRequest)
        {
            xmlHttpRequest.onreadystatechange=onReadyStateChange;
            xmlHttpRequest.open(httpMethod,url,true);
            xmlHttpRequest.setRequestHeader(
            "Content-Type",contentType);
            xmlHttpRequest.setRequestHeader(soapActionHeaderName,soapAction);
            xmlHttpRequest.send(params);
        }
    }
}
function onReadyStateChange()
{
    var ready=xmlHttpRequest.readyState;
    var data=null;
    if (ready==READY_STATE_COMPLETE)
    {
        data=xmlHttpRequest.responseText;
        //... do something with the data...
        document.getElementsByName("taResponse")[0].value=data;
    }
    else
    {
        data="Loading...["+ready+"]";
        document.getElementsByName("taResponse")[0].value=data;
    }
}
function sendData()
{
    var url=document.getElementsByName("txtURL")[0].value;
    var params=document.getElementsByName("taRequest")[0].value;
    var httpMethod=document.getElementsByName("txtMethod")[0].value;
    var soapActionHeaderName;
    soapActionHeaderName=document.getElementsByName("txtActionHeaderName")[0].value;
    var soapAction=document.getElementsByName("txtAction")[0].value;
    var contentType=document.getElementsByName("txtContentType")[0].value;
    sendRequest(url,soapActionHeaderName,soapAction,params,httpMethod,contentType);
}
function clearData()
{
    document.getElementsByName("taResponse")[0].value="";
}
</script>
</head>
<body>
<h1>Soap client</h1>
<table>
<tr>
<tr>
<td>URL: (e.g. http://xyz.com/service)</td>
<td><input type="text"
value="http://localhost:8080/CalculatorProj/services/Calculator"
name="txtURL" size="150"/></td>
</tr>
<td>Request:</td>
<td><textarea rows="12" cols="120" name="taRequest">
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:q0="http://wtp" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
    <q0:add>
      <q0:number1>5</q0:number1>
      <q0:number2>6</q0:number2>
    </q0:add>
  </soapenv:Body>
</soapenv:Envelope>
</textarea>
</td>
</tr>
<tr>
<td>Action header name:</td>
<td><input type="text" value="SOAPAction" name="txtActionHeaderName"/></td>
</tr>
<tr>
<td>Action:</td>
<td><input type="text" value="add" name="txtAction"/></td>
</tr>
<tr>
<td>Content type:</td>
<td><input type="text" value="text/xml; charset=utf-8" name="txtContentType" /></td>
</tr>
<tr>
<td>Method: (GET/POST)</td>
<td><input type="text" value="POST" name="txtMethod"/></td>
</tr>
<tr>
<td>Response:</td>
<td><textarea rows="8" cols="120" name="taResponse"></textarea></td>
</tr>
<tr>
<td></td>
<td align="center">
    <input type="button" value="Send" onclick="sendData()"/>
    <input type="button" value="Clear Result" onclick="clearData()"/>
</td>
</tr>
</table>
</body>
</html>

Note: This code sample works only with in your domain. If you want to try across domain then please refer Google AJAX APIs.

Google gadget

Goto www.google.com and locate iGoogle (top right).
Sing In to iGoogle. Play around with the default gadgets on iGoogle.

Install Google Gadget Editor.

Read how-to-make-google-gadgets and make your first Google gadget.

Refer Google Gadgets for more info.

Monday, August 23, 2010

Reading cross domain JSON (AJAX)

If you want to read JSON content from a different domain, let us say you want to read JSON content from http://twitter.com, then here is a simple example using JQUERY JSON API.

http://twitter.com JSON content link is http://api.twitter.com/1/statuses/public_timeline.json?callback=?.

Javascript example with jQuery.each() loop
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
var JSONPUBICURL="http://api.twitter.com/1/statuses/public_timeline.json?callback=?";
var TWITTERURL="http://twitter.com/";
function getJSON()
{
var strHTML='';
var imgURL="";
$.getJSON(JSONPUBICURL,
function(data){
strHTML+='<table border="0px">';
$.each(data, function(i, item) {

    imgURL=item.user["profile_image_url"];

    strHTML+='<tr>';
    strHTML+='<td valign="top">';
    strHTML+='<img src="'+imgURL+'" alt="'+item.user["screen_name"]+'" title="'+item.user["screen_name"]+'" height="50px" width="50px"/>';
    strHTML+='</td>';
    strHTML+='<td valign="top" >';
    strHTML+='<a href="'+TWITTERURL+item.user["screen_name"]+'/statuses/'+item.id+'" target="_blank" >'+item.text+'</a><br/>';
    strHTML+=item.created_at+' [via '+item.source+']<br/>';
    strHTML+='</td>';
    strHTML+='</tr>';
});
strHTML+='</table>';
strHTML+='<div align="right" ><a href="'+TWITTERURL+'" target="_blank">more...</a></div>';
document.getElementById("tweets").innerHTML=strHTML;
});
}
</script>
<div id="tweets"></div>
<script>
    $(document).ready(getJSON());
</script>

Note: using this approach you can get the live tweets from http://twitter.com.


Javascript example with for loop
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
var JSONPUBICURL="http://api.twitter.com/1/statuses/public_timeline.json?callback=?";
var TWITTERURL="http://twitter.com/";
function getJSON()
{

var strHTML='';
var imgURL="";

$.getJSON(JSONPUBICURL,
function(data){
strHTML+='<table border="0px">';
var length=data.length;
for(var i=0;i<length;i++)
{
    imgURL=data[i].user["profile_image_url"];
    strHTML+='<tr>';
    strHTML+='<td valign="top">';
    strHTML+='<img src="'+imgURL+'" alt="'+data[i].user["screen_name"]+'" title="'+data[i].user["screen_name"]+'" height="50px" width="50px"/>';
    strHTML+='</td>';
    strHTML+='<td valign="top" >';
    strHTML+='<a href="'+TWITTERURL+data[i].user["screen_name"]+'/statuses/'+data[i].id+'" target="_blank" >'+data[i].text+'</a><br/>';
    strHTML+=data[i].created_at+' [via '+data[i].source+']<br/>';
    strHTML+='</td>';
    strHTML+='</tr>';

}
strHTML+='</table>';
strHTML+='<div align="right" ><a href="'+TWITTERURL+'" target="_blank">more...</a></div>';
document.getElementById("tweets").innerHTML=strHTML;

});

}
</script>
<div id="tweets"></div>
<script>
    $(document).ready(getJSON());
</script>

for loop may be faster than jQuery.each() loop. see jQuery tests in Low Level JavaScript Performance.

Sunday, August 22, 2010

Reading cross domain RSS feeds (AJAX)

If you want to read an RSS feed from a different domain, let us say you want to read an RSS feed from http://digg.com, then here is a simple example using Google AJAX Feed API.

http://digg.com RSS feed link is http://feeds.digg.com/digg/popular.rss.

Javascript example
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script>
var RSSURL="http://feeds.digg.com/digg/popular.rss";
var DIGGURL="http://digg.com/";
function getFeed()
{
var strHTML='';
var feed = new google.feeds.Feed(RSSURL);
feed.load(function(result) {
if (!result.error) {    
    var length=result.feed.entries.length;
    for (var i = 0; i < length; i++) {
        var entry = result.feed.entries[i];
        strHTML+='';
        strHTML+='<a href="'+entry.link+'" target="_blank">'+entry.title+'</a><br/>';
        strHTML+=entry.publishedDate+'<br/>';
        strHTML+='<div>';
        strHTML+=entry.contentSnippet+'<br/>';
        strHTML+='</div>';
        strHTML+='<br/>';
    }
    strHTML+='<div align="right"><a href="'+DIGGURL+'" target="_blank">more...</a></div>';
    document.getElementById("digg").innerHTML=strHTML;
}
});
}
</script>
<div id="digg"></div>
<script>
    google.load("feeds", "1");
    google.setOnLoadCallback(getFeed);
</script>

Note: As the Google AJAX Feed API uses Feedfetcher, feed data from the AJAX Feed API may not always be up to date. The Google feed crawler ("Feedfetcher") retrieves feeds from most sites less than once every hour. Some frequently updated sites may be refreshed more often.

Wednesday, August 18, 2010

OpenID Authentication

If you are developing a web application for internet and your web hosting plan does not support SSL and want to support user Sign Up and Sign In, then consider using OpenID authentication mechanism.

Check this URL Federated Login for Google Account Users.

Using Janrain Engage you can build OpenID Sing In module with in few minutes.

There is another quick and easy OpenID library is Dope OpenID.

Thursday, June 17, 2010

How to write a program?

Program accepts input, performs the function and produces the output.

Accept inputs → Perform the function (logic) → Produce output

Let us try to write a simple calculator. The calculator has to support addition, subtraction, multiplication and division and also display the result.
Try to write the calculator program on a paper by following the steps below
Step #1 - Identify the user inputs.
number1
number2
operation
Step #2 - Identify the output.
result
Step #3 - Write the logic.
if operation is "add"
{
    number1+number2=result
}
if operation is "sub"
{
    number1-number2=result
}
if operation is "mul"
{
    number1*number2=result
}
if operation is "div"
{
    number1/number2=result
}
Step #4 - Display the output (result).
Now try to execute the program on the paper by following the steps
Step #1 - Accept user inputs
number1=8
number2=7
operation="sub"
Step #2 - Nothing to do in this step
Step #3 - Execute the logic
if operation is "add"
{
    number1+number2=result
}
if operation is "sub"
{
    number1-number2=result
    8 - 7 = 1(result)
}
if operation is "mul"
{
    number1*number2=result
}
if operation is "div"
{
    number1/number2=result
}
Step #4 - Display the result
Result is 1
The program works fine on the paper.
C# example- Now open Microsoft Visual Studio
or Microsoft Visual C# 2008 Express Edition and create a
console application (File → New Project → Console Application) and try to write the program as below.
using System;

namespace calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            //Identify the user inputs
            float Number1;
            float Number2;
            string Operation;

            //Identify the output
            float Result=0;

            //Accept user inputs
            //can write code to get the input through the console or user interface
            Number1=8;
            Number2=7;
            Operation = "sub";

            //Write the logic
            if ("add" == Operation)
            {
            Result = Number1+Number2;
            }
            if ("sub" == Operation)
            {
            Result = Number1 - Number2;
            }
            if ("mul" == Operation)
            {
            Result = Number1 * Number2;
            }
            if ("div" == Operation)
            {
            Result = Number1 / Number2;
            }

            //Display the output
            Console.Write("Result is {0}",Result);

            //To make the console wait for the user to read the result
            Console.ReadLine();
        }
    }

}
Output:
Result is 1
The above program works fine. So now try to write the logic
or function part as class as below.
using System;

namespace ConsoleApplication6
{
    class Calc//also called as type
    {
        public Calc()//constructor
        {

        }
        //Logic as function
        public float Add(float Num1, float Num2)//function with arguments/inputs
        {
            float Result;//local variable
            Result = Num1 + Num2;
            return Result;//return Result/output
        }
        //Logic as function
        public float Sub(float Num1, float Num2)//function with arguments/inputs
        {
            float Result;//local variable
            Result = Num1 - Num2;
            return Result;//return Result/output

        }
        //Logic as function
        public float Mul(float Num1, float Num2)//function with arguments/inputs
        {
            float Result;//local variable
            Result = Num1 * Num2;
            return Result;//return Result/output
        }
        //Logic as function
        public float Div(float Num1, float Num2)//function with arguments/inputs
        {
            float Result;//local variable
            Result = Num1 / Num2;
            return Result;//return Result/output
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //Identify the user inputs
            float Number1;
            float Number2;
            string Operation;

            //Identify the output
            float Result = 0;

            //Accept user inputs
            //can write code to get the input through the console or user interface
            Number1 = 8;
            Number2 = 7;
            Operation = "sub";

            Calc Calc1 = new Calc();//create new Calc

            //Display the inputs
            Console.WriteLine("Number1 is {0},Number2 is {1}", Number1, Number2);
            //Write the logic
            if ("add" == Operation)
            {
                //Display the operation
                Console.WriteLine("Operation is Add");
                Result=Calc1.Add(Number1, Number2);
            }
            if ("sub" == Operation)
            {
                //Display the operation
                Console.WriteLine("Operation is Sub");
                Result = Calc1.Sub(Number1, Number2);
            }
            if ("mul" == Operation)
            {
                //Display the operation
                Console.WriteLine("Operation is Mul");
                Result = Calc1.Mul(Number1, Number2);
            }
            if ("div" == Operation)
            {
                //Display the operation
                Console.WriteLine("Operation is Div");
                Result = Calc1.Div(Number1, Number2);
            }

            //Display the output
            Console.Write("Result is {0}", Result);

            //To make the console wait for the user to read the result
            Console.ReadLine();



        }
    }
}
Output:
Number1 is 8,Number2 is 7
Operation is Sub
Result is 1
JavaScript example- Now let us write the same
program in JavaScript and dhtml, so open a notepad and try to
write the program as below and save it as .html file.
<html>
    <head>
        <title>Calculator</title>
        <style>
        body{
        background:blue;
        color:white;
        }
        td{
        background:white;
        color:maroon;
        font-family:verdana;
        font-size:15px;
        }
        #cssresult{
        background:fuchsia;
        color:lime;
        }
        .cssbutton{
        background:yellow;
        }
        </style>
        <script>
        function calc(op)
        {
            //Identify the user inputs
            var number1;
            var number2;
            var operation;
            //Identify the output
            var result;
            //Accept user inputs
            number1 = (parseFloat)(document.getElementsByName("txtnum1")[0].value);
            number2 = (parseFloat)(document.getElementsByName("txtnum2")[0].value);
            operation=op;
            //Write the logic
            if(operation == "add")
            {
                result = number1 + number2;
                //Display the result
                document.getElementsByName("txtresult")[0].value=result;
                //Display the result (dhtml)
                document.getElementById("divResult")
                .innerHTML="<b>Result is "+result+"</b>";
                alert("Result is "+result);
            }
            if(operation == "sub")
            {
                result = number1 - number2;
                //Display the result
                document.getElementsByName("txtresult")[0].value=result;
                //Display the result (dhtml)
                document.getElementById("divResult")
                .innerHTML="<b>Result is "+result+"</b>";
                alert("Result is "+result);
            }
            if(operation == "mul")
            {
                result = number1 * number2;
                //Display the result
                document.getElementsByName("txtresult")[0].value=result;
                //Display the result (dhtml)
                document.getElementById("divResult")
                .innerHTML="<b>Result is "+result+"</b>";
                alert("Result is "+result);
            }
            if(operation == "div")
            {
                result = number1 / number2;
                //Display the result
                document.getElementsByName("txtresult")[0].value=result;
                //Display the result (dhtml)
                document.getElementById("divResult")
                .innerHTML="<b>Result is "+result+"</b>";
                alert("Result is "+result);
            }
            if(operation == "clear")
            {
                document.getElementsByName("txtnum1")[0].value="";
                document.getElementsByName("txtnum2")[0].value="";
                document.getElementsByName("txtresult")[0].value="";
                document.getElementById("divResult").innerHTML="";
            }
        }
        </script>
    </head>
    <body >
        Calculator
        <table border="2">
        <tr>
        <td>Number 1</td>
        <td><input type="textbox" name="txtnum1"></td>
        <td class="cssbutton">
            <input type="button" value="Add" onclick="calc('add')">
        </td>
        </tr>
        <tr>
        <td>Number 2</td>
        <td><input type="textbox" name="txtnum2"></td>
        <td class="cssbutton">
            <input type="button" value="Sub" onclick="calc('sub')">
        </td>
        </tr>
        <tr >
        <td>Result</td>
        <td id="cssresult"><input type="textbox" name="txtresult"></td>
        <td class="cssbutton">
            <input type="button" value="Mul" onclick="calc('mul')">
        </td>
        </tr>
        <tr>
        <td colspan="2" class="cssbutton">
            <input type=button value="Clear" onclick="calc('clear')">
        </td>
        <td class="cssbutton">
            <input type="button" value="Div" onclick="calc('div')">
        </td>
        </tr>
        </table>
        <div id="divResult"></div>
    </body>
</html>

Output:
Result is 1

Note: Extend the above program to accept input through the user interface and support more features.

Happy programming!

Note: Please read the guidelines listed in this website for efficient programming.

Software requirements

Requirements of a software form the foundation of the software based product.

Functional and non-functional requirements are derived from the "voice of the customer" (VOC), documents (artifacts) and similar products etc. Success of the software product mainly depends on the non-functional requirements like
  • performance – time taken to perform an operation (throughput) and memory usage
  • scalability - ability to easily expanded or upgraded on demand
  • usability – ease of use and intuitiveness
  • architecture – standalone or client server
  • reliability - ability to yield same result on repeated trials
  • security – ability to protect the system from intruders and protecting the privacy of the users of the software product
  • etc.
and the productivity of software development mainly depends on the non-functional requirements like
  • maintainability (includes extensibility, testability)
  • etc.
Make sure the derived requirements are
  • simple
  • not ambiguous
  • testable
Following are the minimum set of attributes of a requirement
  1. Tag – Requirement tag will be used for traceability (e.g. R1, R2, REQ1, REQ10, FR1, FR10, etc.)
  2. Description