Personal Blog SEP
Polwatta Plant Nursery
Polwatta Plant Nursery - Sri Lanka
Visit Our New Web Site Info- Polwatta Plant Nursery - Colombo Sri Lanka
Sunday, September 14, 2014
How To Work With CodeIgniter Forms
For a web application, HTML forms are the probably most important sections. Because, these are the real interface which make it happen to communicate and receives/store data from visitors. Now a days, we can’t even imagine a website without at least a contact form or so. As always, codeigniter framework have done an incredible job by providing integrated supports to deal with these forms. Basically, codeigniter support for forms has two sections. A library class, known ‘codeigniter forms validation class’. Another is form helper, which is a set of functions to provide easy way to render HTML forms input controls.hese.
Today, in post tutorial, we will learn:
How to create form validation rule
Render a form with codeigniter form helper And
Process submitted data
As Example, We will consider a traditional contact form to illustrate these.
Create Validation Rule Set:
There are two ways to define rules for a form. You can either have it predefined in a config file. Otherwise, you can define the rules dynamically inside the controller function as well. First is better if you wish to reuse the configuration on different pages/controller functions.
Here is an example rule definition in config:
$config['contact_rules'] = array(
'name' => array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email'
),
'subject' => array(
'field' => 'subject',
'label' => 'Subject',
'rules' => 'trim|required|xss_clean'
),
'message' => array(
'field' => 'message',
'label' => 'Message',
'rules' => 'trim|required|xss_clean'
)
);
As you can see on above code, the codeigniter forms configuration is a two-dimensional key/value pair based array. Where, first dimension defines fields and second dimension defines three different property of each item:
field: Defines that name attribute of that particular field.
label: Defines the label text for that field.
rules: Defines the criteria that filed need to be fulfilled. Such as ‘required’ tells the codeigniter form validation class that this field can’t be empty. ‘valid_email’ rule tells to validate the submitted input to a valid email format. ‘trim’ rule actually doesn’t validate anything, rather it just perform an action of trim operation on the submitted input. Similarly, ‘xss_clean’ rule make sure and process input to become safe from security vulnerability.
As an alternative, we can define the rules dynamically in controller function as below:
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'trim|required|xss_clean');
$this->form_validation->set_rules('message', 'message', 'trim|required|xss_clean');
Android Webservice example
In this post, I will be discussing how to invoke web service from Android application. When web methods are invoked from inside Android application, the application gets back the data from the server in the form of XML. The response which has been received can be parsed and rendered in the application as needed.
What is SOAP?
SOAP is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks. It relies on Extensible Markup Language (XML) for its message format, and usually relies on other Application Layer protocols, most notably Hypertext Transfer Protocol (HTTP) and Simple Mail Transfer Protocol (SMTP), for message negotiation and transmission.
Layout XML:
Open main.xml present under /res/layout folder and replace the XML with the below one.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Celsius to Farenheit"
android:textSize="30dp" />
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:numeric="integer"
android:singleLine="true" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="Convert to Farenheit" />
<TextView
android:id="@+id/tv_result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="" android:textSize="26dp"/>
</LinearLayout>
Create following objects under WebserviceActivity class:
private final String NAMESPACE = "http://www.w3schools.com/webservices/";
private final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
private final String SOAP_ACTION = "http://www.w3schools.com/webservices/CelsiusToFahrenheit";
private final String METHOD_NAME = "CelsiusToFahrenheit";
private String TAG = "PGGURU";
private static String celcius;
private static String fahren;
Button b;
TextView tv;
EditText et;
onCreate():
Add following code snippet in the place of onCreate method.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Celcius Edit Control
et = (EditText) findViewById(R.id.editText1);
//Fahrenheit Text control
tv = (TextView) findViewById(R.id.tv_result);
//Button to trigger web service invocation
b = (Button) findViewById(R.id.button1);
//Button Click Listener
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Check if Celcius text control is not empty
if (et.getText().length() != 0 && et.getText().toString() != "") {
//Get the text control value
celcius = et.getText().toString();
//Create instance for AsyncCallWS
AsyncCallWS task = new AsyncCallWS();
//Call execute
task.execute();
//If text control is empty
} else {
tv.setText("Please enter Celcius");
}
}
});
}
Class AsyncCallWS:
Create it as inner class inside WebserviceActivity class.
This class will perform the webservice call which will be executed as separate thread. When execute method is called in onCreate method, it calls the following methods in order:
onPreExecute() – Fahrenheit textview control is set with text ‘Calculation…’
doInBackground() – Invoke getFahrenheit()
onProgressUpdate() -Does nothing
onPostExecute() – Set the Fahrenheit value in textview control
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
Log.i(TAG, "doInBackground");
getFahrenheit(celcius);
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
tv.setText(fahren + "° F");
}
@Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
tv.setText("Calculating...");
}
@Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
What is SOAP?
SOAP is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks. It relies on Extensible Markup Language (XML) for its message format, and usually relies on other Application Layer protocols, most notably Hypertext Transfer Protocol (HTTP) and Simple Mail Transfer Protocol (SMTP), for message negotiation and transmission.
What are we going to develop?
We are gonna develop a simple application to demonstrate how web service is invoked using SOAP protocol in Android application. Application we develop will just convert celcius to Fahrenhiet.
As this application requires Internet connectivity to hit Web Service hosted in remote server, it would be good if Internet connectivity check is done before trying to hit Web Service.
Open main.xml present under /res/layout folder and replace the XML with the below one.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Celsius to Farenheit"
android:textSize="30dp" />
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:numeric="integer"
android:singleLine="true" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="Convert to Farenheit" />
<TextView
android:id="@+id/tv_result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="" android:textSize="26dp"/>
</LinearLayout>
Create following objects under WebserviceActivity class:
private final String NAMESPACE = "http://www.w3schools.com/webservices/";
private final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
private final String SOAP_ACTION = "http://www.w3schools.com/webservices/CelsiusToFahrenheit";
private final String METHOD_NAME = "CelsiusToFahrenheit";
private String TAG = "PGGURU";
private static String celcius;
private static String fahren;
Button b;
TextView tv;
EditText et;
onCreate():
Add following code snippet in the place of onCreate method.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Celcius Edit Control
et = (EditText) findViewById(R.id.editText1);
//Fahrenheit Text control
tv = (TextView) findViewById(R.id.tv_result);
//Button to trigger web service invocation
b = (Button) findViewById(R.id.button1);
//Button Click Listener
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Check if Celcius text control is not empty
if (et.getText().length() != 0 && et.getText().toString() != "") {
//Get the text control value
celcius = et.getText().toString();
//Create instance for AsyncCallWS
AsyncCallWS task = new AsyncCallWS();
//Call execute
task.execute();
//If text control is empty
} else {
tv.setText("Please enter Celcius");
}
}
});
}
Class AsyncCallWS:
Create it as inner class inside WebserviceActivity class.
This class will perform the webservice call which will be executed as separate thread. When execute method is called in onCreate method, it calls the following methods in order:
onPreExecute() – Fahrenheit textview control is set with text ‘Calculation…’
doInBackground() – Invoke getFahrenheit()
onProgressUpdate() -Does nothing
onPostExecute() – Set the Fahrenheit value in textview control
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
Log.i(TAG, "doInBackground");
getFahrenheit(celcius);
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
tv.setText(fahren + "° F");
}
@Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
tv.setText("Calculating...");
}
@Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
getFahrenheit()
Create this method inside WebserviceActivity class.
Method which involves web service invocation:
Create this method inside WebserviceActivity class.
Method which involves web service invocation:
public void getFahrenheit(String celsius) {
//Create request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Property which holds input parameters
PropertyInfo celsiusPI = new PropertyInfo();
//Set Name
celsiusPI.setName("Celsius");
//Set Value
celsiusPI.setValue(celsius);
//Set dataType
celsiusPI.setType(double.class);
//Add the property to request object
request.addProperty(celsiusPI);
//Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
//Set output SOAP object
envelope.setOutputSoapObject(request);
//Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//Invole web service
androidHttpTransport.call(SOAP_ACTION, envelope);
//Get the response
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
//Assign it to fahren static variable
fahren = response.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
Saturday, September 13, 2014
Get Started: Chat application With node.js Socket.io
For 3rd year sep project i implement a chat application in contact us page using node.js frame work and socket.io.
this is the way how i implement the chat application.
The web framework
The first goal is to setup a simple HTML webpage that serves out a form and a list of messages. We’re going to use the Node.JS web framework express to this end. Make sure Node.JS is installed.
First let’s create a package.json manifest file that describes our project. I recommend you place it in a dedicated empty directory (I’ll call mine chat-example).
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {}
}
**Now, in order to easily populate the dependencies with the things we need, we’ll use npm install --save:
npm install --save express
**Now that express is installed we can create an index.js file that will setup our application.
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
This translates into the following:
- Express initializes
appto be a function handler that you can supply to an HTTP server. - We define a route handler
/that gets called when we hit our website home. - We make the http server listen on port 3000.
Serving HTML
So far in index.js we’re calling res.send and pass it a HTML string. Our code would look very confusing if we just placed our entire application’s HTML there. Instead, we’re going to create a index.html file and serve it.
Let’s refactor our route handler to use sendfile instead:
app.get('/', function(req, res){
res.sendFile('index.html');
});
And populate index.html with the following:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
Integrating Socket.IO
Socket.IO is composed of two parts:
A server that integrates with (or mounts on) the Node.JS HTTP Server: socket.io
A client library that loads on the browser side: socket.io-client
During development, socket.io serves the client automatically for us, as we’ll see, so for now we only have to install one module:
npm install --save socket.io
That will install the module and add the dependency to package.json. Now let’s edit index.js to add it:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Now in index.html I add the following snippet before the </body>:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
That’s all it takes to load the socket.io-client, which exposes a io global, and then connect.
Emitting events
The main idea behind Socket.IO is that you can send and receive any events you want, with any data you want. Any objects that can be encoded as JSON will do, and binary data is supported too.
Let’s make it so that when the user types in a message, the server gets it as a chat message event. The scripts section in index.html should now look as follows:
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>
And in index.js we print out the chat message event:
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
Subscribe to:
Posts (Atom)

