Pages

Thursday 17 December 2015

Meteor Js continuous integration with Codeship and Jasmine Js.


Hello, Following are simple steps to implements continuous integration for Meteor Apps on Codeship with Jasmine testing.

Lest assume that you have Codeship account and you have adequate knowledge of Jamine testing. Here you need to add Jasmine test cases in your project directory.

Also you need to create folder .deploy/staging, this folder will contains mup.json file and settings,json file. You need to configure mup.json file for deployment of your meteor project.

Codeship steps:

   - Clone latest Meteor repo from BitBucket
   - Paste the following script to "Setup Command" section, because codeship needs to  install Meteor      and other packages

        nvm install 0.10.33

     nvm use 0.10.33

     curl -o meteor_install_script.sh https://install.meteor.com/

     chmod +x meteor_install_script.sh

     sed -i "s/type sudo >\/dev\/null 2>&1/\ false /g" meteor_install_script.sh

     ./meteor_install_script.sh

     export PATH=$PATH:~/.meteor/

     meteor --version

     npm install -g velocity-cli

     cd ~/src/bitbucket.org/https://username@bitbucket.org/username/reponame.git/ && meteor add sanjo:jasmine velocity:html-reporter


   - Paste following script to "Configure Test Pipelines" section

         meteor run --test


   - Setup deploy command in deployment section by choosing custom script
   
          npm install -g mup

     cd .deploy/staging

     mup deploy

Sunday 13 December 2015

Testing in JavaScript using Velocity

Testing in JavaScript using Velocity


Unit testing required for to ensure the reliability and maintainability of software, and more there is also methods like Test-Driven Development and Behavior Driven Development are avilable.


Velocity supports many javascript framework for testing it includes;

  1. Jasmine

  2. Cucumber

  3. Mocha


Jasmine supports most of the modes of testing in meteor. Following image shows testing modes and supported frameworks.



Jasmine


Each of the framework has advantages and disadvantage but Jasmine has unique fratures that makes it eady to use and get started with.

To use Jasmine, it does not required to have Node.js installed.


Installation


To install Jasmine run following command in your project directory.

meteor  add sanjo:jasmine

We  also need to install Velocity Reporter package to see test result.
meteor  add velocity:html-reporter


Suites and Specs


Each suite in turn contains a set of Expectations that compare the results of the test - called the actual - with the expected value. A Suite is defined by calling the describe() function. It takes two parameters: the name of the Suite, and the function which contains the calls to the expectation methods called Specs. These are defined using the it() method. Like describe(), it() also accepts a name and function parameter. The it() function parameter may contain variables and one or more calls to the expect() method. Used in conjunction with a Matcher function, these carry out the task of comparing the actual and expected values. Here's a simple example to demonstrate:

describe  ("the todo page : page contents", function() {
     
   	it  ("should include a page title of 'Todo List'", 		function()  {
     		expect($('title').text()).toEqual('Todo  List');
   	});


   	it  ("should include a page heading of 'Todo List'",  	function() {
     		expect($('h1').text()).toEqual('Todo  List');
   	});
});


  Put  above code in  /test/jasmine/client/integration/todos/page-contents-spec.js,  Jasmine  supports folder structures.   


Pre-defined Matchers

In the above example, the toBeGreaterThan() method is a matcher. It represents a comparison such as ">" using plain English. There are many other matchers available, including:

  • toBe: represents the exact equality (===) operator.

  • toEqual: represents the regular equality (==) operator.

  • toMatch: calls the RegExp match() method behind the scenes to compare string data.

  • toBeDefined: opposite of the JS "undefined" constant.

  • toBeUndefined: tests the actual against "undefined".

  • toBeNull: tests the actual against a null value - useful for certain functions that may return null, like those of regular expressions (same as toBe(null))

  • toBeTruthy: simulates JavaScript boolean casting.

  • toBeFalsy: like toBeTruthy, but tests against anything that evaluates to false, such as empty strings, zero, undefined, etc…

  • toContain: performs a search on an array for the actual value.

  • toBeLessThan/toBeGreaterThan: for numerical comparisons.

  • toBeCloseTo: for floating point comparisons.

  • toThrow: for catching expected exceptions.

