Sunday, January 15, 2012

What is MVC? How it is implemented in iPhone development?


MVC, a much known term in software industry right now.  I will not spend much time to explain MVC; rather, how it is implemented in IPhone will get more priority in this article. Let’s start.
MVC - simply Model View Controller.
Now take a simple example. Suppose a car. It has a body, four wheels, one steering and one engine. Now, engine is a module, steering is a controller, wheel is a separate module and guess what, body is view. Pretty simple, right. Now come out from the car. In software, an object which represents project entities is module. Controller will do various operations with modules depending on different commands and commands will be sending user interface [view] and the output result will be shown in view itself.
It’s done.
mvc iphone
MVC Architecture 



Cocoatouch is a building block of iPhone development. It is solely following MVC for development. As we understood previously, it has model, view and controller, iPhone development follows the same.  When we create an application using xCode, it will give us a specific folder structure with the support of MVC itself. In the folder one can see view and viewController files.  There will be two kinds of file or rather we can say same named files with two different extensions [*.h , *.m].



Now, let’s see ,what is in it.
[.H] file will contain something like ----

@interface MainViewController : UIViewController {
UILabel *label;// label is added to it
}

@property (nonatomic, retain) IBOutlet UILabel *label;
 //will be used as a reference to controller
@end

Here we can see, it is an interface which inherits UIViewController[Master class for all view]. It also contains a label[Added by us].

[.m]file will contain ---
#import "MainViewController.h"
#import "MainView.h"

@implementation MainViewController
@synthesize label; //to do sync properties in interface

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}

- (void)dealloc {
[label release];
[super dealloc];
}

@end

Here, we implement the created interface in .H file as far as MVC concerns.  And it will work with all the properties declared in interface. Here we use @synthesize to synchronize attributes in [.m] and [.h].
Now in this way we created a controller and an interface for view. Sounds confusing?  Yes , View.h file will work as an interface for view [normal MVC concept].  
We will have .xib files too. It is basically an xml which represents the actual UI.

Now , from the toolbox we can get all available controls ,which we can drag and drop to the UI to design as per our requirement. [The process of designing will not be here in this article. It’s all about MVC in iPhone]
Now it is the time to connect the UI to View to interact with controller.


In view controller connection window, we can find all the added controls in a list. By dragging the listed control reference to the View object cube we can map the UI objects to view properties. All the code related to it will be auto generated. So in this way view and controller will be connected.
Now, we can create a custom model to interact with values sent from view. To do that we need to create an interface of a model in myCar.h file-
#import <foundation/Foundation.h>

@interface myCar : NSObject {
    NSString *name;
}

@property (nonatomic, retain) NSString *name;

+ (myCar *)sharedModel;

@end

Now we are ready to implement the interface in myCar.m file.
#import "myCar.h" 
@implementation myCar \\    here the implementation
@synthesize name;\\ synthesize with interface implementation

- (id) init
{
    self = [super init];
    if (self != nil) {
        name = @"";
    }
    return self;
} 
- (void) dealloc
{
    [name release]; \\release memory from device
    [super dealloc];
}
 @end
Our model is also created.  It’s the time to implement model in our code. See bellow-
- (IBAction)textChanged:(id)sender
{
    myCar *car = [myCar sharedModel];
    model.text = textField.text;
}

It is just an over view. Explore much by creating an app.
Enjoy

Wednesday, January 11, 2012

Nodejs with database access

Now, it is the time for database (mysql) access. Yes, now we will access database and show it to pages. In my previous tutorial, I already explained page creation and handling requests. Here, to access database we need driver and a connection string. Driver will do all the work for you and make the thing very easy and smooth. 
See the code-

var http = require('http');
var sys = require('util');
var hash=require('./hashish');    //lib can be downloaded [here ‘./’ part is showing location of the library.
//I stored the lib in application directory.]
var qs = require('querystring');
var mysql = require('./mysql');  //lib can be down loadded
//----Create mysql client using mysql lib
//===========================================================
var client = mysql.createClient({
  user: 'root', //-------will change as per mysql server user and password
  password: 'root'
});
//----------Connect to Database
//===============================================================
function  db (client)
{// use myDB database from mysql
    client.query('USE myDB, function(error, results) {
        if(error) {
            console.log('Error: ' + error.message);
            client.end();
            return;
        }
    });
}
 //----------------------set data to  title_tbl
