MongoDB Management Service To Rescue Your Application!

In today’s tutorial we’ll be looking at:
Installing Python
Installing PyMongo (Note: PyMongo is a python driver for MongoDB)
..and running mms-agent from your computer(localhost)

I’m using Windows 7 64-bit machine and the installation procedure are shown for the same.

mms-on-devices

Disclaimer: This is not a paid post and neither am I using any affiliate links in this post. I found MMS(MongoDB Management Service) incredibly useful and I wish I knew about it earlier. The monitoring and alerting services can save your applications reputation, and the backup service will literally save your application in disasters situations.

Requirements
MongoDB software: MongoDB – Getting Started Guide
Python 2.7.3
Setuptools
PyMongo driver software

mms-installation-software

Why use MMS ?

  • MMS tracks the key database and hardware metrics important for managing a MongoDB deployment
  • Performance Visualization
  • Custom Alerts
  • Back-up service ..etc

MongoDB Management Service To Rescue Your Application!


[youtube https://www.youtube.com/watch?v=HkvrksJL3Jg]

YouTube Link: https://www.youtube.com/watch?v=HkvrksJL3Jg [Watch the Video In Full Screen.]



Steps
Step 1: Install Python 2.7.3 at C:\Python27
Step 2: Install setuptools
Command to install setuptools

1
2
C:\>cd Python27
C:\Python27>python D:\Python\setuptools\ez_setup.py

This installs easy_installer inside C:\Python27\Scripts folder. Easy installer helps in installing drivers.
Step 3: Now install Pythons MongoDB driver: PyMongo, with the following command.

1
2
C:\Python27>cd Scripts
C:\Python27\Scripts>easy_install PyMongo

This would install PyMongo driver

Step 4: Start MongoDB server.

Step 5: Log into your MMS account, and download the MMS-AGENT. Extract the mms-agent files into a folder. In our case, we extract it to D:\Python\mms-agent
Step 6: Now run the mms-agent with the following command

1
2
3
4
C:\>D:
D:\>cd Python
D:\Python>cd mms-agent
D:\Python\mms-agent>agent.py

This starts mms-agent.

Step 7: Go to your mms account – Fill the form with the host name, port number and other details

add-a-host-mongoDB-management-service-mms

Host Type: Standalone (for this example)
Internal Hostname: 127.0.0.1 (ip address for localhost)
Port: 27017 (default port used my MongoDB server)
DB Username and DB Password: are optional

inside-mms-account

Now it’ll start to fetch the meta data metrics via your IP address, as the agent is installed on your local machine and it knows your network IP address.

inside-mongoDB-management-service-account

Key things inside your account
Events: restart, shut-down or downtime etc
Alerts: To alert you in certain situations. You get emails for downtime etc, once setup.
Backup: It’s a premium service, which costs a little – backup service is pay-as-you-go service billed via credit card.
Users: You could invite people as admin or read only user. This way, you could bring in your team mates/colleagues to analyze and help you in performance tuning of your application.
Dashboard: You can customize your dashboard to give you quick view of key aspects of your application is a rich web console. You could have RAM usage statistics or query performance metrics etc.
Settings: Normal profile information: email id, password, phone verification etc.

Application Performance
Checking with the query performance and your application behavior from the very beginning of application development is recommended. And MMS is a perfect solution for this. This is one of the main reasons for this video tutorial. Running MMS on production servers is easy. You’ve bunch of plugins pre-installed at your host, you just need to enable it and insert the secret keys provided to you inside mms-agent file. But I would recommend you to watch for your application behavior from as early as in its development stage.

Note: You should know the norms of your application behavior, so that you can notice when there is abnormalities. MMS helps you effectively do that.

MongoDB Management Service is free service for getting metrics and setting alerts. And you only pay, if you use backup service and you pay for it as you use it.

Optimize / Improve Performance of jQuery Applications

Video tutorial illustrating simple tweaks which help optimize / improve the performance of jQuery Applications.

To Optimize
1. Write all javascript programs in an external file and embed it into the html pages.
2. Whenever possible, embed the javascript file at the end of body tag. i.e., just before the closing body tag.
3. It’s also good practice to separate CSS coding to an external file and then embed it to the web pages.

How it helps ?
1. i. If you have thousands of web pages, writing the same code on all the pages and maintaining it and/or modifying it is a touch job.
Having it in an external file helps in re-usability and maintainability.
ii. It only loads the javascript files once and do not load the same files again and again for all other pages, hence saving a lot of bandwidth. Also highly optimizing the load time of web pages.
2. When the parser encounters these javascript files, they stop loading all other elements and allocate all its bandwidth to load javascript file. So writing it at the end of body tag helps. Since all other important elements like images, content will be loaded before these time-consuming javascript files.

Video Tutorial: Optimize / Improve Performance of jQuery Applications


[youtube https://www.youtube.com/watch?v=BsPgkr-YGMs]

YouTube Link: https://www.youtube.com/watch?v=BsPgkr-YGMs [Watch the Video In Full Screen.]



Above video uses Animation of Text and Image: jQuery code to illustrate the optimization concept. If you have not already seen the video, we highly encourage you to watch it and practice it.

In our future tutorials we will be writing most of our javascript code in external file and will be embedding them at the end of body tag. With this tutorial you know why we would do that!

Build VOTE / LIKE, UNLIKE Feature: PHP & MySQL

In Voting system we need to make sure, one person votes only once, to a particular poll. Or One person can only like a particular image once.
Person who votes must be allowed to vote down and the person who likes must be allowed to unlike the same image / item etc.

Looks complicated? Relax, its not that complicated!

Let me explain the logic and direct you to some videos..
First, build your User Signup and Login forms.
Make username as primary key.

Now create another table with two fields. id(primary key and auto_increment) and image.

Now another table with two fields again: username and id
Make username and id as primary keys..that is, composite primary key.

In database design, a composite key is a key that consists of 2 or more attributes that uniquely identify an entity occurrence. Each attribute that makes up the compound key is a simple key in its own right.

This way, same user can not like / vote for the same image twice! It would throw error, as it violets composite key rule. You could make use of Die() and show appropriate message or still better use if else and if the query has not executed(due to violation of composite key rule) show links in the else part to vote down or unlike. There you could simply delete the entry from vote table.

Video Tutorial: Build VOTE / LIKE, UNLIKE Feature: PHP & MySQL


[youtube https://www.youtube.com/watch?v=XZ6hBLNayr0]

YouTube Link: https://www.youtube.com/watch?v=XZ6hBLNayr0 [Watch the Video In Full Screen.]



Take 3 tables: user, image and vote
username is primary key in user table.
id is primary key in image table. attributes: id and image
id and username are composite primary key in vote table.

Vote / Like, Unlike

1
mysql> INSERT INTO vote VALUES( ‘2’, ’apple’ );

Count Vote / Like

1
mysql> SELECT count(*) FROM vote WHERE id= ‘2’;

Vote down / Unlike

1
mysql> DELETE FROM vote WHERE( id=‘2’ AND username=’apple’ );

Make sure to take the values of id and username dynamically. Am showing 2 and apple for the sake of illustration.
username will be present inside the session variable once the user logs in.
id value will be associated with the like or vote link/button of the image. [id is unique to each individual image]

Taking advantage of the error thrown by the composite primary key. i.e., using if else we check if the user has already voted or liked particular image or participated in a particular poll, if yes, we show him/her unlike or vote down link/button.

Vote, Vote Down or Like, Unlike Feature

1
2
3
4
If( mysql_query(“INSERT INTO vote VALUES( ‘2’, ’apple’ )”)  )
  echo “Thanks for the vote”;
else
  echo “<a href=‘vote.php?down=1’>Vote Down</a>”;

You could mix this simple logic with some CSS and other stuffs like AJAX and implement the voting system easily in a short period of time, like a pro!

Email Verification in PHP: Part 2

This video to illustrates, verification of user email ID by sending a unique URL to be clicked by the user inorder to active his account, to further use the application.

Continuation of Email Verification in PHP: Part 1

login form
login.php

This is bit more than just a simple login form. Because, here we need to check if the user is present in our database, and next, if present, whether the user has activated his/her account or not.

1
2
3
4
5
<form action="log.php" method=post>
email: <input type="text" name="u"/>
Pwd: <input type="password" name="p"/>
<input type="submit"/>
</form>

This is just the login form. Below is the coding of log.php file which does all the decision making activities.

login action page
log.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
< ?php
 
include_once('db.php');
 
?>
 
< ?php
 
 $u = $_POST['u'];
 $p = md5($_POST['p']);
 
 $res = mysql_query("SELECT count(*) from login where(email='$u' and pass='$p')");
 
  $row = mysql_fetch_array($res);
 
 if($row[0]>0)
 {
   echo '<b>Successfully logged in</b><br />';
 
   $rs =  mysql_query("SELECT actv from login where email='$u'");
   $rw =  mysql_fetch_array($rs);
 
   if($rw[0] == 0)
   {
 echo '<b>But please activate your email ID, before proceeding</b>';
 exit();
   } 
   else
   {
              $rs = mysql_query("SELECT name from login where email='$u'");
              $rw= mysql_fetch_array($rs);
 echo "Account activated......<br /> <br /> <blockquote><span color=red >
              Welcome ".$rw[0].",</span><br /><br /> This website will be ready 
              soon, and you'll be among the first to hear from us!<br /> 
              Until then, you can browse through our extensive collection of 
              quality tweets submitted by our present members 
              <a href=http://www.twitfever.com>Retweet Club</a><br /><br /> 
              Regards,<br />Satish, CEO Technotip IT Solutions and Training 
              Center</blockquote>";
 
exit();
    }
 
 }
 else
   echo "<br />Login Failed";
 
 
?>

again, we are making use of md5() encryption, inorder to check with the already encrypted data present inside the database.

1
2
3
4
5
6
7
8
9
10
$res = mysql_query("SELECT count(*) from login where(email='$u' and pass='$p')");
 
  $row = mysql_fetch_array($res);
 
 if($row[0]>0)
 {
   echo '<b>Successfully logged in</b><br />';
 }
 else
   echo "<br />Login Failed";

with this we are checking if the user has already registered or not.

If he/she is a registered user, then we check if the account has been activated or not..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$rs =  mysql_query("SELECT actv from login where email='$u'");
   $rw =  mysql_fetch_array($rs);
 
   if($rw[0] == 0)
   {
 echo '<b>But please activate your email ID, before proceeding</b>';
 exit();
   } 
   else
   {
              $rs = mysql_query("SELECT name from login where email='$u'");
              $rw= mysql_fetch_array($rs);
 echo "Account activated......<br /> <br /> <blockquote><span color=red >
              Welcome ".$rw[0].",</span><br /><br /> This website will be ready 
              soon, and you'll be among the first to hear from us!<br /> 
              Until then, you can browse through our extensive collection of 
              quality tweets submitted by our present members 
              <a href=http://www.twitfever.com>Retweet Club</a><br /><br /> 
              Regards,<br />Satish, CEO Technotip IT Solutions and Training Center
              </blockquote>";
 
exit();
    }

Depending on whether the user has activated his/her account we display the appropriate message.

activate.php
This is the file to which the values will be sent to, once the user clicks on the link sent to his/her email.

Using the values sent by the user(upon clicking the link), this script checks the value against the database to see if its valid. If valid, it updates the act attribute value to 1, which indicated the user verified his/her account.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
< ?php include_once('db.php'); ?>
 
< ?php
 
 $act = $_GET['act'];
 $email = $_GET['email'];
 
 $sql = "SELECT rndm from login where email='$email'";
 
 $res = mysql_query($sql);
 $row = mysql_fetch_array($res);
 
 if($row[0] == $act)
 {
  mysql_query("Update login SET actv=1 WHERE email='$email'");
  echo '<b>Your account activated<br /><a href="login.php">Login now</a>';
 }
 else
  echo "Wrong link bro!";
?>

Video Tutorial: Part 2


[youtube https://www.youtube.com/watch?v=Cm5Q0xlir-Q]

YouTube Link: https://www.youtube.com/watch?v=Cm5Q0xlir-Q [Watch the Video In Full Screen.]



Other users:
We can make use of this application and allow or disallow some of the features of our application.
This technique highly helps in combating with the spam issues on the web.

You can purchase this simple script directly for as less as $1.95 get here.

Email Verification in PHP: Part 1

This video to illustrates, verification of user email ID by sending a unique URL to be clicked by the user inorder to active his account, to further use the application.

Use
We can restrict certain features of our application for the accounts which has not been verified.
By this we can know if the email ID is valid and authorized user is using it and no one else.

Database

1
2
3
4
5
6
7
8
9
mysql> create database test;
mysql> use test;
mysql> create table login(
   name varchar(25) not null, 
   pass varchar(60) not null, 
   email varchar(30) primary key,
   phn varchar(15), 
   rndm varchar(20) not null, 
   actv int not null);

Note: Do not make phno as integer, as it can’t handle huge numbers like 9844552841 (if its a phone number!)
email is concede red as Primary Key, as we can identify each user uniquely via this attribute. No two user can have the same email id.

Database connection script
db.php

1
2
3
4
< ?php
 mysql_connect('localhost','DatabaseUsername','DatabasePassword');
 mysql_select_db('DatabaseName');
?>

Registration Code:
register.php

1
2
3
4
5
6
7
<form action="save.php" method="post">
Name: <input type="text" name="n"/>
eMail ID: <input type="text" name="email"/>
password: <input type="password" name="password"/>
Phn number: <input type="text" name="phn"/>
<input type="SUBMIT"/>
</form>

The user input will be passed to save.php via post method.

save.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
< ?php include_once('db.php'); ?>
< ?php
 
$n = $_POST['n'];
$p = md5($_POST['password']);
$email = $_POST['email'];
$phn = $_POST['phn'];
$rndm = rand(34565, 993240);
 
$sql ="INSERT into login values('$n','$p','$email','$phn', '$rndm', '0')";
 
if(!mysql_query($sql))
 echo "Not updated..".mysql_error();
else
{
 
  $url = "http://yourdomainname.com/reg/activate.php?act=$rndm&email=$email";
  $cont = "click this link $url To activate your account";
 
  if( mail($email, "Activate Account!", $cont, "From: [email protected]") )
   echo '<b>Please visit your email to activate your account
         <br />After Activation, <a href="login.php">log into your account</a>';
  else
   echo '<b>Registration failed..<a href="register.php">please try again</a></b>';
 
}
?>

change yourdomainname.com to the actual domain name the application is hosted on.

md5() is a built-in function. It is a encryption technique for securing the user passwords from intruders.
rand( initialValue, finalValue) is a built-in PHP function which takes range as its parameter and generates a random number between them.

mail() is a built-in PHP function for sending emails.

General Syntax:
mail(To, Subject, Content, From)

Video Tutorial: Part 1


[youtube https://www.youtube.com/watch?v=BwgOn5sbK4c]

YouTube Link: https://www.youtube.com/watch?v=BwgOn5sbK4c [Watch the Video In Full Screen.]



Also look at: Email Verification in PHP: Part 2

You can purchase this simple script directly for as less as $1.95 get here.