Example

Put follwing code in demoapplication.css

<head>
    <title>jasminetest</title>
</head>
<body>
<h1>Welcome  to Meteor!</h1>
	{{>  hello}}
</body>
<template  name="hello">
    <button  id="clickButton">Click Me</button>
    <p  id="buttonText">You've pressed the button  {{counter}} 		times.</p>
</template>

Put follwing code in demoapplication.js

if  (Meteor.isClient) {
    //  counter starts at 0
    Session.setDefault('counter',  0);
    Template.hello.helpers({
        counter:  function () {
            return  Session.get('counter');
        }
    });
    Template.hello.events({
        'click  button': function () {
            //  increment the counter when button is clicked
            Session.set('counter',  Session.get('counter') + 			1);
        }
    });
}


Write following tets to check counter display proper or not


inside tests/jasmine/cleint/integration/sample/buttonSpec.js


describe('clicking  the button', function () {
    //  reset the counter before each test
    beforeEach(function()  {
        Session.set('counter',  0);
    });
    it('should  show how many times the button was pressed', 	function () {
        //  Get the text we are testing
        var  text = $('p#buttonText').text();
         
       //  assert that we see 'You've pressed the button 			times.'
        expect(text).toEqual("You've  pressed the button 0 			times.");
    });
});


Output:



Friday 22 May 2015

Link List formation

Algorithm


node *n;
n=(node*)malloc(sizeof(node));
n->data=x,y,z;
n->next=21,22,Null;
C program of link list

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct newnode
{
int number;
struct newnode *nextnode;
};
struct newnode *firstnode;
void linklist()
{
char ch='a';
struct newnode *ptr,*n;
while(ch!='n')
{
printf("\nEnter elements");
n=(struct newnode*)malloc(sizeof(struct newnode));
scanf("%d",&n->nnumber);
n->nextnode=0;
if(firstnode==0)
{
firstnode=n;
}
else
{
for(ptr=firstnode ;ptr->nextnode!=0;ptr=ptr->nextnode);
{
ptr->nextnode=n;
}
}
printf("\npress y for continue and n for no");
ch=getch();
}
}
void display()
{
struct newnode *ptr;
printf("Elements are");
for(ptr=firstnode;ptr!=0;ptr=ptr->nextnode)
{
printf("\n%d",ptr->nnumber);
}
}
void main()
{
clrscr();
firstnode=0;
linklist();
display();
getch();
}

Wednesday 20 May 2015

Android splash screen tutorial

It is best way to represent your logo or show start up image until all data are not loaded to the application or first page.
To understand the splash screen you must have a knowledge of Thread in java, because splash scree is appear for only some milliseconds (3000 i.e 3 secs) which means running thread for some time and after that we have to terminate it.

Now lets start the implementation of splash screen.

create new layout file and copy following code inside it.

activity_splash_screen.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/appsplash"
    android:orientation="vertical" >
</LinearLayout>

in above i have add image in background of LinearLayout. So replace it with your image.

Add new class file for splash sceeen.

SplashScreen.java

package com.ilearn.xtreme;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;

public class SplashScreen extends Activity {

    // Splash screen timer in milliseconds
    private static int SPLASH_TIME_OUT = 3000;
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_scren);
       
        
        new Handler().postDelayed(new Runnable() {


            @Override
            public void run() {
                // This method will be executed once the timer is over and name of target activity
              
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(i);

                // close this activity
                finish();
            }
        }, SPLASH_TIME_OUT);
    }

}


Dont forget to make this activity as launcher activity in manifest file by adding following code.

<activity
.........some code
<intent-filter>
 <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
.........some code
</activity>


screenshot of output is as follows





share it and enjoy.
comment wherever you stuck thank you :)

Android Webview with forward backward and reload page tutorial

Webview in android is builtin tool to create application with web interface. It allows us to include webpage within the app without opening browser.
This tutorial includes webview with forward,backward and reload control.