function SetData (client)
{
  var values = ['1', '2', 'technobelities'];
  client.query('INSERT INTO title_tbl SET company_id = ?, title_id = ? , description = ?', values,
    function(error, results) {
      if(error) {
        console.log("Error: " + error.message);
        client.end();
        return;
      }
      console.log(' Inserted  Data: ' + results.affectedRows + ' row.');
      console.log(' inserted Id: ' + results.insertId);
    }
  );
  GetData(client);
}
//---------------------get data  from db
function  GetData (client,res)
{
var data="";
  client.query(
    'SELECT * FROM title_tbl',
    function selectCb(error, results, fields) {
      if (error) {
          console.log(' Error: ' + error.message);
          client.end();
          return;
      }

      if(results.length > 0)
      {
        var firstResult = results[0];
        data= (' Company id: ' + firstResult['company_id'] + ';') +dataContent;
        data=('Description: ' + firstResult['description']+ ';') +dataContent;
res.end(data);
      }
                  console.log(data);
  });

  client.end();
  console.log('Connection closed');
  return data;
}
var server = http.createServer(function(req, res) {
db(client);
GetData(client);
});
server.listen(8000);


Its …done. Try to customize code as par requirement.  Feel free to ask any query.

Tuesday, January 3, 2012

Nodejs with handlers in javascript


We can point site URL to a specific handler, created by nodejs(server side javascript). Hummm, Sounds exceptional. Let’s see.   We are able to create a server in previous post. Have you noticed request and response in the code? Request object contains all the Request properties. URL (string) is one of it. [In previously it was uri(object).]  From the url property we can get the requested url path and according to that we can handle the request as per plan. Pretty simple. Now see the code[written in notepad, you can use any other editor] -

var http = require('http');
var sys = require('util');
 var server = http.createServer(function(req, res) {
  switch (req.url) { //check the request url
    case '/’:
      display_home(req, res); //pointing handler
      break;
    case '/registration’: 
      display_registration (req, res);
      break;
    default:
      show_404(req, res);//no handler found
      break;
  }
});
server.listen(8088);
//====== Server generation and handler pointing is done======
//==========First handler===============
function display_ home (req, res) {
//======response type set=========
  res.writeHead(200, {'Content-Type': 'text/html'});
//=======response content============== 
res.end(
    '<div> This is your home page</div><a  href=”/registration”> Click to register</a><a  href=”/nothing”> nothing</a>'
  );
}
//========Second handler=================
function display_ registration (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(
    '<div> This is your registration page</div>'
  );
}
//==========Error handler==========
function show_404(req, res) {
  res.writeHead(404, {'Content-Type': 'text/plain'});
  res.end('No handler found');
 
}

Save the code with js extension. Run this with node command  as shown in previous post and traverse through your first nodeJs site.
Let me know your quires.
Enjoy.

Create server in NodeJs - Server side Javascript

Nodejs is a simple javascript [Server side] which creates an http server with a specified port. Yes, it is creating a http server by using its library. Now suppose you have IIS or apache in your machine, running on a port 80. Now, if we run bellow code , it will create a server with a different port number[suppose : 8088]. Now , if you run the  url : http://localhost/ and http://localhost:8088/ ,two different server will be accessed. 

var http = require("http");   //import http
http.createServer(function(request, response) { //create server in node js
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write(“<h1>Hi to nodejs</h1>”);  // return for the request.
  response.end();
}).listen(8088); //port for the server is specified
 
A small code for creating server dynamically. We can see- request and response as input with create Server. These will contain the request and response object.  I bit strange structure, right. Here createServer function takes a function as an input which takes request and response as it’s input.  If any doubt ,please ask me.  
But, how or where we will run this code? A bit work needs to be done.
Download NodeJs from http://nodejs.org/ . Run it in in the development machine[it supports Windows,Linux and MAC; I used windows]. You will get the Nodejs folder in the installation location. It contains - node_modules, node.exe and npm.cmd. To execute the code above , you have to use node.exe . Go to command prompt -> nodejs folder. This is where you will use your code. Create a folder called MyServer.  Save your code in it [Suppose : server.js]. That’s it. You are ready to go.
Command to execute the code-

>node  “C:\Program Files\nodejs\MyServer\server.js”

Now , open any browser and put http://localhost:8088/  in address bar.  You will see a big ->                   Hi to nodejs. You can design any page structure using HTML in the place of “<h1>Hi to nodejs</h1>”.
That’s it for now. Enjoy J