we will start with creating one layout file.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/relativeLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        
        
        <EditText
            android:id="@+id/edit_search"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="3dp"
            android:layout_marginRight="3dp"
            android:layout_marginTop="3dp"
            android:hint="Search Url"
            android:paddingBottom="5dp"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:paddingTop="5dp" />

        <Button
            android:id="@+id/btnsearch"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignRight="@+id/edit_search"
            android:layout_centerVertical="true"
            android:layout_marginRight="17dp"
            android:background="@drawable/search_icon"
            android:gravity="right"
            android:paddingBottom="5dp"
            android:paddingRight="5dp"
            android:paddingTop="5dp" />

    </RelativeLayout>



    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="410dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/relativeLayout2"
        android:background="#ffffff" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true" />


</RelativeLayout>



for adding menus add menu item in res/menu/main.xml
I have added image icon for menu so you can add your own icons in drawable folder.

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.phenomax.xtreme.MainActivity" >

    <item
        android:id="@+id/action_settings"
        android:showAsAction="always"
        android:icon="@drawable/ic_menu_settings"/>
    
     <item
        android:id="@+id/backward"
        android:showAsAction="always"
        android:icon="@drawable/backward"/>
     <item
        android:id="@+id/forward"
        android:showAsAction="always"
        android:icon="@drawable/forward"/>
     <item
        android:id="@+id/reload"
        android:showAsAction="always"
        android:icon="@drawable/reload"/>
      <item
        android:id="@+id/appicon"
        android:showAsAction="always"
        android:icon="@drawable/app_icon"/>
    


</menu>









Create class file for webview. and copy paste following code.

MainActivity.java

package com.ilearn.xtreme;


import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.*;

public class MainActivity extends Activity {
    

WebView web;
ProgressBar progressBar;
ImageButton backw;
ImageButton forw;
ImageButton reload;
ImageButton appbtn;
Button search;
EditText searchurl;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        web = (WebView) findViewById(R.id.webView1);
     
        searchurl=(EditText)findViewById(R.id.edit_search);
        
        
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
           
            searchurl=(EditText)findViewById(R.id.edit_search);
            String urlname=searchurl.getText().toString();
           
            progressBar = (ProgressBar) findViewById(R.id.progressBar);
                progressBar.setProgress(30); 
           
            web.setWebViewClient(new myWebClient());
                web.getSettings().setJavaScriptEnabled(true);
                web.getSettings().setLoadWithOverviewMode(true);
                web.getSettings().setUseWideViewPort(true);
                web.getSettings().setBuiltInZoomControls(true);
                web.loadUrl("http://"+urlname);
                  
                   
            }
          });
        
        
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) { //this method is used for adding menu items to the Activity
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) { //this method is used for handling menu items' events
    // Handle item selection
    switch (item.getItemId()) {

    case R.id.backward:
    if(web.canGoBack()) { //for go back history
    web.goBack();
    }
    return true;

    case R.id.forward:
    if(web.canGoForward()) {  //for go forward
    web.goForward();
    }
    return true;
    
    case R.id.reload:
        {
        web.reload();
        }
        return true;
        
    case R.id.action_settings:
    {
    
    }
    return true;

    default:
    return super.onOptionsItemSelected(item);
    }
    }
    
    
    

    public class myWebClient extends WebViewClient
    {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
    // TODO Auto-generated method stub
    super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // TODO Auto-generated method stub
                progressBar.setVisibility(View.VISIBLE);
                
    view.loadUrl(url);
    return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {
    // TODO Auto-generated method stub
    super.onPageFinished(view, url);

    progressBar.setVisibility(View.GONE);
    }
    }

    // To handle "Back" key press event for WebView to go back to previous screen.
public boolean goback(int keyCode, KeyEvent event)
{
if ( web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}

}


Now in the manifest file dont forget to add permission for Internet Access.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ilearn.xtreme"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ilearn.xtreme.MainActivity"
            android:label="@string/notitle"
             android:icon="@drawable/noicon"
         >
          
          <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category                      android:name="android.intent.category.LAUNCHER" />

            </intent-filter>
  
        </activity>
        
    </application>


</manifest>



Monday 18 May 2015

Android JSON Parsing tutorial Using PHP and MySql Database and Display it on ListView

Today i am going to show tutorial how to parse JSON data to android and display it on ListView.
Here first of all we need to have php file that fetch data from MySql Database. 
PHP file will convert that data into JSON format.

json.php

<?php
$host = ""; // host of MySQL server
$user = ""; // MySQL user
$pwd = ""; // MySQL user's password
$db = ""; // database name

// Create connection
$con = mysqli_connect($host, $user, $pwd, $db);

// Check connection
if(mysqli_connect_errno($con)) {
    die("Failed to connect to MySQL: " . mysqli_connect_error());
}

// query the application data
$sql = "SELECT * FROM updates ORDER By id desc";
$result = mysqli_query($con, $sql);

// an array to save the application data
$rows = array();

// iterate to query result and add every rows into array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $rows[] = $row;
}

// close the database connection
mysqli_close($con);

// echo the application data in json format
echo '{"updates":' ,json_encode($rows),'}';


Now we need one layout file for android app.

activity_main.xml

 <RelativeLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#e8e8e8"  
  >

<ListView android:id="@+id/toplist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#e8e8e8"
        android:layout_marginLeft="7dp"
        android:layout_marginTop="5dp"
       android:layout_marginRight="7dp"
  />

 </RelativeLayout>


We need another xml file for elements for listview. Create another xml file inside res/layout folder, name it listview_item.xml

listview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/listitem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#f9c045"
        android:textSize="13sp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        />
</RelativeLayout>


for fetching the data we need to write one class file for GET and POST method to access JSON objects from Server.

JSONGet.java

package com.im.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONStudentParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONStudentParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}


Now its time for main coding that is java file that will fetch the data and display it on ListView.

MainActivity.java

package com.im.json;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.im.json.JSONGet;

public class Result extends Activity  {
  ListView list;

  ArrayList<HashMap<String, String>> reslist = new ArrayList<HashMap<String, String>>();
  
  private static String url = "http://localhost:8080/json.php";  //change to your server url
  
  private static final String TAG_RESULT = "updates";
  private static final String TAG_NAME = "mark";  //JSON tag name
  
  
  JSONArray android = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main.xml);
        getActionBar().setDisplayHomeAsUpEnabled(true);  // for up navigation
        reslist = new ArrayList<HashMap<String, String>>();
      
       
new parsedata().execute()
    }

    private class parsedata extends AsyncTask<String, String, JSONObject> {
       private ProgressDialog pDialog;
       
      
      @Override
        protected void onPreExecute() {
            super.onPreExecute();
             
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
      }
      @Override
        protected JSONObject doInBackground(String... args) {
       
        JSONStudentParser jParser1 = new JSONStudentParser();
      
        
        
        List<NameValuePair> params = new ArrayList<NameValuePair>();
 params.add(new BasicNameValuePair("no_parameter","")); //here we do not want want to                                                            fetch data on such condition hence parameter will be blank.
       JSONObject json = jParser1.getJSONFromUrl(url, params);
        
        return json;
      }
       @Override
         protected void onPostExecute(JSONObject json) {
         pDialog.dismiss();
         try {
  
            android = json.getJSONArray(TAG_RESULT);
            for(int i = 0; i < android.length(); i++){
            JSONObject c = android.getJSONObject(i);
  
            String name = c.getString(TAG_NAME);
            
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(TAG_NAME, name);
            
            reslist.add(map);
            list=(ListView)findViewById(R.id.toplist);
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, reslist,
                R.layout.listview_item,
                new String[] { TAG_NAME }, new int[] {R.id.listitem});
                list.setAdapter(adapter);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                       
                    }
                });
            }
            
             } catch (JSONException e) {
          e.printStackTrace();
        }
       }
    }
    
    
    
}


Enjoy :)

Share because share knowledge, get knowledge.

Comment if you find any error and ask if me you stuck.